repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
docker/docker-credential-helpers
credentials/credentials.go
Erase
func Erase(helper Helper, reader io.Reader) error { scanner := bufio.NewScanner(reader) buffer := new(bytes.Buffer) for scanner.Scan() { buffer.Write(scanner.Bytes()) } if err := scanner.Err(); err != nil && err != io.EOF { return err } serverURL := strings.TrimSpace(buffer.String()) if len(serverURL) == 0 { return NewErrCredentialsMissingServerURL() } return helper.Delete(serverURL) }
go
func Erase(helper Helper, reader io.Reader) error { scanner := bufio.NewScanner(reader) buffer := new(bytes.Buffer) for scanner.Scan() { buffer.Write(scanner.Bytes()) } if err := scanner.Err(); err != nil && err != io.EOF { return err } serverURL := strings.TrimSpace(buffer.String()) if len(serverURL) == 0 { return NewErrCredentialsMissingServerURL() } return helper.Delete(serverURL) }
[ "func", "Erase", "(", "helper", "Helper", ",", "reader", "io", ".", "Reader", ")", "error", "{", "scanner", ":=", "bufio", ".", "NewScanner", "(", "reader", ")", "\n\n", "buffer", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "for", "scanner", ".", "Scan", "(", ")", "{", "buffer", ".", "Write", "(", "scanner", ".", "Bytes", "(", ")", ")", "\n", "}", "\n\n", "if", "err", ":=", "scanner", ".", "Err", "(", ")", ";", "err", "!=", "nil", "&&", "err", "!=", "io", ".", "EOF", "{", "return", "err", "\n", "}", "\n\n", "serverURL", ":=", "strings", ".", "TrimSpace", "(", "buffer", ".", "String", "(", ")", ")", "\n", "if", "len", "(", "serverURL", ")", "==", "0", "{", "return", "NewErrCredentialsMissingServerURL", "(", ")", "\n", "}", "\n\n", "return", "helper", ".", "Delete", "(", "serverURL", ")", "\n", "}" ]
// Erase removes credentials from the store. // The reader must contain the server URL to remove.
[ "Erase", "removes", "credentials", "from", "the", "store", ".", "The", "reader", "must", "contain", "the", "server", "URL", "to", "remove", "." ]
beda055c573157c4cea5c7f5fe8bec04e9061b19
https://github.com/docker/docker-credential-helpers/blob/beda055c573157c4cea5c7f5fe8bec04e9061b19/credentials/credentials.go#L152-L170
train
docker/docker-credential-helpers
credentials/credentials.go
List
func List(helper Helper, writer io.Writer) error { accts, err := helper.List() if err != nil { return err } return json.NewEncoder(writer).Encode(accts) }
go
func List(helper Helper, writer io.Writer) error { accts, err := helper.List() if err != nil { return err } return json.NewEncoder(writer).Encode(accts) }
[ "func", "List", "(", "helper", "Helper", ",", "writer", "io", ".", "Writer", ")", "error", "{", "accts", ",", "err", ":=", "helper", ".", "List", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "json", ".", "NewEncoder", "(", "writer", ")", ".", "Encode", "(", "accts", ")", "\n", "}" ]
//List returns all the serverURLs of keys in //the OS store as a list of strings
[ "List", "returns", "all", "the", "serverURLs", "of", "keys", "in", "the", "OS", "store", "as", "a", "list", "of", "strings" ]
beda055c573157c4cea5c7f5fe8bec04e9061b19
https://github.com/docker/docker-credential-helpers/blob/beda055c573157c4cea5c7f5fe8bec04e9061b19/credentials/credentials.go#L174-L180
train
docker/docker-credential-helpers
credentials/credentials.go
PrintVersion
func PrintVersion(writer io.Writer) error { fmt.Fprintln(writer, Version) return nil }
go
func PrintVersion(writer io.Writer) error { fmt.Fprintln(writer, Version) return nil }
[ "func", "PrintVersion", "(", "writer", "io", ".", "Writer", ")", "error", "{", "fmt", ".", "Fprintln", "(", "writer", ",", "Version", ")", "\n", "return", "nil", "\n", "}" ]
//PrintVersion outputs the current version.
[ "PrintVersion", "outputs", "the", "current", "version", "." ]
beda055c573157c4cea5c7f5fe8bec04e9061b19
https://github.com/docker/docker-credential-helpers/blob/beda055c573157c4cea5c7f5fe8bec04e9061b19/credentials/credentials.go#L183-L186
train
docker/docker-credential-helpers
wincred/wincred_windows.go
Add
func (h Wincred) Add(creds *credentials.Credentials) error { credsLabels := []byte(credentials.CredsLabel) g := winc.NewGenericCredential(creds.ServerURL) g.UserName = creds.Username g.CredentialBlob = []byte(creds.Secret) g.Persist = winc.PersistLocalMachine g.Attributes = []winc.CredentialAttribute{{Keyword: "label", Value: credsLabels}} return g.Write() }
go
func (h Wincred) Add(creds *credentials.Credentials) error { credsLabels := []byte(credentials.CredsLabel) g := winc.NewGenericCredential(creds.ServerURL) g.UserName = creds.Username g.CredentialBlob = []byte(creds.Secret) g.Persist = winc.PersistLocalMachine g.Attributes = []winc.CredentialAttribute{{Keyword: "label", Value: credsLabels}} return g.Write() }
[ "func", "(", "h", "Wincred", ")", "Add", "(", "creds", "*", "credentials", ".", "Credentials", ")", "error", "{", "credsLabels", ":=", "[", "]", "byte", "(", "credentials", ".", "CredsLabel", ")", "\n", "g", ":=", "winc", ".", "NewGenericCredential", "(", "creds", ".", "ServerURL", ")", "\n", "g", ".", "UserName", "=", "creds", ".", "Username", "\n", "g", ".", "CredentialBlob", "=", "[", "]", "byte", "(", "creds", ".", "Secret", ")", "\n", "g", ".", "Persist", "=", "winc", ".", "PersistLocalMachine", "\n", "g", ".", "Attributes", "=", "[", "]", "winc", ".", "CredentialAttribute", "{", "{", "Keyword", ":", "\"", "\"", ",", "Value", ":", "credsLabels", "}", "}", "\n\n", "return", "g", ".", "Write", "(", ")", "\n", "}" ]
// Add adds new credentials to the windows credentials manager.
[ "Add", "adds", "new", "credentials", "to", "the", "windows", "credentials", "manager", "." ]
beda055c573157c4cea5c7f5fe8bec04e9061b19
https://github.com/docker/docker-credential-helpers/blob/beda055c573157c4cea5c7f5fe8bec04e9061b19/wincred/wincred_windows.go#L17-L26
train
docker/docker-credential-helpers
wincred/wincred_windows.go
Delete
func (h Wincred) Delete(serverURL string) error { g, err := winc.GetGenericCredential(serverURL) if g == nil { return nil } if err != nil { return err } return g.Delete() }
go
func (h Wincred) Delete(serverURL string) error { g, err := winc.GetGenericCredential(serverURL) if g == nil { return nil } if err != nil { return err } return g.Delete() }
[ "func", "(", "h", "Wincred", ")", "Delete", "(", "serverURL", "string", ")", "error", "{", "g", ",", "err", ":=", "winc", ".", "GetGenericCredential", "(", "serverURL", ")", "\n", "if", "g", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "g", ".", "Delete", "(", ")", "\n", "}" ]
// Delete removes credentials from the windows credentials manager.
[ "Delete", "removes", "credentials", "from", "the", "windows", "credentials", "manager", "." ]
beda055c573157c4cea5c7f5fe8bec04e9061b19
https://github.com/docker/docker-credential-helpers/blob/beda055c573157c4cea5c7f5fe8bec04e9061b19/wincred/wincred_windows.go#L29-L38
train
docker/docker-credential-helpers
wincred/wincred_windows.go
Get
func (h Wincred) Get(serverURL string) (string, string, error) { target, err := getTarget(serverURL) if err != nil { return "", "", err } else if target == "" { return "", "", credentials.NewErrCredentialsNotFound() } g, _ := winc.GetGenericCredential(target) if g == nil { return "", "", credentials.NewErrCredentialsNotFound() } for _, attr := range g.Attributes { if strings.Compare(attr.Keyword, "label") == 0 && bytes.Compare(attr.Value, []byte(credentials.CredsLabel)) == 0 { return g.UserName, string(g.CredentialBlob), nil } } return "", "", credentials.NewErrCredentialsNotFound() }
go
func (h Wincred) Get(serverURL string) (string, string, error) { target, err := getTarget(serverURL) if err != nil { return "", "", err } else if target == "" { return "", "", credentials.NewErrCredentialsNotFound() } g, _ := winc.GetGenericCredential(target) if g == nil { return "", "", credentials.NewErrCredentialsNotFound() } for _, attr := range g.Attributes { if strings.Compare(attr.Keyword, "label") == 0 && bytes.Compare(attr.Value, []byte(credentials.CredsLabel)) == 0 { return g.UserName, string(g.CredentialBlob), nil } } return "", "", credentials.NewErrCredentialsNotFound() }
[ "func", "(", "h", "Wincred", ")", "Get", "(", "serverURL", "string", ")", "(", "string", ",", "string", ",", "error", ")", "{", "target", ",", "err", ":=", "getTarget", "(", "serverURL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "\"", "\"", ",", "err", "\n", "}", "else", "if", "target", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "\"", "\"", ",", "credentials", ".", "NewErrCredentialsNotFound", "(", ")", "\n", "}", "\n\n", "g", ",", "_", ":=", "winc", ".", "GetGenericCredential", "(", "target", ")", "\n", "if", "g", "==", "nil", "{", "return", "\"", "\"", ",", "\"", "\"", ",", "credentials", ".", "NewErrCredentialsNotFound", "(", ")", "\n", "}", "\n\n", "for", "_", ",", "attr", ":=", "range", "g", ".", "Attributes", "{", "if", "strings", ".", "Compare", "(", "attr", ".", "Keyword", ",", "\"", "\"", ")", "==", "0", "&&", "bytes", ".", "Compare", "(", "attr", ".", "Value", ",", "[", "]", "byte", "(", "credentials", ".", "CredsLabel", ")", ")", "==", "0", "{", "return", "g", ".", "UserName", ",", "string", "(", "g", ".", "CredentialBlob", ")", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "\"", "\"", ",", "\"", "\"", ",", "credentials", ".", "NewErrCredentialsNotFound", "(", ")", "\n", "}" ]
// Get retrieves credentials from the windows credentials manager.
[ "Get", "retrieves", "credentials", "from", "the", "windows", "credentials", "manager", "." ]
beda055c573157c4cea5c7f5fe8bec04e9061b19
https://github.com/docker/docker-credential-helpers/blob/beda055c573157c4cea5c7f5fe8bec04e9061b19/wincred/wincred_windows.go#L41-L62
train
docker/docker-credential-helpers
wincred/wincred_windows.go
List
func (h Wincred) List() (map[string]string, error) { creds, err := winc.List() if err != nil { return nil, err } resp := make(map[string]string) for i := range creds { attrs := creds[i].Attributes for _, attr := range attrs { if strings.Compare(attr.Keyword, "label") == 0 && bytes.Compare(attr.Value, []byte(credentials.CredsLabel)) == 0 { resp[creds[i].TargetName] = creds[i].UserName } } } return resp, nil }
go
func (h Wincred) List() (map[string]string, error) { creds, err := winc.List() if err != nil { return nil, err } resp := make(map[string]string) for i := range creds { attrs := creds[i].Attributes for _, attr := range attrs { if strings.Compare(attr.Keyword, "label") == 0 && bytes.Compare(attr.Value, []byte(credentials.CredsLabel)) == 0 { resp[creds[i].TargetName] = creds[i].UserName } } } return resp, nil }
[ "func", "(", "h", "Wincred", ")", "List", "(", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "creds", ",", "err", ":=", "winc", ".", "List", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "resp", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "for", "i", ":=", "range", "creds", "{", "attrs", ":=", "creds", "[", "i", "]", ".", "Attributes", "\n", "for", "_", ",", "attr", ":=", "range", "attrs", "{", "if", "strings", ".", "Compare", "(", "attr", ".", "Keyword", ",", "\"", "\"", ")", "==", "0", "&&", "bytes", ".", "Compare", "(", "attr", ".", "Value", ",", "[", "]", "byte", "(", "credentials", ".", "CredsLabel", ")", ")", "==", "0", "{", "resp", "[", "creds", "[", "i", "]", ".", "TargetName", "]", "=", "creds", "[", "i", "]", ".", "UserName", "\n", "}", "\n", "}", "\n\n", "}", "\n\n", "return", "resp", ",", "nil", "\n", "}" ]
// List returns the stored URLs and corresponding usernames for a given credentials label.
[ "List", "returns", "the", "stored", "URLs", "and", "corresponding", "usernames", "for", "a", "given", "credentials", "label", "." ]
beda055c573157c4cea5c7f5fe8bec04e9061b19
https://github.com/docker/docker-credential-helpers/blob/beda055c573157c4cea5c7f5fe8bec04e9061b19/wincred/wincred_windows.go#L130-L150
train
docker/docker-credential-helpers
pass/pass_linux.go
listPassDir
func listPassDir(args ...string) ([]os.FileInfo, error) { passDir := getPassDir() p := path.Join(append([]string{passDir, PASS_FOLDER}, args...)...) contents, err := ioutil.ReadDir(p) if err != nil { if os.IsNotExist(err) { return []os.FileInfo{}, nil } return nil, err } return contents, nil }
go
func listPassDir(args ...string) ([]os.FileInfo, error) { passDir := getPassDir() p := path.Join(append([]string{passDir, PASS_FOLDER}, args...)...) contents, err := ioutil.ReadDir(p) if err != nil { if os.IsNotExist(err) { return []os.FileInfo{}, nil } return nil, err } return contents, nil }
[ "func", "listPassDir", "(", "args", "...", "string", ")", "(", "[", "]", "os", ".", "FileInfo", ",", "error", ")", "{", "passDir", ":=", "getPassDir", "(", ")", "\n", "p", ":=", "path", ".", "Join", "(", "append", "(", "[", "]", "string", "{", "passDir", ",", "PASS_FOLDER", "}", ",", "args", "...", ")", "...", ")", "\n", "contents", ",", "err", ":=", "ioutil", ".", "ReadDir", "(", "p", ")", "\n", "if", "err", "!=", "nil", "{", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "[", "]", "os", ".", "FileInfo", "{", "}", ",", "nil", "\n", "}", "\n\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "contents", ",", "nil", "\n", "}" ]
// listPassDir lists all the contents of a directory in the password store. // Pass uses fancy unicode to emit stuff to stdout, so rather than try // and parse this, let's just look at the directory structure instead.
[ "listPassDir", "lists", "all", "the", "contents", "of", "a", "directory", "in", "the", "password", "store", ".", "Pass", "uses", "fancy", "unicode", "to", "emit", "stuff", "to", "stdout", "so", "rather", "than", "try", "and", "parse", "this", "let", "s", "just", "look", "at", "the", "directory", "structure", "instead", "." ]
beda055c573157c4cea5c7f5fe8bec04e9061b19
https://github.com/docker/docker-credential-helpers/blob/beda055c573157c4cea5c7f5fe8bec04e9061b19/pass/pass_linux.go#L115-L128
train
stianeikeland/go-rpio
rpio.go
WritePin
func WritePin(pin Pin, state State) { p := uint8(pin) // Set register, 7 / 8 depending on bank // Clear register, 10 / 11 depending on bank setReg := p/32 + 7 clearReg := p/32 + 10 memlock.Lock() if state == Low { gpioMem[clearReg] = 1 << (p & 31) } else { gpioMem[setReg] = 1 << (p & 31) } memlock.Unlock() // not deferring saves ~600ns }
go
func WritePin(pin Pin, state State) { p := uint8(pin) // Set register, 7 / 8 depending on bank // Clear register, 10 / 11 depending on bank setReg := p/32 + 7 clearReg := p/32 + 10 memlock.Lock() if state == Low { gpioMem[clearReg] = 1 << (p & 31) } else { gpioMem[setReg] = 1 << (p & 31) } memlock.Unlock() // not deferring saves ~600ns }
[ "func", "WritePin", "(", "pin", "Pin", ",", "state", "State", ")", "{", "p", ":=", "uint8", "(", "pin", ")", "\n\n", "// Set register, 7 / 8 depending on bank", "// Clear register, 10 / 11 depending on bank", "setReg", ":=", "p", "/", "32", "+", "7", "\n", "clearReg", ":=", "p", "/", "32", "+", "10", "\n\n", "memlock", ".", "Lock", "(", ")", "\n\n", "if", "state", "==", "Low", "{", "gpioMem", "[", "clearReg", "]", "=", "1", "<<", "(", "p", "&", "31", ")", "\n", "}", "else", "{", "gpioMem", "[", "setReg", "]", "=", "1", "<<", "(", "p", "&", "31", ")", "\n", "}", "\n", "memlock", ".", "Unlock", "(", ")", "// not deferring saves ~600ns", "\n", "}" ]
// WritePin sets a given pin High or Low // by setting the clear or set registers respectively
[ "WritePin", "sets", "a", "given", "pin", "High", "or", "Low", "by", "setting", "the", "clear", "or", "set", "registers", "respectively" ]
a36b96d0b1a40b37017d64875275e7e6312408c7
https://github.com/stianeikeland/go-rpio/blob/a36b96d0b1a40b37017d64875275e7e6312408c7/rpio.go#L319-L335
train
stianeikeland/go-rpio
rpio.go
ReadPin
func ReadPin(pin Pin) State { // Input level register offset (13 / 14 depending on bank) levelReg := uint8(pin)/32 + 13 if (gpioMem[levelReg] & (1 << uint8(pin&31))) != 0 { return High } return Low }
go
func ReadPin(pin Pin) State { // Input level register offset (13 / 14 depending on bank) levelReg := uint8(pin)/32 + 13 if (gpioMem[levelReg] & (1 << uint8(pin&31))) != 0 { return High } return Low }
[ "func", "ReadPin", "(", "pin", "Pin", ")", "State", "{", "// Input level register offset (13 / 14 depending on bank)", "levelReg", ":=", "uint8", "(", "pin", ")", "/", "32", "+", "13", "\n\n", "if", "(", "gpioMem", "[", "levelReg", "]", "&", "(", "1", "<<", "uint8", "(", "pin", "&", "31", ")", ")", ")", "!=", "0", "{", "return", "High", "\n", "}", "\n\n", "return", "Low", "\n", "}" ]
// ReadPin reads the state of a pin
[ "ReadPin", "reads", "the", "state", "of", "a", "pin" ]
a36b96d0b1a40b37017d64875275e7e6312408c7
https://github.com/stianeikeland/go-rpio/blob/a36b96d0b1a40b37017d64875275e7e6312408c7/rpio.go#L338-L347
train
stianeikeland/go-rpio
rpio.go
Close
func Close() error { EnableIRQs(irqsBackup) // Return IRQs to state where it was before - just to be nice memlock.Lock() defer memlock.Unlock() for _, mem8 := range [][]uint8{gpioMem8, clkMem8, pwmMem8, spiMem8, intrMem8} { if err := syscall.Munmap(mem8); err != nil { return err } } return nil }
go
func Close() error { EnableIRQs(irqsBackup) // Return IRQs to state where it was before - just to be nice memlock.Lock() defer memlock.Unlock() for _, mem8 := range [][]uint8{gpioMem8, clkMem8, pwmMem8, spiMem8, intrMem8} { if err := syscall.Munmap(mem8); err != nil { return err } } return nil }
[ "func", "Close", "(", ")", "error", "{", "EnableIRQs", "(", "irqsBackup", ")", "// Return IRQs to state where it was before - just to be nice", "\n\n", "memlock", ".", "Lock", "(", ")", "\n", "defer", "memlock", ".", "Unlock", "(", ")", "\n", "for", "_", ",", "mem8", ":=", "range", "[", "]", "[", "]", "uint8", "{", "gpioMem8", ",", "clkMem8", ",", "pwmMem8", ",", "spiMem8", ",", "intrMem8", "}", "{", "if", "err", ":=", "syscall", ".", "Munmap", "(", "mem8", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Close unmaps GPIO memory
[ "Close", "unmaps", "GPIO", "memory" ]
a36b96d0b1a40b37017d64875275e7e6312408c7
https://github.com/stianeikeland/go-rpio/blob/a36b96d0b1a40b37017d64875275e7e6312408c7/rpio.go#L702-L713
train
stianeikeland/go-rpio
spi.go
SpiReceive
func SpiReceive(n int) []byte { data := make([]byte, n, n) SpiExchange(data) return data }
go
func SpiReceive(n int) []byte { data := make([]byte, n, n) SpiExchange(data) return data }
[ "func", "SpiReceive", "(", "n", "int", ")", "[", "]", "byte", "{", "data", ":=", "make", "(", "[", "]", "byte", ",", "n", ",", "n", ")", "\n", "SpiExchange", "(", "data", ")", "\n", "return", "data", "\n", "}" ]
// SpiReceive receives n bytes from slave. // // Note that n zeroed bytes are send to slave as side effect.
[ "SpiReceive", "receives", "n", "bytes", "from", "slave", ".", "Note", "that", "n", "zeroed", "bytes", "are", "send", "to", "slave", "as", "side", "effect", "." ]
a36b96d0b1a40b37017d64875275e7e6312408c7
https://github.com/stianeikeland/go-rpio/blob/a36b96d0b1a40b37017d64875275e7e6312408c7/spi.go#L124-L128
train
hashicorp/go-memdb
txn.go
readableIndex
func (txn *Txn) readableIndex(table, index string) *iradix.Txn { // Look for existing transaction if txn.write && txn.modified != nil { key := tableIndex{table, index} exist, ok := txn.modified[key] if ok { return exist } } // Create a read transaction path := indexPath(table, index) raw, _ := txn.rootTxn.Get(path) indexTxn := raw.(*iradix.Tree).Txn() return indexTxn }
go
func (txn *Txn) readableIndex(table, index string) *iradix.Txn { // Look for existing transaction if txn.write && txn.modified != nil { key := tableIndex{table, index} exist, ok := txn.modified[key] if ok { return exist } } // Create a read transaction path := indexPath(table, index) raw, _ := txn.rootTxn.Get(path) indexTxn := raw.(*iradix.Tree).Txn() return indexTxn }
[ "func", "(", "txn", "*", "Txn", ")", "readableIndex", "(", "table", ",", "index", "string", ")", "*", "iradix", ".", "Txn", "{", "// Look for existing transaction", "if", "txn", ".", "write", "&&", "txn", ".", "modified", "!=", "nil", "{", "key", ":=", "tableIndex", "{", "table", ",", "index", "}", "\n", "exist", ",", "ok", ":=", "txn", ".", "modified", "[", "key", "]", "\n", "if", "ok", "{", "return", "exist", "\n", "}", "\n", "}", "\n\n", "// Create a read transaction", "path", ":=", "indexPath", "(", "table", ",", "index", ")", "\n", "raw", ",", "_", ":=", "txn", ".", "rootTxn", ".", "Get", "(", "path", ")", "\n", "indexTxn", ":=", "raw", ".", "(", "*", "iradix", ".", "Tree", ")", ".", "Txn", "(", ")", "\n", "return", "indexTxn", "\n", "}" ]
// readableIndex returns a transaction usable for reading the given // index in a table. If a write transaction is in progress, we may need // to use an existing modified txn.
[ "readableIndex", "returns", "a", "transaction", "usable", "for", "reading", "the", "given", "index", "in", "a", "table", ".", "If", "a", "write", "transaction", "is", "in", "progress", "we", "may", "need", "to", "use", "an", "existing", "modified", "txn", "." ]
10278d3759e27502b741e52c7d8115d892e7723a
https://github.com/hashicorp/go-memdb/blob/10278d3759e27502b741e52c7d8115d892e7723a/txn.go#L42-L57
train
hashicorp/go-memdb
txn.go
writableIndex
func (txn *Txn) writableIndex(table, index string) *iradix.Txn { if txn.modified == nil { txn.modified = make(map[tableIndex]*iradix.Txn) } // Look for existing transaction key := tableIndex{table, index} exist, ok := txn.modified[key] if ok { return exist } // Start a new transaction path := indexPath(table, index) raw, _ := txn.rootTxn.Get(path) indexTxn := raw.(*iradix.Tree).Txn() // If we are the primary DB, enable mutation tracking. Snapshots should // not notify, otherwise we will trigger watches on the primary DB when // the writes will not be visible. indexTxn.TrackMutate(txn.db.primary) // Keep this open for the duration of the txn txn.modified[key] = indexTxn return indexTxn }
go
func (txn *Txn) writableIndex(table, index string) *iradix.Txn { if txn.modified == nil { txn.modified = make(map[tableIndex]*iradix.Txn) } // Look for existing transaction key := tableIndex{table, index} exist, ok := txn.modified[key] if ok { return exist } // Start a new transaction path := indexPath(table, index) raw, _ := txn.rootTxn.Get(path) indexTxn := raw.(*iradix.Tree).Txn() // If we are the primary DB, enable mutation tracking. Snapshots should // not notify, otherwise we will trigger watches on the primary DB when // the writes will not be visible. indexTxn.TrackMutate(txn.db.primary) // Keep this open for the duration of the txn txn.modified[key] = indexTxn return indexTxn }
[ "func", "(", "txn", "*", "Txn", ")", "writableIndex", "(", "table", ",", "index", "string", ")", "*", "iradix", ".", "Txn", "{", "if", "txn", ".", "modified", "==", "nil", "{", "txn", ".", "modified", "=", "make", "(", "map", "[", "tableIndex", "]", "*", "iradix", ".", "Txn", ")", "\n", "}", "\n\n", "// Look for existing transaction", "key", ":=", "tableIndex", "{", "table", ",", "index", "}", "\n", "exist", ",", "ok", ":=", "txn", ".", "modified", "[", "key", "]", "\n", "if", "ok", "{", "return", "exist", "\n", "}", "\n\n", "// Start a new transaction", "path", ":=", "indexPath", "(", "table", ",", "index", ")", "\n", "raw", ",", "_", ":=", "txn", ".", "rootTxn", ".", "Get", "(", "path", ")", "\n", "indexTxn", ":=", "raw", ".", "(", "*", "iradix", ".", "Tree", ")", ".", "Txn", "(", ")", "\n\n", "// If we are the primary DB, enable mutation tracking. Snapshots should", "// not notify, otherwise we will trigger watches on the primary DB when", "// the writes will not be visible.", "indexTxn", ".", "TrackMutate", "(", "txn", ".", "db", ".", "primary", ")", "\n\n", "// Keep this open for the duration of the txn", "txn", ".", "modified", "[", "key", "]", "=", "indexTxn", "\n", "return", "indexTxn", "\n", "}" ]
// writableIndex returns a transaction usable for modifying the // given index in a table.
[ "writableIndex", "returns", "a", "transaction", "usable", "for", "modifying", "the", "given", "index", "in", "a", "table", "." ]
10278d3759e27502b741e52c7d8115d892e7723a
https://github.com/hashicorp/go-memdb/blob/10278d3759e27502b741e52c7d8115d892e7723a/txn.go#L61-L86
train
hashicorp/go-memdb
txn.go
Abort
func (txn *Txn) Abort() { // Noop for a read transaction if !txn.write { return } // Check if already aborted or committed if txn.rootTxn == nil { return } // Clear the txn txn.rootTxn = nil txn.modified = nil // Release the writer lock since this is invalid txn.db.writer.Unlock() }
go
func (txn *Txn) Abort() { // Noop for a read transaction if !txn.write { return } // Check if already aborted or committed if txn.rootTxn == nil { return } // Clear the txn txn.rootTxn = nil txn.modified = nil // Release the writer lock since this is invalid txn.db.writer.Unlock() }
[ "func", "(", "txn", "*", "Txn", ")", "Abort", "(", ")", "{", "// Noop for a read transaction", "if", "!", "txn", ".", "write", "{", "return", "\n", "}", "\n\n", "// Check if already aborted or committed", "if", "txn", ".", "rootTxn", "==", "nil", "{", "return", "\n", "}", "\n\n", "// Clear the txn", "txn", ".", "rootTxn", "=", "nil", "\n", "txn", ".", "modified", "=", "nil", "\n\n", "// Release the writer lock since this is invalid", "txn", ".", "db", ".", "writer", ".", "Unlock", "(", ")", "\n", "}" ]
// Abort is used to cancel this transaction. // This is a noop for read transactions.
[ "Abort", "is", "used", "to", "cancel", "this", "transaction", ".", "This", "is", "a", "noop", "for", "read", "transactions", "." ]
10278d3759e27502b741e52c7d8115d892e7723a
https://github.com/hashicorp/go-memdb/blob/10278d3759e27502b741e52c7d8115d892e7723a/txn.go#L90-L107
train
hashicorp/go-memdb
txn.go
Commit
func (txn *Txn) Commit() { // Noop for a read transaction if !txn.write { return } // Check if already aborted or committed if txn.rootTxn == nil { return } // Commit each sub-transaction scoped to (table, index) for key, subTxn := range txn.modified { path := indexPath(key.Table, key.Index) final := subTxn.CommitOnly() txn.rootTxn.Insert(path, final) } // Update the root of the DB newRoot := txn.rootTxn.CommitOnly() atomic.StorePointer(&txn.db.root, unsafe.Pointer(newRoot)) // Now issue all of the mutation updates (this is safe to call // even if mutation tracking isn't enabled); we do this after // the root pointer is swapped so that waking responders will // see the new state. for _, subTxn := range txn.modified { subTxn.Notify() } txn.rootTxn.Notify() // Clear the txn txn.rootTxn = nil txn.modified = nil // Release the writer lock since this is invalid txn.db.writer.Unlock() // Run the deferred functions, if any for i := len(txn.after); i > 0; i-- { fn := txn.after[i-1] fn() } }
go
func (txn *Txn) Commit() { // Noop for a read transaction if !txn.write { return } // Check if already aborted or committed if txn.rootTxn == nil { return } // Commit each sub-transaction scoped to (table, index) for key, subTxn := range txn.modified { path := indexPath(key.Table, key.Index) final := subTxn.CommitOnly() txn.rootTxn.Insert(path, final) } // Update the root of the DB newRoot := txn.rootTxn.CommitOnly() atomic.StorePointer(&txn.db.root, unsafe.Pointer(newRoot)) // Now issue all of the mutation updates (this is safe to call // even if mutation tracking isn't enabled); we do this after // the root pointer is swapped so that waking responders will // see the new state. for _, subTxn := range txn.modified { subTxn.Notify() } txn.rootTxn.Notify() // Clear the txn txn.rootTxn = nil txn.modified = nil // Release the writer lock since this is invalid txn.db.writer.Unlock() // Run the deferred functions, if any for i := len(txn.after); i > 0; i-- { fn := txn.after[i-1] fn() } }
[ "func", "(", "txn", "*", "Txn", ")", "Commit", "(", ")", "{", "// Noop for a read transaction", "if", "!", "txn", ".", "write", "{", "return", "\n", "}", "\n\n", "// Check if already aborted or committed", "if", "txn", ".", "rootTxn", "==", "nil", "{", "return", "\n", "}", "\n\n", "// Commit each sub-transaction scoped to (table, index)", "for", "key", ",", "subTxn", ":=", "range", "txn", ".", "modified", "{", "path", ":=", "indexPath", "(", "key", ".", "Table", ",", "key", ".", "Index", ")", "\n", "final", ":=", "subTxn", ".", "CommitOnly", "(", ")", "\n", "txn", ".", "rootTxn", ".", "Insert", "(", "path", ",", "final", ")", "\n", "}", "\n\n", "// Update the root of the DB", "newRoot", ":=", "txn", ".", "rootTxn", ".", "CommitOnly", "(", ")", "\n", "atomic", ".", "StorePointer", "(", "&", "txn", ".", "db", ".", "root", ",", "unsafe", ".", "Pointer", "(", "newRoot", ")", ")", "\n\n", "// Now issue all of the mutation updates (this is safe to call", "// even if mutation tracking isn't enabled); we do this after", "// the root pointer is swapped so that waking responders will", "// see the new state.", "for", "_", ",", "subTxn", ":=", "range", "txn", ".", "modified", "{", "subTxn", ".", "Notify", "(", ")", "\n", "}", "\n", "txn", ".", "rootTxn", ".", "Notify", "(", ")", "\n\n", "// Clear the txn", "txn", ".", "rootTxn", "=", "nil", "\n", "txn", ".", "modified", "=", "nil", "\n\n", "// Release the writer lock since this is invalid", "txn", ".", "db", ".", "writer", ".", "Unlock", "(", ")", "\n\n", "// Run the deferred functions, if any", "for", "i", ":=", "len", "(", "txn", ".", "after", ")", ";", "i", ">", "0", ";", "i", "--", "{", "fn", ":=", "txn", ".", "after", "[", "i", "-", "1", "]", "\n", "fn", "(", ")", "\n", "}", "\n", "}" ]
// Commit is used to finalize this transaction. // This is a noop for read transactions.
[ "Commit", "is", "used", "to", "finalize", "this", "transaction", ".", "This", "is", "a", "noop", "for", "read", "transactions", "." ]
10278d3759e27502b741e52c7d8115d892e7723a
https://github.com/hashicorp/go-memdb/blob/10278d3759e27502b741e52c7d8115d892e7723a/txn.go#L111-L154
train
hashicorp/go-memdb
txn.go
Delete
func (txn *Txn) Delete(table string, obj interface{}) error { if !txn.write { return fmt.Errorf("cannot delete in read-only transaction") } // Get the table schema tableSchema, ok := txn.db.schema.Tables[table] if !ok { return fmt.Errorf("invalid table '%s'", table) } // Get the primary ID of the object idSchema := tableSchema.Indexes[id] idIndexer := idSchema.Indexer.(SingleIndexer) ok, idVal, err := idIndexer.FromObject(obj) if err != nil { return fmt.Errorf("failed to build primary index: %v", err) } if !ok { return fmt.Errorf("object missing primary index") } // Lookup the object by ID first, check fi we should continue idTxn := txn.writableIndex(table, id) existing, ok := idTxn.Get(idVal) if !ok { return ErrNotFound } // Remove the object from all the indexes for name, indexSchema := range tableSchema.Indexes { indexTxn := txn.writableIndex(table, name) // Handle the update by deleting from the index first var ( ok bool vals [][]byte err error ) switch indexer := indexSchema.Indexer.(type) { case SingleIndexer: var val []byte ok, val, err = indexer.FromObject(existing) vals = [][]byte{val} case MultiIndexer: ok, vals, err = indexer.FromObject(existing) } if err != nil { return fmt.Errorf("failed to build index '%s': %v", name, err) } if ok { // Handle non-unique index by computing a unique index. // This is done by appending the primary key which must // be unique anyways. for _, val := range vals { if !indexSchema.Unique { val = append(val, idVal...) } indexTxn.Delete(val) } } } return nil }
go
func (txn *Txn) Delete(table string, obj interface{}) error { if !txn.write { return fmt.Errorf("cannot delete in read-only transaction") } // Get the table schema tableSchema, ok := txn.db.schema.Tables[table] if !ok { return fmt.Errorf("invalid table '%s'", table) } // Get the primary ID of the object idSchema := tableSchema.Indexes[id] idIndexer := idSchema.Indexer.(SingleIndexer) ok, idVal, err := idIndexer.FromObject(obj) if err != nil { return fmt.Errorf("failed to build primary index: %v", err) } if !ok { return fmt.Errorf("object missing primary index") } // Lookup the object by ID first, check fi we should continue idTxn := txn.writableIndex(table, id) existing, ok := idTxn.Get(idVal) if !ok { return ErrNotFound } // Remove the object from all the indexes for name, indexSchema := range tableSchema.Indexes { indexTxn := txn.writableIndex(table, name) // Handle the update by deleting from the index first var ( ok bool vals [][]byte err error ) switch indexer := indexSchema.Indexer.(type) { case SingleIndexer: var val []byte ok, val, err = indexer.FromObject(existing) vals = [][]byte{val} case MultiIndexer: ok, vals, err = indexer.FromObject(existing) } if err != nil { return fmt.Errorf("failed to build index '%s': %v", name, err) } if ok { // Handle non-unique index by computing a unique index. // This is done by appending the primary key which must // be unique anyways. for _, val := range vals { if !indexSchema.Unique { val = append(val, idVal...) } indexTxn.Delete(val) } } } return nil }
[ "func", "(", "txn", "*", "Txn", ")", "Delete", "(", "table", "string", ",", "obj", "interface", "{", "}", ")", "error", "{", "if", "!", "txn", ".", "write", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Get the table schema", "tableSchema", ",", "ok", ":=", "txn", ".", "db", ".", "schema", ".", "Tables", "[", "table", "]", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "table", ")", "\n", "}", "\n\n", "// Get the primary ID of the object", "idSchema", ":=", "tableSchema", ".", "Indexes", "[", "id", "]", "\n", "idIndexer", ":=", "idSchema", ".", "Indexer", ".", "(", "SingleIndexer", ")", "\n", "ok", ",", "idVal", ",", "err", ":=", "idIndexer", ".", "FromObject", "(", "obj", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Lookup the object by ID first, check fi we should continue", "idTxn", ":=", "txn", ".", "writableIndex", "(", "table", ",", "id", ")", "\n", "existing", ",", "ok", ":=", "idTxn", ".", "Get", "(", "idVal", ")", "\n", "if", "!", "ok", "{", "return", "ErrNotFound", "\n", "}", "\n\n", "// Remove the object from all the indexes", "for", "name", ",", "indexSchema", ":=", "range", "tableSchema", ".", "Indexes", "{", "indexTxn", ":=", "txn", ".", "writableIndex", "(", "table", ",", "name", ")", "\n\n", "// Handle the update by deleting from the index first", "var", "(", "ok", "bool", "\n", "vals", "[", "]", "[", "]", "byte", "\n", "err", "error", "\n", ")", "\n", "switch", "indexer", ":=", "indexSchema", ".", "Indexer", ".", "(", "type", ")", "{", "case", "SingleIndexer", ":", "var", "val", "[", "]", "byte", "\n", "ok", ",", "val", ",", "err", "=", "indexer", ".", "FromObject", "(", "existing", ")", "\n", "vals", "=", "[", "]", "[", "]", "byte", "{", "val", "}", "\n", "case", "MultiIndexer", ":", "ok", ",", "vals", ",", "err", "=", "indexer", ".", "FromObject", "(", "existing", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ",", "err", ")", "\n", "}", "\n", "if", "ok", "{", "// Handle non-unique index by computing a unique index.", "// This is done by appending the primary key which must", "// be unique anyways.", "for", "_", ",", "val", ":=", "range", "vals", "{", "if", "!", "indexSchema", ".", "Unique", "{", "val", "=", "append", "(", "val", ",", "idVal", "...", ")", "\n", "}", "\n", "indexTxn", ".", "Delete", "(", "val", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Delete is used to delete a single object from the given table // This object must already exist in the table
[ "Delete", "is", "used", "to", "delete", "a", "single", "object", "from", "the", "given", "table", "This", "object", "must", "already", "exist", "in", "the", "table" ]
10278d3759e27502b741e52c7d8115d892e7723a
https://github.com/hashicorp/go-memdb/blob/10278d3759e27502b741e52c7d8115d892e7723a/txn.go#L273-L336
train
hashicorp/go-memdb
txn.go
DeletePrefix
func (txn *Txn) DeletePrefix(table string, prefix_index string, prefix string) (bool, error) { if !txn.write { return false, fmt.Errorf("cannot delete in read-only transaction") } if !strings.HasSuffix(prefix_index, "_prefix") { return false, fmt.Errorf("Index name for DeletePrefix must be a prefix index, Got %v ", prefix_index) } deletePrefixIndex := strings.TrimSuffix(prefix_index, "_prefix") // Get an iterator over all of the keys with the given prefix. entries, err := txn.Get(table, prefix_index, prefix) if err != nil { return false, fmt.Errorf("failed kvs lookup: %s", err) } // Get the table schema tableSchema, ok := txn.db.schema.Tables[table] if !ok { return false, fmt.Errorf("invalid table '%s'", table) } foundAny := false for entry := entries.Next(); entry != nil; entry = entries.Next() { if !foundAny { foundAny = true } // Get the primary ID of the object idSchema := tableSchema.Indexes[id] idIndexer := idSchema.Indexer.(SingleIndexer) ok, idVal, err := idIndexer.FromObject(entry) if err != nil { return false, fmt.Errorf("failed to build primary index: %v", err) } if !ok { return false, fmt.Errorf("object missing primary index") } // Remove the object from all the indexes except the given prefix index for name, indexSchema := range tableSchema.Indexes { if name == deletePrefixIndex { continue } indexTxn := txn.writableIndex(table, name) // Handle the update by deleting from the index first var ( ok bool vals [][]byte err error ) switch indexer := indexSchema.Indexer.(type) { case SingleIndexer: var val []byte ok, val, err = indexer.FromObject(entry) vals = [][]byte{val} case MultiIndexer: ok, vals, err = indexer.FromObject(entry) } if err != nil { return false, fmt.Errorf("failed to build index '%s': %v", name, err) } if ok { // Handle non-unique index by computing a unique index. // This is done by appending the primary key which must // be unique anyways. for _, val := range vals { if !indexSchema.Unique { val = append(val, idVal...) } indexTxn.Delete(val) } } } } if foundAny { indexTxn := txn.writableIndex(table, deletePrefixIndex) ok = indexTxn.DeletePrefix([]byte(prefix)) if !ok { panic(fmt.Errorf("prefix %v matched some entries but DeletePrefix did not delete any ", prefix)) } return true, nil } return false, nil }
go
func (txn *Txn) DeletePrefix(table string, prefix_index string, prefix string) (bool, error) { if !txn.write { return false, fmt.Errorf("cannot delete in read-only transaction") } if !strings.HasSuffix(prefix_index, "_prefix") { return false, fmt.Errorf("Index name for DeletePrefix must be a prefix index, Got %v ", prefix_index) } deletePrefixIndex := strings.TrimSuffix(prefix_index, "_prefix") // Get an iterator over all of the keys with the given prefix. entries, err := txn.Get(table, prefix_index, prefix) if err != nil { return false, fmt.Errorf("failed kvs lookup: %s", err) } // Get the table schema tableSchema, ok := txn.db.schema.Tables[table] if !ok { return false, fmt.Errorf("invalid table '%s'", table) } foundAny := false for entry := entries.Next(); entry != nil; entry = entries.Next() { if !foundAny { foundAny = true } // Get the primary ID of the object idSchema := tableSchema.Indexes[id] idIndexer := idSchema.Indexer.(SingleIndexer) ok, idVal, err := idIndexer.FromObject(entry) if err != nil { return false, fmt.Errorf("failed to build primary index: %v", err) } if !ok { return false, fmt.Errorf("object missing primary index") } // Remove the object from all the indexes except the given prefix index for name, indexSchema := range tableSchema.Indexes { if name == deletePrefixIndex { continue } indexTxn := txn.writableIndex(table, name) // Handle the update by deleting from the index first var ( ok bool vals [][]byte err error ) switch indexer := indexSchema.Indexer.(type) { case SingleIndexer: var val []byte ok, val, err = indexer.FromObject(entry) vals = [][]byte{val} case MultiIndexer: ok, vals, err = indexer.FromObject(entry) } if err != nil { return false, fmt.Errorf("failed to build index '%s': %v", name, err) } if ok { // Handle non-unique index by computing a unique index. // This is done by appending the primary key which must // be unique anyways. for _, val := range vals { if !indexSchema.Unique { val = append(val, idVal...) } indexTxn.Delete(val) } } } } if foundAny { indexTxn := txn.writableIndex(table, deletePrefixIndex) ok = indexTxn.DeletePrefix([]byte(prefix)) if !ok { panic(fmt.Errorf("prefix %v matched some entries but DeletePrefix did not delete any ", prefix)) } return true, nil } return false, nil }
[ "func", "(", "txn", "*", "Txn", ")", "DeletePrefix", "(", "table", "string", ",", "prefix_index", "string", ",", "prefix", "string", ")", "(", "bool", ",", "error", ")", "{", "if", "!", "txn", ".", "write", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "!", "strings", ".", "HasSuffix", "(", "prefix_index", ",", "\"", "\"", ")", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "prefix_index", ")", "\n", "}", "\n\n", "deletePrefixIndex", ":=", "strings", ".", "TrimSuffix", "(", "prefix_index", ",", "\"", "\"", ")", "\n\n", "// Get an iterator over all of the keys with the given prefix.", "entries", ",", "err", ":=", "txn", ".", "Get", "(", "table", ",", "prefix_index", ",", "prefix", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "// Get the table schema", "tableSchema", ",", "ok", ":=", "txn", ".", "db", ".", "schema", ".", "Tables", "[", "table", "]", "\n", "if", "!", "ok", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "table", ")", "\n", "}", "\n\n", "foundAny", ":=", "false", "\n", "for", "entry", ":=", "entries", ".", "Next", "(", ")", ";", "entry", "!=", "nil", ";", "entry", "=", "entries", ".", "Next", "(", ")", "{", "if", "!", "foundAny", "{", "foundAny", "=", "true", "\n", "}", "\n", "// Get the primary ID of the object", "idSchema", ":=", "tableSchema", ".", "Indexes", "[", "id", "]", "\n", "idIndexer", ":=", "idSchema", ".", "Indexer", ".", "(", "SingleIndexer", ")", "\n", "ok", ",", "idVal", ",", "err", ":=", "idIndexer", ".", "FromObject", "(", "entry", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "!", "ok", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "// Remove the object from all the indexes except the given prefix index", "for", "name", ",", "indexSchema", ":=", "range", "tableSchema", ".", "Indexes", "{", "if", "name", "==", "deletePrefixIndex", "{", "continue", "\n", "}", "\n", "indexTxn", ":=", "txn", ".", "writableIndex", "(", "table", ",", "name", ")", "\n\n", "// Handle the update by deleting from the index first", "var", "(", "ok", "bool", "\n", "vals", "[", "]", "[", "]", "byte", "\n", "err", "error", "\n", ")", "\n", "switch", "indexer", ":=", "indexSchema", ".", "Indexer", ".", "(", "type", ")", "{", "case", "SingleIndexer", ":", "var", "val", "[", "]", "byte", "\n", "ok", ",", "val", ",", "err", "=", "indexer", ".", "FromObject", "(", "entry", ")", "\n", "vals", "=", "[", "]", "[", "]", "byte", "{", "val", "}", "\n", "case", "MultiIndexer", ":", "ok", ",", "vals", ",", "err", "=", "indexer", ".", "FromObject", "(", "entry", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ",", "err", ")", "\n", "}", "\n\n", "if", "ok", "{", "// Handle non-unique index by computing a unique index.", "// This is done by appending the primary key which must", "// be unique anyways.", "for", "_", ",", "val", ":=", "range", "vals", "{", "if", "!", "indexSchema", ".", "Unique", "{", "val", "=", "append", "(", "val", ",", "idVal", "...", ")", "\n", "}", "\n", "indexTxn", ".", "Delete", "(", "val", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "foundAny", "{", "indexTxn", ":=", "txn", ".", "writableIndex", "(", "table", ",", "deletePrefixIndex", ")", "\n", "ok", "=", "indexTxn", ".", "DeletePrefix", "(", "[", "]", "byte", "(", "prefix", ")", ")", "\n", "if", "!", "ok", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "prefix", ")", ")", "\n", "}", "\n", "return", "true", ",", "nil", "\n", "}", "\n", "return", "false", ",", "nil", "\n", "}" ]
// DeletePrefix is used to delete an entire subtree based on a prefix. // The given index must be a prefix index, and will be used to perform a scan and enumerate the set of objects to delete. // These will be removed from all other indexes, and then a special prefix operation will delete the objects from the given index in an efficient subtree delete operation. // This is useful when you have a very large number of objects indexed by the given index, along with a much smaller number of entries in the other indexes for those objects.
[ "DeletePrefix", "is", "used", "to", "delete", "an", "entire", "subtree", "based", "on", "a", "prefix", ".", "The", "given", "index", "must", "be", "a", "prefix", "index", "and", "will", "be", "used", "to", "perform", "a", "scan", "and", "enumerate", "the", "set", "of", "objects", "to", "delete", ".", "These", "will", "be", "removed", "from", "all", "other", "indexes", "and", "then", "a", "special", "prefix", "operation", "will", "delete", "the", "objects", "from", "the", "given", "index", "in", "an", "efficient", "subtree", "delete", "operation", ".", "This", "is", "useful", "when", "you", "have", "a", "very", "large", "number", "of", "objects", "indexed", "by", "the", "given", "index", "along", "with", "a", "much", "smaller", "number", "of", "entries", "in", "the", "other", "indexes", "for", "those", "objects", "." ]
10278d3759e27502b741e52c7d8115d892e7723a
https://github.com/hashicorp/go-memdb/blob/10278d3759e27502b741e52c7d8115d892e7723a/txn.go#L342-L426
train
hashicorp/go-memdb
txn.go
DeleteAll
func (txn *Txn) DeleteAll(table, index string, args ...interface{}) (int, error) { if !txn.write { return 0, fmt.Errorf("cannot delete in read-only transaction") } // Get all the objects iter, err := txn.Get(table, index, args...) if err != nil { return 0, err } // Put them into a slice so there are no safety concerns while actually // performing the deletes var objs []interface{} for { obj := iter.Next() if obj == nil { break } objs = append(objs, obj) } // Do the deletes num := 0 for _, obj := range objs { if err := txn.Delete(table, obj); err != nil { return num, err } num++ } return num, nil }
go
func (txn *Txn) DeleteAll(table, index string, args ...interface{}) (int, error) { if !txn.write { return 0, fmt.Errorf("cannot delete in read-only transaction") } // Get all the objects iter, err := txn.Get(table, index, args...) if err != nil { return 0, err } // Put them into a slice so there are no safety concerns while actually // performing the deletes var objs []interface{} for { obj := iter.Next() if obj == nil { break } objs = append(objs, obj) } // Do the deletes num := 0 for _, obj := range objs { if err := txn.Delete(table, obj); err != nil { return num, err } num++ } return num, nil }
[ "func", "(", "txn", "*", "Txn", ")", "DeleteAll", "(", "table", ",", "index", "string", ",", "args", "...", "interface", "{", "}", ")", "(", "int", ",", "error", ")", "{", "if", "!", "txn", ".", "write", "{", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Get all the objects", "iter", ",", "err", ":=", "txn", ".", "Get", "(", "table", ",", "index", ",", "args", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "// Put them into a slice so there are no safety concerns while actually", "// performing the deletes", "var", "objs", "[", "]", "interface", "{", "}", "\n", "for", "{", "obj", ":=", "iter", ".", "Next", "(", ")", "\n", "if", "obj", "==", "nil", "{", "break", "\n", "}", "\n\n", "objs", "=", "append", "(", "objs", ",", "obj", ")", "\n", "}", "\n\n", "// Do the deletes", "num", ":=", "0", "\n", "for", "_", ",", "obj", ":=", "range", "objs", "{", "if", "err", ":=", "txn", ".", "Delete", "(", "table", ",", "obj", ")", ";", "err", "!=", "nil", "{", "return", "num", ",", "err", "\n", "}", "\n", "num", "++", "\n", "}", "\n", "return", "num", ",", "nil", "\n", "}" ]
// DeleteAll is used to delete all the objects in a given table // matching the constraints on the index
[ "DeleteAll", "is", "used", "to", "delete", "all", "the", "objects", "in", "a", "given", "table", "matching", "the", "constraints", "on", "the", "index" ]
10278d3759e27502b741e52c7d8115d892e7723a
https://github.com/hashicorp/go-memdb/blob/10278d3759e27502b741e52c7d8115d892e7723a/txn.go#L430-L462
train
hashicorp/go-memdb
txn.go
FirstWatch
func (txn *Txn) FirstWatch(table, index string, args ...interface{}) (<-chan struct{}, interface{}, error) { // Get the index value indexSchema, val, err := txn.getIndexValue(table, index, args...) if err != nil { return nil, nil, err } // Get the index itself indexTxn := txn.readableIndex(table, indexSchema.Name) // Do an exact lookup if indexSchema.Unique && val != nil && indexSchema.Name == index { watch, obj, ok := indexTxn.GetWatch(val) if !ok { return watch, nil, nil } return watch, obj, nil } // Handle non-unique index by using an iterator and getting the first value iter := indexTxn.Root().Iterator() watch := iter.SeekPrefixWatch(val) _, value, _ := iter.Next() return watch, value, nil }
go
func (txn *Txn) FirstWatch(table, index string, args ...interface{}) (<-chan struct{}, interface{}, error) { // Get the index value indexSchema, val, err := txn.getIndexValue(table, index, args...) if err != nil { return nil, nil, err } // Get the index itself indexTxn := txn.readableIndex(table, indexSchema.Name) // Do an exact lookup if indexSchema.Unique && val != nil && indexSchema.Name == index { watch, obj, ok := indexTxn.GetWatch(val) if !ok { return watch, nil, nil } return watch, obj, nil } // Handle non-unique index by using an iterator and getting the first value iter := indexTxn.Root().Iterator() watch := iter.SeekPrefixWatch(val) _, value, _ := iter.Next() return watch, value, nil }
[ "func", "(", "txn", "*", "Txn", ")", "FirstWatch", "(", "table", ",", "index", "string", ",", "args", "...", "interface", "{", "}", ")", "(", "<-", "chan", "struct", "{", "}", ",", "interface", "{", "}", ",", "error", ")", "{", "// Get the index value", "indexSchema", ",", "val", ",", "err", ":=", "txn", ".", "getIndexValue", "(", "table", ",", "index", ",", "args", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "// Get the index itself", "indexTxn", ":=", "txn", ".", "readableIndex", "(", "table", ",", "indexSchema", ".", "Name", ")", "\n\n", "// Do an exact lookup", "if", "indexSchema", ".", "Unique", "&&", "val", "!=", "nil", "&&", "indexSchema", ".", "Name", "==", "index", "{", "watch", ",", "obj", ",", "ok", ":=", "indexTxn", ".", "GetWatch", "(", "val", ")", "\n", "if", "!", "ok", "{", "return", "watch", ",", "nil", ",", "nil", "\n", "}", "\n", "return", "watch", ",", "obj", ",", "nil", "\n", "}", "\n\n", "// Handle non-unique index by using an iterator and getting the first value", "iter", ":=", "indexTxn", ".", "Root", "(", ")", ".", "Iterator", "(", ")", "\n", "watch", ":=", "iter", ".", "SeekPrefixWatch", "(", "val", ")", "\n", "_", ",", "value", ",", "_", ":=", "iter", ".", "Next", "(", ")", "\n", "return", "watch", ",", "value", ",", "nil", "\n", "}" ]
// FirstWatch is used to return the first matching object for // the given constraints on the index along with the watch channel
[ "FirstWatch", "is", "used", "to", "return", "the", "first", "matching", "object", "for", "the", "given", "constraints", "on", "the", "index", "along", "with", "the", "watch", "channel" ]
10278d3759e27502b741e52c7d8115d892e7723a
https://github.com/hashicorp/go-memdb/blob/10278d3759e27502b741e52c7d8115d892e7723a/txn.go#L466-L490
train
hashicorp/go-memdb
txn.go
First
func (txn *Txn) First(table, index string, args ...interface{}) (interface{}, error) { _, val, err := txn.FirstWatch(table, index, args...) return val, err }
go
func (txn *Txn) First(table, index string, args ...interface{}) (interface{}, error) { _, val, err := txn.FirstWatch(table, index, args...) return val, err }
[ "func", "(", "txn", "*", "Txn", ")", "First", "(", "table", ",", "index", "string", ",", "args", "...", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "_", ",", "val", ",", "err", ":=", "txn", ".", "FirstWatch", "(", "table", ",", "index", ",", "args", "...", ")", "\n", "return", "val", ",", "err", "\n", "}" ]
// First is used to return the first matching object for // the given constraints on the index
[ "First", "is", "used", "to", "return", "the", "first", "matching", "object", "for", "the", "given", "constraints", "on", "the", "index" ]
10278d3759e27502b741e52c7d8115d892e7723a
https://github.com/hashicorp/go-memdb/blob/10278d3759e27502b741e52c7d8115d892e7723a/txn.go#L494-L497
train
hashicorp/go-memdb
txn.go
getIndexValue
func (txn *Txn) getIndexValue(table, index string, args ...interface{}) (*IndexSchema, []byte, error) { // Get the table schema tableSchema, ok := txn.db.schema.Tables[table] if !ok { return nil, nil, fmt.Errorf("invalid table '%s'", table) } // Check for a prefix scan prefixScan := false if strings.HasSuffix(index, "_prefix") { index = strings.TrimSuffix(index, "_prefix") prefixScan = true } // Get the index schema indexSchema, ok := tableSchema.Indexes[index] if !ok { return nil, nil, fmt.Errorf("invalid index '%s'", index) } // Hot-path for when there are no arguments if len(args) == 0 { return indexSchema, nil, nil } // Special case the prefix scanning if prefixScan { prefixIndexer, ok := indexSchema.Indexer.(PrefixIndexer) if !ok { return indexSchema, nil, fmt.Errorf("index '%s' does not support prefix scanning", index) } val, err := prefixIndexer.PrefixFromArgs(args...) if err != nil { return indexSchema, nil, fmt.Errorf("index error: %v", err) } return indexSchema, val, err } // Get the exact match index val, err := indexSchema.Indexer.FromArgs(args...) if err != nil { return indexSchema, nil, fmt.Errorf("index error: %v", err) } return indexSchema, val, err }
go
func (txn *Txn) getIndexValue(table, index string, args ...interface{}) (*IndexSchema, []byte, error) { // Get the table schema tableSchema, ok := txn.db.schema.Tables[table] if !ok { return nil, nil, fmt.Errorf("invalid table '%s'", table) } // Check for a prefix scan prefixScan := false if strings.HasSuffix(index, "_prefix") { index = strings.TrimSuffix(index, "_prefix") prefixScan = true } // Get the index schema indexSchema, ok := tableSchema.Indexes[index] if !ok { return nil, nil, fmt.Errorf("invalid index '%s'", index) } // Hot-path for when there are no arguments if len(args) == 0 { return indexSchema, nil, nil } // Special case the prefix scanning if prefixScan { prefixIndexer, ok := indexSchema.Indexer.(PrefixIndexer) if !ok { return indexSchema, nil, fmt.Errorf("index '%s' does not support prefix scanning", index) } val, err := prefixIndexer.PrefixFromArgs(args...) if err != nil { return indexSchema, nil, fmt.Errorf("index error: %v", err) } return indexSchema, val, err } // Get the exact match index val, err := indexSchema.Indexer.FromArgs(args...) if err != nil { return indexSchema, nil, fmt.Errorf("index error: %v", err) } return indexSchema, val, err }
[ "func", "(", "txn", "*", "Txn", ")", "getIndexValue", "(", "table", ",", "index", "string", ",", "args", "...", "interface", "{", "}", ")", "(", "*", "IndexSchema", ",", "[", "]", "byte", ",", "error", ")", "{", "// Get the table schema", "tableSchema", ",", "ok", ":=", "txn", ".", "db", ".", "schema", ".", "Tables", "[", "table", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "table", ")", "\n", "}", "\n\n", "// Check for a prefix scan", "prefixScan", ":=", "false", "\n", "if", "strings", ".", "HasSuffix", "(", "index", ",", "\"", "\"", ")", "{", "index", "=", "strings", ".", "TrimSuffix", "(", "index", ",", "\"", "\"", ")", "\n", "prefixScan", "=", "true", "\n", "}", "\n\n", "// Get the index schema", "indexSchema", ",", "ok", ":=", "tableSchema", ".", "Indexes", "[", "index", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "index", ")", "\n", "}", "\n\n", "// Hot-path for when there are no arguments", "if", "len", "(", "args", ")", "==", "0", "{", "return", "indexSchema", ",", "nil", ",", "nil", "\n", "}", "\n\n", "// Special case the prefix scanning", "if", "prefixScan", "{", "prefixIndexer", ",", "ok", ":=", "indexSchema", ".", "Indexer", ".", "(", "PrefixIndexer", ")", "\n", "if", "!", "ok", "{", "return", "indexSchema", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "index", ")", "\n", "}", "\n\n", "val", ",", "err", ":=", "prefixIndexer", ".", "PrefixFromArgs", "(", "args", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "indexSchema", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "indexSchema", ",", "val", ",", "err", "\n", "}", "\n\n", "// Get the exact match index", "val", ",", "err", ":=", "indexSchema", ".", "Indexer", ".", "FromArgs", "(", "args", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "indexSchema", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "indexSchema", ",", "val", ",", "err", "\n", "}" ]
// getIndexValue is used to get the IndexSchema and the value // used to scan the index given the parameters. This handles prefix based // scans when the index has the "_prefix" suffix. The index must support // prefix iteration.
[ "getIndexValue", "is", "used", "to", "get", "the", "IndexSchema", "and", "the", "value", "used", "to", "scan", "the", "index", "given", "the", "parameters", ".", "This", "handles", "prefix", "based", "scans", "when", "the", "index", "has", "the", "_prefix", "suffix", ".", "The", "index", "must", "support", "prefix", "iteration", "." ]
10278d3759e27502b741e52c7d8115d892e7723a
https://github.com/hashicorp/go-memdb/blob/10278d3759e27502b741e52c7d8115d892e7723a/txn.go#L536-L582
train
hashicorp/go-memdb
txn.go
Get
func (txn *Txn) Get(table, index string, args ...interface{}) (ResultIterator, error) { // Get the index value to scan indexSchema, val, err := txn.getIndexValue(table, index, args...) if err != nil { return nil, err } // Get the index itself indexTxn := txn.readableIndex(table, indexSchema.Name) indexRoot := indexTxn.Root() // Get an interator over the index indexIter := indexRoot.Iterator() // Seek the iterator to the appropriate sub-set watchCh := indexIter.SeekPrefixWatch(val) // Create an iterator iter := &radixIterator{ iter: indexIter, watchCh: watchCh, } return iter, nil }
go
func (txn *Txn) Get(table, index string, args ...interface{}) (ResultIterator, error) { // Get the index value to scan indexSchema, val, err := txn.getIndexValue(table, index, args...) if err != nil { return nil, err } // Get the index itself indexTxn := txn.readableIndex(table, indexSchema.Name) indexRoot := indexTxn.Root() // Get an interator over the index indexIter := indexRoot.Iterator() // Seek the iterator to the appropriate sub-set watchCh := indexIter.SeekPrefixWatch(val) // Create an iterator iter := &radixIterator{ iter: indexIter, watchCh: watchCh, } return iter, nil }
[ "func", "(", "txn", "*", "Txn", ")", "Get", "(", "table", ",", "index", "string", ",", "args", "...", "interface", "{", "}", ")", "(", "ResultIterator", ",", "error", ")", "{", "// Get the index value to scan", "indexSchema", ",", "val", ",", "err", ":=", "txn", ".", "getIndexValue", "(", "table", ",", "index", ",", "args", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Get the index itself", "indexTxn", ":=", "txn", ".", "readableIndex", "(", "table", ",", "indexSchema", ".", "Name", ")", "\n", "indexRoot", ":=", "indexTxn", ".", "Root", "(", ")", "\n\n", "// Get an interator over the index", "indexIter", ":=", "indexRoot", ".", "Iterator", "(", ")", "\n\n", "// Seek the iterator to the appropriate sub-set", "watchCh", ":=", "indexIter", ".", "SeekPrefixWatch", "(", "val", ")", "\n\n", "// Create an iterator", "iter", ":=", "&", "radixIterator", "{", "iter", ":", "indexIter", ",", "watchCh", ":", "watchCh", ",", "}", "\n", "return", "iter", ",", "nil", "\n", "}" ]
// Get is used to construct a ResultIterator over all the // rows that match the given constraints of an index.
[ "Get", "is", "used", "to", "construct", "a", "ResultIterator", "over", "all", "the", "rows", "that", "match", "the", "given", "constraints", "of", "an", "index", "." ]
10278d3759e27502b741e52c7d8115d892e7723a
https://github.com/hashicorp/go-memdb/blob/10278d3759e27502b741e52c7d8115d892e7723a/txn.go#L593-L616
train
hashicorp/go-memdb
txn.go
Defer
func (txn *Txn) Defer(fn func()) { txn.after = append(txn.after, fn) }
go
func (txn *Txn) Defer(fn func()) { txn.after = append(txn.after, fn) }
[ "func", "(", "txn", "*", "Txn", ")", "Defer", "(", "fn", "func", "(", ")", ")", "{", "txn", ".", "after", "=", "append", "(", "txn", ".", "after", ",", "fn", ")", "\n", "}" ]
// Defer is used to push a new arbitrary function onto a stack which // gets called when a transaction is committed and finished. Deferred // functions are called in LIFO order, and only invoked at the end of // write transactions.
[ "Defer", "is", "used", "to", "push", "a", "new", "arbitrary", "function", "onto", "a", "stack", "which", "gets", "called", "when", "a", "transaction", "is", "committed", "and", "finished", ".", "Deferred", "functions", "are", "called", "in", "LIFO", "order", "and", "only", "invoked", "at", "the", "end", "of", "write", "transactions", "." ]
10278d3759e27502b741e52c7d8115d892e7723a
https://github.com/hashicorp/go-memdb/blob/10278d3759e27502b741e52c7d8115d892e7723a/txn.go#L622-L624
train
hashicorp/go-memdb
filter.go
Next
func (f *FilterIterator) Next() interface{} { for { if value := f.iter.Next(); value == nil || !f.filter(value) { return value } } }
go
func (f *FilterIterator) Next() interface{} { for { if value := f.iter.Next(); value == nil || !f.filter(value) { return value } } }
[ "func", "(", "f", "*", "FilterIterator", ")", "Next", "(", ")", "interface", "{", "}", "{", "for", "{", "if", "value", ":=", "f", ".", "iter", ".", "Next", "(", ")", ";", "value", "==", "nil", "||", "!", "f", ".", "filter", "(", "value", ")", "{", "return", "value", "\n", "}", "\n", "}", "\n", "}" ]
// Next returns the next non-filtered result from the wrapped iterator
[ "Next", "returns", "the", "next", "non", "-", "filtered", "result", "from", "the", "wrapped", "iterator" ]
10278d3759e27502b741e52c7d8115d892e7723a
https://github.com/hashicorp/go-memdb/blob/10278d3759e27502b741e52c7d8115d892e7723a/filter.go#L27-L33
train
hashicorp/go-memdb
watch-gen/main.go
render
func render() error { tmpl, err := template.New("watch").Parse(source) if err != nil { return err } if err := tmpl.Execute(os.Stdout, make([]struct{}, aFew)); err != nil { return err } return nil }
go
func render() error { tmpl, err := template.New("watch").Parse(source) if err != nil { return err } if err := tmpl.Execute(os.Stdout, make([]struct{}, aFew)); err != nil { return err } return nil }
[ "func", "render", "(", ")", "error", "{", "tmpl", ",", "err", ":=", "template", ".", "New", "(", "\"", "\"", ")", ".", "Parse", "(", "source", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "tmpl", ".", "Execute", "(", "os", ".", "Stdout", ",", "make", "(", "[", "]", "struct", "{", "}", ",", "aFew", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// render prints the template to stdout.
[ "render", "prints", "the", "template", "to", "stdout", "." ]
10278d3759e27502b741e52c7d8115d892e7723a
https://github.com/hashicorp/go-memdb/blob/10278d3759e27502b741e52c7d8115d892e7723a/watch-gen/main.go#L47-L56
train
hashicorp/go-memdb
schema.go
Validate
func (s *DBSchema) Validate() error { if s == nil { return fmt.Errorf("schema is nil") } if len(s.Tables) == 0 { return fmt.Errorf("schema has no tables defined") } for name, table := range s.Tables { if name != table.Name { return fmt.Errorf("table name mis-match for '%s'", name) } if err := table.Validate(); err != nil { return fmt.Errorf("table %q: %s", name, err) } } return nil }
go
func (s *DBSchema) Validate() error { if s == nil { return fmt.Errorf("schema is nil") } if len(s.Tables) == 0 { return fmt.Errorf("schema has no tables defined") } for name, table := range s.Tables { if name != table.Name { return fmt.Errorf("table name mis-match for '%s'", name) } if err := table.Validate(); err != nil { return fmt.Errorf("table %q: %s", name, err) } } return nil }
[ "func", "(", "s", "*", "DBSchema", ")", "Validate", "(", ")", "error", "{", "if", "s", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "len", "(", "s", ".", "Tables", ")", "==", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "for", "name", ",", "table", ":=", "range", "s", ".", "Tables", "{", "if", "name", "!=", "table", ".", "Name", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n\n", "if", "err", ":=", "table", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Validate validates the schema.
[ "Validate", "validates", "the", "schema", "." ]
10278d3759e27502b741e52c7d8115d892e7723a
https://github.com/hashicorp/go-memdb/blob/10278d3759e27502b741e52c7d8115d892e7723a/schema.go#L16-L36
train
hashicorp/go-memdb
schema.go
Validate
func (s *TableSchema) Validate() error { if s.Name == "" { return fmt.Errorf("missing table name") } if len(s.Indexes) == 0 { return fmt.Errorf("missing table indexes for '%s'", s.Name) } if _, ok := s.Indexes["id"]; !ok { return fmt.Errorf("must have id index") } if !s.Indexes["id"].Unique { return fmt.Errorf("id index must be unique") } if _, ok := s.Indexes["id"].Indexer.(SingleIndexer); !ok { return fmt.Errorf("id index must be a SingleIndexer") } for name, index := range s.Indexes { if name != index.Name { return fmt.Errorf("index name mis-match for '%s'", name) } if err := index.Validate(); err != nil { return fmt.Errorf("index %q: %s", name, err) } } return nil }
go
func (s *TableSchema) Validate() error { if s.Name == "" { return fmt.Errorf("missing table name") } if len(s.Indexes) == 0 { return fmt.Errorf("missing table indexes for '%s'", s.Name) } if _, ok := s.Indexes["id"]; !ok { return fmt.Errorf("must have id index") } if !s.Indexes["id"].Unique { return fmt.Errorf("id index must be unique") } if _, ok := s.Indexes["id"].Indexer.(SingleIndexer); !ok { return fmt.Errorf("id index must be a SingleIndexer") } for name, index := range s.Indexes { if name != index.Name { return fmt.Errorf("index name mis-match for '%s'", name) } if err := index.Validate(); err != nil { return fmt.Errorf("index %q: %s", name, err) } } return nil }
[ "func", "(", "s", "*", "TableSchema", ")", "Validate", "(", ")", "error", "{", "if", "s", ".", "Name", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "len", "(", "s", ".", "Indexes", ")", "==", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "s", ".", "Name", ")", "\n", "}", "\n\n", "if", "_", ",", "ok", ":=", "s", ".", "Indexes", "[", "\"", "\"", "]", ";", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "!", "s", ".", "Indexes", "[", "\"", "\"", "]", ".", "Unique", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "_", ",", "ok", ":=", "s", ".", "Indexes", "[", "\"", "\"", "]", ".", "Indexer", ".", "(", "SingleIndexer", ")", ";", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "for", "name", ",", "index", ":=", "range", "s", ".", "Indexes", "{", "if", "name", "!=", "index", ".", "Name", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n\n", "if", "err", ":=", "index", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Validate is used to validate the table schema
[ "Validate", "is", "used", "to", "validate", "the", "table", "schema" ]
10278d3759e27502b741e52c7d8115d892e7723a
https://github.com/hashicorp/go-memdb/blob/10278d3759e27502b741e52c7d8115d892e7723a/schema.go#L50-L82
train
hashicorp/go-memdb
memdb.go
NewMemDB
func NewMemDB(schema *DBSchema) (*MemDB, error) { // Validate the schema if err := schema.Validate(); err != nil { return nil, err } // Create the MemDB db := &MemDB{ schema: schema, root: unsafe.Pointer(iradix.New()), primary: true, } if err := db.initialize(); err != nil { return nil, err } return db, nil }
go
func NewMemDB(schema *DBSchema) (*MemDB, error) { // Validate the schema if err := schema.Validate(); err != nil { return nil, err } // Create the MemDB db := &MemDB{ schema: schema, root: unsafe.Pointer(iradix.New()), primary: true, } if err := db.initialize(); err != nil { return nil, err } return db, nil }
[ "func", "NewMemDB", "(", "schema", "*", "DBSchema", ")", "(", "*", "MemDB", ",", "error", ")", "{", "// Validate the schema", "if", "err", ":=", "schema", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Create the MemDB", "db", ":=", "&", "MemDB", "{", "schema", ":", "schema", ",", "root", ":", "unsafe", ".", "Pointer", "(", "iradix", ".", "New", "(", ")", ")", ",", "primary", ":", "true", ",", "}", "\n", "if", "err", ":=", "db", ".", "initialize", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "db", ",", "nil", "\n", "}" ]
// NewMemDB creates a new MemDB with the given schema
[ "NewMemDB", "creates", "a", "new", "MemDB", "with", "the", "given", "schema" ]
10278d3759e27502b741e52c7d8115d892e7723a
https://github.com/hashicorp/go-memdb/blob/10278d3759e27502b741e52c7d8115d892e7723a/memdb.go#L28-L45
train
hashicorp/go-memdb
memdb.go
getRoot
func (db *MemDB) getRoot() *iradix.Tree { root := (*iradix.Tree)(atomic.LoadPointer(&db.root)) return root }
go
func (db *MemDB) getRoot() *iradix.Tree { root := (*iradix.Tree)(atomic.LoadPointer(&db.root)) return root }
[ "func", "(", "db", "*", "MemDB", ")", "getRoot", "(", ")", "*", "iradix", ".", "Tree", "{", "root", ":=", "(", "*", "iradix", ".", "Tree", ")", "(", "atomic", ".", "LoadPointer", "(", "&", "db", ".", "root", ")", ")", "\n", "return", "root", "\n", "}" ]
// getRoot is used to do an atomic load of the root pointer
[ "getRoot", "is", "used", "to", "do", "an", "atomic", "load", "of", "the", "root", "pointer" ]
10278d3759e27502b741e52c7d8115d892e7723a
https://github.com/hashicorp/go-memdb/blob/10278d3759e27502b741e52c7d8115d892e7723a/memdb.go#L48-L51
train
hashicorp/go-memdb
memdb.go
Txn
func (db *MemDB) Txn(write bool) *Txn { if write { db.writer.Lock() } txn := &Txn{ db: db, write: write, rootTxn: db.getRoot().Txn(), } return txn }
go
func (db *MemDB) Txn(write bool) *Txn { if write { db.writer.Lock() } txn := &Txn{ db: db, write: write, rootTxn: db.getRoot().Txn(), } return txn }
[ "func", "(", "db", "*", "MemDB", ")", "Txn", "(", "write", "bool", ")", "*", "Txn", "{", "if", "write", "{", "db", ".", "writer", ".", "Lock", "(", ")", "\n", "}", "\n", "txn", ":=", "&", "Txn", "{", "db", ":", "db", ",", "write", ":", "write", ",", "rootTxn", ":", "db", ".", "getRoot", "(", ")", ".", "Txn", "(", ")", ",", "}", "\n", "return", "txn", "\n", "}" ]
// Txn is used to start a new transaction, in either read or write mode. // There can only be a single concurrent writer, but any number of readers.
[ "Txn", "is", "used", "to", "start", "a", "new", "transaction", "in", "either", "read", "or", "write", "mode", ".", "There", "can", "only", "be", "a", "single", "concurrent", "writer", "but", "any", "number", "of", "readers", "." ]
10278d3759e27502b741e52c7d8115d892e7723a
https://github.com/hashicorp/go-memdb/blob/10278d3759e27502b741e52c7d8115d892e7723a/memdb.go#L55-L65
train
hashicorp/go-memdb
memdb.go
Snapshot
func (db *MemDB) Snapshot() *MemDB { clone := &MemDB{ schema: db.schema, root: unsafe.Pointer(db.getRoot()), primary: false, } return clone }
go
func (db *MemDB) Snapshot() *MemDB { clone := &MemDB{ schema: db.schema, root: unsafe.Pointer(db.getRoot()), primary: false, } return clone }
[ "func", "(", "db", "*", "MemDB", ")", "Snapshot", "(", ")", "*", "MemDB", "{", "clone", ":=", "&", "MemDB", "{", "schema", ":", "db", ".", "schema", ",", "root", ":", "unsafe", ".", "Pointer", "(", "db", ".", "getRoot", "(", ")", ")", ",", "primary", ":", "false", ",", "}", "\n", "return", "clone", "\n", "}" ]
// Snapshot is used to capture a point-in-time snapshot // of the database that will not be affected by any write // operations to the existing DB.
[ "Snapshot", "is", "used", "to", "capture", "a", "point", "-", "in", "-", "time", "snapshot", "of", "the", "database", "that", "will", "not", "be", "affected", "by", "any", "write", "operations", "to", "the", "existing", "DB", "." ]
10278d3759e27502b741e52c7d8115d892e7723a
https://github.com/hashicorp/go-memdb/blob/10278d3759e27502b741e52c7d8115d892e7723a/memdb.go#L70-L77
train
hashicorp/go-memdb
memdb.go
initialize
func (db *MemDB) initialize() error { root := db.getRoot() for tName, tableSchema := range db.schema.Tables { for iName := range tableSchema.Indexes { index := iradix.New() path := indexPath(tName, iName) root, _, _ = root.Insert(path, index) } } db.root = unsafe.Pointer(root) return nil }
go
func (db *MemDB) initialize() error { root := db.getRoot() for tName, tableSchema := range db.schema.Tables { for iName := range tableSchema.Indexes { index := iradix.New() path := indexPath(tName, iName) root, _, _ = root.Insert(path, index) } } db.root = unsafe.Pointer(root) return nil }
[ "func", "(", "db", "*", "MemDB", ")", "initialize", "(", ")", "error", "{", "root", ":=", "db", ".", "getRoot", "(", ")", "\n", "for", "tName", ",", "tableSchema", ":=", "range", "db", ".", "schema", ".", "Tables", "{", "for", "iName", ":=", "range", "tableSchema", ".", "Indexes", "{", "index", ":=", "iradix", ".", "New", "(", ")", "\n", "path", ":=", "indexPath", "(", "tName", ",", "iName", ")", "\n", "root", ",", "_", ",", "_", "=", "root", ".", "Insert", "(", "path", ",", "index", ")", "\n", "}", "\n", "}", "\n", "db", ".", "root", "=", "unsafe", ".", "Pointer", "(", "root", ")", "\n", "return", "nil", "\n", "}" ]
// initialize is used to setup the DB for use after creation. This should // be called only once after allocating a MemDB.
[ "initialize", "is", "used", "to", "setup", "the", "DB", "for", "use", "after", "creation", ".", "This", "should", "be", "called", "only", "once", "after", "allocating", "a", "MemDB", "." ]
10278d3759e27502b741e52c7d8115d892e7723a
https://github.com/hashicorp/go-memdb/blob/10278d3759e27502b741e52c7d8115d892e7723a/memdb.go#L81-L92
train
hashicorp/go-memdb
index.go
IsIntType
func IsIntType(k reflect.Kind) (size int, okay bool) { switch k { case reflect.Int: return binary.MaxVarintLen64, true case reflect.Int8: return 2, true case reflect.Int16: return binary.MaxVarintLen16, true case reflect.Int32: return binary.MaxVarintLen32, true case reflect.Int64: return binary.MaxVarintLen64, true default: return 0, false } }
go
func IsIntType(k reflect.Kind) (size int, okay bool) { switch k { case reflect.Int: return binary.MaxVarintLen64, true case reflect.Int8: return 2, true case reflect.Int16: return binary.MaxVarintLen16, true case reflect.Int32: return binary.MaxVarintLen32, true case reflect.Int64: return binary.MaxVarintLen64, true default: return 0, false } }
[ "func", "IsIntType", "(", "k", "reflect", ".", "Kind", ")", "(", "size", "int", ",", "okay", "bool", ")", "{", "switch", "k", "{", "case", "reflect", ".", "Int", ":", "return", "binary", ".", "MaxVarintLen64", ",", "true", "\n", "case", "reflect", ".", "Int8", ":", "return", "2", ",", "true", "\n", "case", "reflect", ".", "Int16", ":", "return", "binary", ".", "MaxVarintLen16", ",", "true", "\n", "case", "reflect", ".", "Int32", ":", "return", "binary", ".", "MaxVarintLen32", ",", "true", "\n", "case", "reflect", ".", "Int64", ":", "return", "binary", ".", "MaxVarintLen64", ",", "true", "\n", "default", ":", "return", "0", ",", "false", "\n", "}", "\n", "}" ]
// IsIntType returns whether the passed type is a type of int and the number // of bytes needed to encode the type.
[ "IsIntType", "returns", "whether", "the", "passed", "type", "is", "a", "type", "of", "int", "and", "the", "number", "of", "bytes", "needed", "to", "encode", "the", "type", "." ]
10278d3759e27502b741e52c7d8115d892e7723a
https://github.com/hashicorp/go-memdb/blob/10278d3759e27502b741e52c7d8115d892e7723a/index.go#L328-L343
train
hashicorp/go-memdb
index.go
IsUintType
func IsUintType(k reflect.Kind) (size int, okay bool) { switch k { case reflect.Uint: return binary.MaxVarintLen64, true case reflect.Uint8: return 2, true case reflect.Uint16: return binary.MaxVarintLen16, true case reflect.Uint32: return binary.MaxVarintLen32, true case reflect.Uint64: return binary.MaxVarintLen64, true default: return 0, false } }
go
func IsUintType(k reflect.Kind) (size int, okay bool) { switch k { case reflect.Uint: return binary.MaxVarintLen64, true case reflect.Uint8: return 2, true case reflect.Uint16: return binary.MaxVarintLen16, true case reflect.Uint32: return binary.MaxVarintLen32, true case reflect.Uint64: return binary.MaxVarintLen64, true default: return 0, false } }
[ "func", "IsUintType", "(", "k", "reflect", ".", "Kind", ")", "(", "size", "int", ",", "okay", "bool", ")", "{", "switch", "k", "{", "case", "reflect", ".", "Uint", ":", "return", "binary", ".", "MaxVarintLen64", ",", "true", "\n", "case", "reflect", ".", "Uint8", ":", "return", "2", ",", "true", "\n", "case", "reflect", ".", "Uint16", ":", "return", "binary", ".", "MaxVarintLen16", ",", "true", "\n", "case", "reflect", ".", "Uint32", ":", "return", "binary", ".", "MaxVarintLen32", ",", "true", "\n", "case", "reflect", ".", "Uint64", ":", "return", "binary", ".", "MaxVarintLen64", ",", "true", "\n", "default", ":", "return", "0", ",", "false", "\n", "}", "\n", "}" ]
// IsUintType returns whether the passed type is a type of uint and the number // of bytes needed to encode the type.
[ "IsUintType", "returns", "whether", "the", "passed", "type", "is", "a", "type", "of", "uint", "and", "the", "number", "of", "bytes", "needed", "to", "encode", "the", "type", "." ]
10278d3759e27502b741e52c7d8115d892e7723a
https://github.com/hashicorp/go-memdb/blob/10278d3759e27502b741e52c7d8115d892e7723a/index.go#L401-L416
train
hashicorp/go-memdb
index.go
parseString
func (u *UUIDFieldIndex) parseString(s string, enforceLength bool) ([]byte, error) { // Verify the length l := len(s) if enforceLength && l != 36 { return nil, fmt.Errorf("UUID must be 36 characters") } else if l > 36 { return nil, fmt.Errorf("Invalid UUID length. UUID have 36 characters; got %d", l) } hyphens := strings.Count(s, "-") if hyphens > 4 { return nil, fmt.Errorf(`UUID should have maximum of 4 "-"; got %d`, hyphens) } // The sanitized length is the length of the original string without the "-". sanitized := strings.Replace(s, "-", "", -1) sanitizedLength := len(sanitized) if sanitizedLength%2 != 0 { return nil, fmt.Errorf("Input (without hyphens) must be even length") } dec, err := hex.DecodeString(sanitized) if err != nil { return nil, fmt.Errorf("Invalid UUID: %v", err) } return dec, nil }
go
func (u *UUIDFieldIndex) parseString(s string, enforceLength bool) ([]byte, error) { // Verify the length l := len(s) if enforceLength && l != 36 { return nil, fmt.Errorf("UUID must be 36 characters") } else if l > 36 { return nil, fmt.Errorf("Invalid UUID length. UUID have 36 characters; got %d", l) } hyphens := strings.Count(s, "-") if hyphens > 4 { return nil, fmt.Errorf(`UUID should have maximum of 4 "-"; got %d`, hyphens) } // The sanitized length is the length of the original string without the "-". sanitized := strings.Replace(s, "-", "", -1) sanitizedLength := len(sanitized) if sanitizedLength%2 != 0 { return nil, fmt.Errorf("Input (without hyphens) must be even length") } dec, err := hex.DecodeString(sanitized) if err != nil { return nil, fmt.Errorf("Invalid UUID: %v", err) } return dec, nil }
[ "func", "(", "u", "*", "UUIDFieldIndex", ")", "parseString", "(", "s", "string", ",", "enforceLength", "bool", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "// Verify the length", "l", ":=", "len", "(", "s", ")", "\n", "if", "enforceLength", "&&", "l", "!=", "36", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "else", "if", "l", ">", "36", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "l", ")", "\n", "}", "\n\n", "hyphens", ":=", "strings", ".", "Count", "(", "s", ",", "\"", "\"", ")", "\n", "if", "hyphens", ">", "4", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "`UUID should have maximum of 4 \"-\"; got %d`", ",", "hyphens", ")", "\n", "}", "\n\n", "// The sanitized length is the length of the original string without the \"-\".", "sanitized", ":=", "strings", ".", "Replace", "(", "s", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n", "sanitizedLength", ":=", "len", "(", "sanitized", ")", "\n", "if", "sanitizedLength", "%", "2", "!=", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "dec", ",", "err", ":=", "hex", ".", "DecodeString", "(", "sanitized", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "return", "dec", ",", "nil", "\n", "}" ]
// parseString parses a UUID from the string. If enforceLength is false, it will // parse a partial UUID. An error is returned if the input, stripped of hyphens, // is not even length.
[ "parseString", "parses", "a", "UUID", "from", "the", "string", ".", "If", "enforceLength", "is", "false", "it", "will", "parse", "a", "partial", "UUID", ".", "An", "error", "is", "returned", "if", "the", "input", "stripped", "of", "hyphens", "is", "not", "even", "length", "." ]
10278d3759e27502b741e52c7d8115d892e7723a
https://github.com/hashicorp/go-memdb/blob/10278d3759e27502b741e52c7d8115d892e7723a/index.go#L481-L508
train
hashicorp/go-memdb
index.go
fromBoolArgs
func fromBoolArgs(args []interface{}) ([]byte, error) { if len(args) != 1 { return nil, fmt.Errorf("must provide only a single argument") } if val, ok := args[0].(bool); !ok { return nil, fmt.Errorf("argument must be a boolean type: %#v", args[0]) } else if val { return []byte{1}, nil } return []byte{0}, nil }
go
func fromBoolArgs(args []interface{}) ([]byte, error) { if len(args) != 1 { return nil, fmt.Errorf("must provide only a single argument") } if val, ok := args[0].(bool); !ok { return nil, fmt.Errorf("argument must be a boolean type: %#v", args[0]) } else if val { return []byte{1}, nil } return []byte{0}, nil }
[ "func", "fromBoolArgs", "(", "args", "[", "]", "interface", "{", "}", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "len", "(", "args", ")", "!=", "1", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "val", ",", "ok", ":=", "args", "[", "0", "]", ".", "(", "bool", ")", ";", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "args", "[", "0", "]", ")", "\n", "}", "else", "if", "val", "{", "return", "[", "]", "byte", "{", "1", "}", ",", "nil", "\n", "}", "\n\n", "return", "[", "]", "byte", "{", "0", "}", ",", "nil", "\n", "}" ]
// fromBoolArgs is a helper that expects only a single boolean argument and // returns a single length byte array containing either a one or zero depending // on whether the passed input is true or false respectively.
[ "fromBoolArgs", "is", "a", "helper", "that", "expects", "only", "a", "single", "boolean", "argument", "and", "returns", "a", "single", "length", "byte", "array", "containing", "either", "a", "one", "or", "zero", "depending", "on", "whether", "the", "passed", "input", "is", "true", "or", "false", "respectively", "." ]
10278d3759e27502b741e52c7d8115d892e7723a
https://github.com/hashicorp/go-memdb/blob/10278d3759e27502b741e52c7d8115d892e7723a/index.go#L570-L582
train
hashicorp/go-memdb
watch_few.go
watchFew
func watchFew(ctx context.Context, ch []<-chan struct{}) error { select { case <-ch[0]: return nil case <-ch[1]: return nil case <-ch[2]: return nil case <-ch[3]: return nil case <-ch[4]: return nil case <-ch[5]: return nil case <-ch[6]: return nil case <-ch[7]: return nil case <-ch[8]: return nil case <-ch[9]: return nil case <-ch[10]: return nil case <-ch[11]: return nil case <-ch[12]: return nil case <-ch[13]: return nil case <-ch[14]: return nil case <-ch[15]: return nil case <-ch[16]: return nil case <-ch[17]: return nil case <-ch[18]: return nil case <-ch[19]: return nil case <-ch[20]: return nil case <-ch[21]: return nil case <-ch[22]: return nil case <-ch[23]: return nil case <-ch[24]: return nil case <-ch[25]: return nil case <-ch[26]: return nil case <-ch[27]: return nil case <-ch[28]: return nil case <-ch[29]: return nil case <-ch[30]: return nil case <-ch[31]: return nil case <-ctx.Done(): return ctx.Err() } }
go
func watchFew(ctx context.Context, ch []<-chan struct{}) error { select { case <-ch[0]: return nil case <-ch[1]: return nil case <-ch[2]: return nil case <-ch[3]: return nil case <-ch[4]: return nil case <-ch[5]: return nil case <-ch[6]: return nil case <-ch[7]: return nil case <-ch[8]: return nil case <-ch[9]: return nil case <-ch[10]: return nil case <-ch[11]: return nil case <-ch[12]: return nil case <-ch[13]: return nil case <-ch[14]: return nil case <-ch[15]: return nil case <-ch[16]: return nil case <-ch[17]: return nil case <-ch[18]: return nil case <-ch[19]: return nil case <-ch[20]: return nil case <-ch[21]: return nil case <-ch[22]: return nil case <-ch[23]: return nil case <-ch[24]: return nil case <-ch[25]: return nil case <-ch[26]: return nil case <-ch[27]: return nil case <-ch[28]: return nil case <-ch[29]: return nil case <-ch[30]: return nil case <-ch[31]: return nil case <-ctx.Done(): return ctx.Err() } }
[ "func", "watchFew", "(", "ctx", "context", ".", "Context", ",", "ch", "[", "]", "<-", "chan", "struct", "{", "}", ")", "error", "{", "select", "{", "case", "<-", "ch", "[", "0", "]", ":", "return", "nil", "\n\n", "case", "<-", "ch", "[", "1", "]", ":", "return", "nil", "\n\n", "case", "<-", "ch", "[", "2", "]", ":", "return", "nil", "\n\n", "case", "<-", "ch", "[", "3", "]", ":", "return", "nil", "\n\n", "case", "<-", "ch", "[", "4", "]", ":", "return", "nil", "\n\n", "case", "<-", "ch", "[", "5", "]", ":", "return", "nil", "\n\n", "case", "<-", "ch", "[", "6", "]", ":", "return", "nil", "\n\n", "case", "<-", "ch", "[", "7", "]", ":", "return", "nil", "\n\n", "case", "<-", "ch", "[", "8", "]", ":", "return", "nil", "\n\n", "case", "<-", "ch", "[", "9", "]", ":", "return", "nil", "\n\n", "case", "<-", "ch", "[", "10", "]", ":", "return", "nil", "\n\n", "case", "<-", "ch", "[", "11", "]", ":", "return", "nil", "\n\n", "case", "<-", "ch", "[", "12", "]", ":", "return", "nil", "\n\n", "case", "<-", "ch", "[", "13", "]", ":", "return", "nil", "\n\n", "case", "<-", "ch", "[", "14", "]", ":", "return", "nil", "\n\n", "case", "<-", "ch", "[", "15", "]", ":", "return", "nil", "\n\n", "case", "<-", "ch", "[", "16", "]", ":", "return", "nil", "\n\n", "case", "<-", "ch", "[", "17", "]", ":", "return", "nil", "\n\n", "case", "<-", "ch", "[", "18", "]", ":", "return", "nil", "\n\n", "case", "<-", "ch", "[", "19", "]", ":", "return", "nil", "\n\n", "case", "<-", "ch", "[", "20", "]", ":", "return", "nil", "\n\n", "case", "<-", "ch", "[", "21", "]", ":", "return", "nil", "\n\n", "case", "<-", "ch", "[", "22", "]", ":", "return", "nil", "\n\n", "case", "<-", "ch", "[", "23", "]", ":", "return", "nil", "\n\n", "case", "<-", "ch", "[", "24", "]", ":", "return", "nil", "\n\n", "case", "<-", "ch", "[", "25", "]", ":", "return", "nil", "\n\n", "case", "<-", "ch", "[", "26", "]", ":", "return", "nil", "\n\n", "case", "<-", "ch", "[", "27", "]", ":", "return", "nil", "\n\n", "case", "<-", "ch", "[", "28", "]", ":", "return", "nil", "\n\n", "case", "<-", "ch", "[", "29", "]", ":", "return", "nil", "\n\n", "case", "<-", "ch", "[", "30", "]", ":", "return", "nil", "\n\n", "case", "<-", "ch", "[", "31", "]", ":", "return", "nil", "\n\n", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "ctx", ".", "Err", "(", ")", "\n", "}", "\n", "}" ]
// watchFew is used if there are only a few watchers as a performance // optimization.
[ "watchFew", "is", "used", "if", "there", "are", "only", "a", "few", "watchers", "as", "a", "performance", "optimization", "." ]
10278d3759e27502b741e52c7d8115d892e7723a
https://github.com/hashicorp/go-memdb/blob/10278d3759e27502b741e52c7d8115d892e7723a/watch_few.go#L15-L117
train
hashicorp/go-memdb
watch.go
Add
func (w WatchSet) Add(watchCh <-chan struct{}) { if w == nil { return } if _, ok := w[watchCh]; !ok { w[watchCh] = struct{}{} } }
go
func (w WatchSet) Add(watchCh <-chan struct{}) { if w == nil { return } if _, ok := w[watchCh]; !ok { w[watchCh] = struct{}{} } }
[ "func", "(", "w", "WatchSet", ")", "Add", "(", "watchCh", "<-", "chan", "struct", "{", "}", ")", "{", "if", "w", "==", "nil", "{", "return", "\n", "}", "\n\n", "if", "_", ",", "ok", ":=", "w", "[", "watchCh", "]", ";", "!", "ok", "{", "w", "[", "watchCh", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "}" ]
// Add appends a watchCh to the WatchSet if non-nil.
[ "Add", "appends", "a", "watchCh", "to", "the", "WatchSet", "if", "non", "-", "nil", "." ]
10278d3759e27502b741e52c7d8115d892e7723a
https://github.com/hashicorp/go-memdb/blob/10278d3759e27502b741e52c7d8115d892e7723a/watch.go#L17-L25
train
hashicorp/go-memdb
watch.go
Watch
func (w WatchSet) Watch(timeoutCh <-chan time.Time) bool { if w == nil { return false } // Create a context that gets cancelled when the timeout is triggered ctx, cancel := context.WithCancel(context.Background()) defer cancel() go func() { select { case <-timeoutCh: cancel() case <-ctx.Done(): } }() return w.WatchCtx(ctx) == context.Canceled }
go
func (w WatchSet) Watch(timeoutCh <-chan time.Time) bool { if w == nil { return false } // Create a context that gets cancelled when the timeout is triggered ctx, cancel := context.WithCancel(context.Background()) defer cancel() go func() { select { case <-timeoutCh: cancel() case <-ctx.Done(): } }() return w.WatchCtx(ctx) == context.Canceled }
[ "func", "(", "w", "WatchSet", ")", "Watch", "(", "timeoutCh", "<-", "chan", "time", ".", "Time", ")", "bool", "{", "if", "w", "==", "nil", "{", "return", "false", "\n", "}", "\n\n", "// Create a context that gets cancelled when the timeout is triggered", "ctx", ",", "cancel", ":=", "context", ".", "WithCancel", "(", "context", ".", "Background", "(", ")", ")", "\n", "defer", "cancel", "(", ")", "\n\n", "go", "func", "(", ")", "{", "select", "{", "case", "<-", "timeoutCh", ":", "cancel", "(", ")", "\n", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "}", "\n", "}", "(", ")", "\n\n", "return", "w", ".", "WatchCtx", "(", "ctx", ")", "==", "context", ".", "Canceled", "\n", "}" ]
// Watch is used to wait for either the watch set to trigger or a timeout. // Returns true on timeout.
[ "Watch", "is", "used", "to", "wait", "for", "either", "the", "watch", "set", "to", "trigger", "or", "a", "timeout", ".", "Returns", "true", "on", "timeout", "." ]
10278d3759e27502b741e52c7d8115d892e7723a
https://github.com/hashicorp/go-memdb/blob/10278d3759e27502b741e52c7d8115d892e7723a/watch.go#L47-L65
train
hashicorp/go-memdb
watch.go
WatchCtx
func (w WatchSet) WatchCtx(ctx context.Context) error { if w == nil { return nil } if n := len(w); n <= aFew { idx := 0 chunk := make([]<-chan struct{}, aFew) for watchCh := range w { chunk[idx] = watchCh idx++ } return watchFew(ctx, chunk) } return w.watchMany(ctx) }
go
func (w WatchSet) WatchCtx(ctx context.Context) error { if w == nil { return nil } if n := len(w); n <= aFew { idx := 0 chunk := make([]<-chan struct{}, aFew) for watchCh := range w { chunk[idx] = watchCh idx++ } return watchFew(ctx, chunk) } return w.watchMany(ctx) }
[ "func", "(", "w", "WatchSet", ")", "WatchCtx", "(", "ctx", "context", ".", "Context", ")", "error", "{", "if", "w", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "if", "n", ":=", "len", "(", "w", ")", ";", "n", "<=", "aFew", "{", "idx", ":=", "0", "\n", "chunk", ":=", "make", "(", "[", "]", "<-", "chan", "struct", "{", "}", ",", "aFew", ")", "\n", "for", "watchCh", ":=", "range", "w", "{", "chunk", "[", "idx", "]", "=", "watchCh", "\n", "idx", "++", "\n", "}", "\n", "return", "watchFew", "(", "ctx", ",", "chunk", ")", "\n", "}", "\n\n", "return", "w", ".", "watchMany", "(", "ctx", ")", "\n", "}" ]
// WatchCtx is used to wait for either the watch set to trigger or for the // context to be cancelled. Watch with a timeout channel can be mimicked by // creating a context with a deadline. WatchCtx should be preferred over Watch.
[ "WatchCtx", "is", "used", "to", "wait", "for", "either", "the", "watch", "set", "to", "trigger", "or", "for", "the", "context", "to", "be", "cancelled", ".", "Watch", "with", "a", "timeout", "channel", "can", "be", "mimicked", "by", "creating", "a", "context", "with", "a", "deadline", ".", "WatchCtx", "should", "be", "preferred", "over", "Watch", "." ]
10278d3759e27502b741e52c7d8115d892e7723a
https://github.com/hashicorp/go-memdb/blob/10278d3759e27502b741e52c7d8115d892e7723a/watch.go#L70-L86
train
hashicorp/go-memdb
watch.go
watchMany
func (w WatchSet) watchMany(ctx context.Context) error { // Set up a goroutine for each watcher. triggerCh := make(chan struct{}, 1) watcher := func(chunk []<-chan struct{}) { if err := watchFew(ctx, chunk); err == nil { select { case triggerCh <- struct{}{}: default: } } } // Apportion the watch channels into chunks we can feed into the // watchFew helper. idx := 0 chunk := make([]<-chan struct{}, aFew) for watchCh := range w { subIdx := idx % aFew chunk[subIdx] = watchCh idx++ // Fire off this chunk and start a fresh one. if idx%aFew == 0 { go watcher(chunk) chunk = make([]<-chan struct{}, aFew) } } // Make sure to watch any residual channels in the last chunk. if idx%aFew != 0 { go watcher(chunk) } // Wait for a channel to trigger or timeout. select { case <-triggerCh: return nil case <-ctx.Done(): return ctx.Err() } }
go
func (w WatchSet) watchMany(ctx context.Context) error { // Set up a goroutine for each watcher. triggerCh := make(chan struct{}, 1) watcher := func(chunk []<-chan struct{}) { if err := watchFew(ctx, chunk); err == nil { select { case triggerCh <- struct{}{}: default: } } } // Apportion the watch channels into chunks we can feed into the // watchFew helper. idx := 0 chunk := make([]<-chan struct{}, aFew) for watchCh := range w { subIdx := idx % aFew chunk[subIdx] = watchCh idx++ // Fire off this chunk and start a fresh one. if idx%aFew == 0 { go watcher(chunk) chunk = make([]<-chan struct{}, aFew) } } // Make sure to watch any residual channels in the last chunk. if idx%aFew != 0 { go watcher(chunk) } // Wait for a channel to trigger or timeout. select { case <-triggerCh: return nil case <-ctx.Done(): return ctx.Err() } }
[ "func", "(", "w", "WatchSet", ")", "watchMany", "(", "ctx", "context", ".", "Context", ")", "error", "{", "// Set up a goroutine for each watcher.", "triggerCh", ":=", "make", "(", "chan", "struct", "{", "}", ",", "1", ")", "\n", "watcher", ":=", "func", "(", "chunk", "[", "]", "<-", "chan", "struct", "{", "}", ")", "{", "if", "err", ":=", "watchFew", "(", "ctx", ",", "chunk", ")", ";", "err", "==", "nil", "{", "select", "{", "case", "triggerCh", "<-", "struct", "{", "}", "{", "}", ":", "default", ":", "}", "\n", "}", "\n", "}", "\n\n", "// Apportion the watch channels into chunks we can feed into the", "// watchFew helper.", "idx", ":=", "0", "\n", "chunk", ":=", "make", "(", "[", "]", "<-", "chan", "struct", "{", "}", ",", "aFew", ")", "\n", "for", "watchCh", ":=", "range", "w", "{", "subIdx", ":=", "idx", "%", "aFew", "\n", "chunk", "[", "subIdx", "]", "=", "watchCh", "\n", "idx", "++", "\n\n", "// Fire off this chunk and start a fresh one.", "if", "idx", "%", "aFew", "==", "0", "{", "go", "watcher", "(", "chunk", ")", "\n", "chunk", "=", "make", "(", "[", "]", "<-", "chan", "struct", "{", "}", ",", "aFew", ")", "\n", "}", "\n", "}", "\n\n", "// Make sure to watch any residual channels in the last chunk.", "if", "idx", "%", "aFew", "!=", "0", "{", "go", "watcher", "(", "chunk", ")", "\n", "}", "\n\n", "// Wait for a channel to trigger or timeout.", "select", "{", "case", "<-", "triggerCh", ":", "return", "nil", "\n", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "ctx", ".", "Err", "(", ")", "\n", "}", "\n", "}" ]
// watchMany is used if there are many watchers.
[ "watchMany", "is", "used", "if", "there", "are", "many", "watchers", "." ]
10278d3759e27502b741e52c7d8115d892e7723a
https://github.com/hashicorp/go-memdb/blob/10278d3759e27502b741e52c7d8115d892e7723a/watch.go#L89-L129
train
google/codesearch
index/regexp.go
and
func (q *Query) and(r *Query) *Query { return q.andOr(r, QAnd) }
go
func (q *Query) and(r *Query) *Query { return q.andOr(r, QAnd) }
[ "func", "(", "q", "*", "Query", ")", "and", "(", "r", "*", "Query", ")", "*", "Query", "{", "return", "q", ".", "andOr", "(", "r", ",", "QAnd", ")", "\n", "}" ]
// and returns the query q AND r, possibly reusing q's and r's storage.
[ "and", "returns", "the", "query", "q", "AND", "r", "possibly", "reusing", "q", "s", "and", "r", "s", "storage", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/regexp.go#L41-L43
train
google/codesearch
index/regexp.go
or
func (q *Query) or(r *Query) *Query { return q.andOr(r, QOr) }
go
func (q *Query) or(r *Query) *Query { return q.andOr(r, QOr) }
[ "func", "(", "q", "*", "Query", ")", "or", "(", "r", "*", "Query", ")", "*", "Query", "{", "return", "q", ".", "andOr", "(", "r", ",", "QOr", ")", "\n", "}" ]
// or returns the query q OR r, possibly reusing q's and r's storage.
[ "or", "returns", "the", "query", "q", "OR", "r", "possibly", "reusing", "q", "s", "and", "r", "s", "storage", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/regexp.go#L46-L48
train
google/codesearch
index/regexp.go
implies
func (q *Query) implies(r *Query) bool { if q.Op == QNone || r.Op == QAll { // False implies everything. // Everything implies True. return true } if q.Op == QAll || r.Op == QNone { // True implies nothing. // Nothing implies False. return false } if q.Op == QAnd || (q.Op == QOr && len(q.Trigram) == 1 && len(q.Sub) == 0) { return trigramsImply(q.Trigram, r) } if q.Op == QOr && r.Op == QOr && len(q.Trigram) > 0 && len(q.Sub) == 0 && stringSet.isSubsetOf(q.Trigram, r.Trigram) { return true } return false }
go
func (q *Query) implies(r *Query) bool { if q.Op == QNone || r.Op == QAll { // False implies everything. // Everything implies True. return true } if q.Op == QAll || r.Op == QNone { // True implies nothing. // Nothing implies False. return false } if q.Op == QAnd || (q.Op == QOr && len(q.Trigram) == 1 && len(q.Sub) == 0) { return trigramsImply(q.Trigram, r) } if q.Op == QOr && r.Op == QOr && len(q.Trigram) > 0 && len(q.Sub) == 0 && stringSet.isSubsetOf(q.Trigram, r.Trigram) { return true } return false }
[ "func", "(", "q", "*", "Query", ")", "implies", "(", "r", "*", "Query", ")", "bool", "{", "if", "q", ".", "Op", "==", "QNone", "||", "r", ".", "Op", "==", "QAll", "{", "// False implies everything.", "// Everything implies True.", "return", "true", "\n", "}", "\n", "if", "q", ".", "Op", "==", "QAll", "||", "r", ".", "Op", "==", "QNone", "{", "// True implies nothing.", "// Nothing implies False.", "return", "false", "\n", "}", "\n\n", "if", "q", ".", "Op", "==", "QAnd", "||", "(", "q", ".", "Op", "==", "QOr", "&&", "len", "(", "q", ".", "Trigram", ")", "==", "1", "&&", "len", "(", "q", ".", "Sub", ")", "==", "0", ")", "{", "return", "trigramsImply", "(", "q", ".", "Trigram", ",", "r", ")", "\n", "}", "\n\n", "if", "q", ".", "Op", "==", "QOr", "&&", "r", ".", "Op", "==", "QOr", "&&", "len", "(", "q", ".", "Trigram", ")", ">", "0", "&&", "len", "(", "q", ".", "Sub", ")", "==", "0", "&&", "stringSet", ".", "isSubsetOf", "(", "q", ".", "Trigram", ",", "r", ".", "Trigram", ")", "{", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// implies reports whether q implies r. // It is okay for it to return false negatives.
[ "implies", "reports", "whether", "q", "implies", "r", ".", "It", "is", "okay", "for", "it", "to", "return", "false", "negatives", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/regexp.go#L174-L196
train
google/codesearch
index/regexp.go
maybeRewrite
func (q *Query) maybeRewrite(op QueryOp) { if q.Op != QAnd && q.Op != QOr { return } // AND/OR doing real work? Can't rewrite. n := len(q.Sub) + len(q.Trigram) if n > 1 { return } // Nothing left in the AND/OR? if n == 0 { if q.Op == QAnd { q.Op = QAll } else { q.Op = QNone } return } // Just a sub-node: throw away wrapper. if len(q.Sub) == 1 { *q = *q.Sub[0] } // Just a trigram: can use either op. q.Op = op }
go
func (q *Query) maybeRewrite(op QueryOp) { if q.Op != QAnd && q.Op != QOr { return } // AND/OR doing real work? Can't rewrite. n := len(q.Sub) + len(q.Trigram) if n > 1 { return } // Nothing left in the AND/OR? if n == 0 { if q.Op == QAnd { q.Op = QAll } else { q.Op = QNone } return } // Just a sub-node: throw away wrapper. if len(q.Sub) == 1 { *q = *q.Sub[0] } // Just a trigram: can use either op. q.Op = op }
[ "func", "(", "q", "*", "Query", ")", "maybeRewrite", "(", "op", "QueryOp", ")", "{", "if", "q", ".", "Op", "!=", "QAnd", "&&", "q", ".", "Op", "!=", "QOr", "{", "return", "\n", "}", "\n\n", "// AND/OR doing real work? Can't rewrite.", "n", ":=", "len", "(", "q", ".", "Sub", ")", "+", "len", "(", "q", ".", "Trigram", ")", "\n", "if", "n", ">", "1", "{", "return", "\n", "}", "\n\n", "// Nothing left in the AND/OR?", "if", "n", "==", "0", "{", "if", "q", ".", "Op", "==", "QAnd", "{", "q", ".", "Op", "=", "QAll", "\n", "}", "else", "{", "q", ".", "Op", "=", "QNone", "\n", "}", "\n", "return", "\n", "}", "\n\n", "// Just a sub-node: throw away wrapper.", "if", "len", "(", "q", ".", "Sub", ")", "==", "1", "{", "*", "q", "=", "*", "q", ".", "Sub", "[", "0", "]", "\n", "}", "\n\n", "// Just a trigram: can use either op.", "q", ".", "Op", "=", "op", "\n", "}" ]
// maybeRewrite rewrites q to use op if it is possible to do so // without changing the meaning. It also simplifies if the node // is an empty OR or AND.
[ "maybeRewrite", "rewrites", "q", "to", "use", "op", "if", "it", "is", "possible", "to", "do", "so", "without", "changing", "the", "meaning", ".", "It", "also", "simplifies", "if", "the", "node", "is", "an", "empty", "OR", "or", "AND", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/regexp.go#L229-L257
train
google/codesearch
index/regexp.go
andTrigrams
func (q *Query) andTrigrams(t stringSet) *Query { if t.minLen() < 3 { // If there is a short string, we can't guarantee // that any trigrams must be present, so use ALL. // q AND ALL = q. return q } //println("andtrigrams", strings.Join(t, ",")) or := noneQuery for _, tt := range t { var trig stringSet for i := 0; i+3 <= len(tt); i++ { trig.add(tt[i : i+3]) } trig.clean(false) //println(tt, "trig", strings.Join(trig, ",")) or = or.or(&Query{Op: QAnd, Trigram: trig}) } q = q.and(or) return q }
go
func (q *Query) andTrigrams(t stringSet) *Query { if t.minLen() < 3 { // If there is a short string, we can't guarantee // that any trigrams must be present, so use ALL. // q AND ALL = q. return q } //println("andtrigrams", strings.Join(t, ",")) or := noneQuery for _, tt := range t { var trig stringSet for i := 0; i+3 <= len(tt); i++ { trig.add(tt[i : i+3]) } trig.clean(false) //println(tt, "trig", strings.Join(trig, ",")) or = or.or(&Query{Op: QAnd, Trigram: trig}) } q = q.and(or) return q }
[ "func", "(", "q", "*", "Query", ")", "andTrigrams", "(", "t", "stringSet", ")", "*", "Query", "{", "if", "t", ".", "minLen", "(", ")", "<", "3", "{", "// If there is a short string, we can't guarantee", "// that any trigrams must be present, so use ALL.", "// q AND ALL = q.", "return", "q", "\n", "}", "\n\n", "//println(\"andtrigrams\", strings.Join(t, \",\"))", "or", ":=", "noneQuery", "\n", "for", "_", ",", "tt", ":=", "range", "t", "{", "var", "trig", "stringSet", "\n", "for", "i", ":=", "0", ";", "i", "+", "3", "<=", "len", "(", "tt", ")", ";", "i", "++", "{", "trig", ".", "add", "(", "tt", "[", "i", ":", "i", "+", "3", "]", ")", "\n", "}", "\n", "trig", ".", "clean", "(", "false", ")", "\n", "//println(tt, \"trig\", strings.Join(trig, \",\"))", "or", "=", "or", ".", "or", "(", "&", "Query", "{", "Op", ":", "QAnd", ",", "Trigram", ":", "trig", "}", ")", "\n", "}", "\n", "q", "=", "q", ".", "and", "(", "or", ")", "\n", "return", "q", "\n", "}" ]
// andTrigrams returns q AND the OR of the AND of the trigrams present in each string.
[ "andTrigrams", "returns", "q", "AND", "the", "OR", "of", "the", "AND", "of", "the", "trigrams", "present", "in", "each", "string", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/regexp.go#L260-L281
train
google/codesearch
index/regexp.go
RegexpQuery
func RegexpQuery(re *syntax.Regexp) *Query { info := analyze(re) info.simplify(true) info.addExact() return info.match }
go
func RegexpQuery(re *syntax.Regexp) *Query { info := analyze(re) info.simplify(true) info.addExact() return info.match }
[ "func", "RegexpQuery", "(", "re", "*", "syntax", ".", "Regexp", ")", "*", "Query", "{", "info", ":=", "analyze", "(", "re", ")", "\n", "info", ".", "simplify", "(", "true", ")", "\n", "info", ".", "addExact", "(", ")", "\n", "return", "info", ".", "match", "\n", "}" ]
// RegexpQuery returns a Query for the given regexp.
[ "RegexpQuery", "returns", "a", "Query", "for", "the", "given", "regexp", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/regexp.go#L333-L338
train
google/codesearch
index/regexp.go
anyMatch
func anyMatch() regexpInfo { return regexpInfo{ canEmpty: true, prefix: []string{""}, suffix: []string{""}, match: allQuery, } }
go
func anyMatch() regexpInfo { return regexpInfo{ canEmpty: true, prefix: []string{""}, suffix: []string{""}, match: allQuery, } }
[ "func", "anyMatch", "(", ")", "regexpInfo", "{", "return", "regexpInfo", "{", "canEmpty", ":", "true", ",", "prefix", ":", "[", "]", "string", "{", "\"", "\"", "}", ",", "suffix", ":", "[", "]", "string", "{", "\"", "\"", "}", ",", "match", ":", "allQuery", ",", "}", "\n", "}" ]
// anyMatch returns the regexpInfo describing a regexp that // matches any string.
[ "anyMatch", "returns", "the", "regexpInfo", "describing", "a", "regexp", "that", "matches", "any", "string", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/regexp.go#L382-L389
train
google/codesearch
index/regexp.go
fold
func fold(f func(x, y regexpInfo) regexpInfo, sub []*syntax.Regexp, zero regexpInfo) regexpInfo { if len(sub) == 0 { return zero } if len(sub) == 1 { return analyze(sub[0]) } info := f(analyze(sub[0]), analyze(sub[1])) for i := 2; i < len(sub); i++ { info = f(info, analyze(sub[i])) } return info }
go
func fold(f func(x, y regexpInfo) regexpInfo, sub []*syntax.Regexp, zero regexpInfo) regexpInfo { if len(sub) == 0 { return zero } if len(sub) == 1 { return analyze(sub[0]) } info := f(analyze(sub[0]), analyze(sub[1])) for i := 2; i < len(sub); i++ { info = f(info, analyze(sub[i])) } return info }
[ "func", "fold", "(", "f", "func", "(", "x", ",", "y", "regexpInfo", ")", "regexpInfo", ",", "sub", "[", "]", "*", "syntax", ".", "Regexp", ",", "zero", "regexpInfo", ")", "regexpInfo", "{", "if", "len", "(", "sub", ")", "==", "0", "{", "return", "zero", "\n", "}", "\n", "if", "len", "(", "sub", ")", "==", "1", "{", "return", "analyze", "(", "sub", "[", "0", "]", ")", "\n", "}", "\n", "info", ":=", "f", "(", "analyze", "(", "sub", "[", "0", "]", ")", ",", "analyze", "(", "sub", "[", "1", "]", ")", ")", "\n", "for", "i", ":=", "2", ";", "i", "<", "len", "(", "sub", ")", ";", "i", "++", "{", "info", "=", "f", "(", "info", ",", "analyze", "(", "sub", "[", "i", "]", ")", ")", "\n", "}", "\n", "return", "info", "\n", "}" ]
// fold is the usual higher-order function.
[ "fold", "is", "the", "usual", "higher", "-", "order", "function", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/regexp.go#L543-L555
train
google/codesearch
index/regexp.go
concat
func concat(x, y regexpInfo) (out regexpInfo) { //println("concat", x.String(), "...", y.String()) //defer func() { println("->", out.String()) }() var xy regexpInfo xy.match = x.match.and(y.match) if x.exact.have() && y.exact.have() { xy.exact = x.exact.cross(y.exact, false) } else { if x.exact.have() { xy.prefix = x.exact.cross(y.prefix, false) } else { xy.prefix = x.prefix if x.canEmpty { xy.prefix = xy.prefix.union(y.prefix, false) } } if y.exact.have() { xy.suffix = x.suffix.cross(y.exact, true) } else { xy.suffix = y.suffix if y.canEmpty { xy.suffix = xy.suffix.union(x.suffix, true) } } } // If all the possible strings in the cross product of x.suffix // and y.prefix are long enough, then the trigram for one // of them must be present and would not necessarily be // accounted for in xy.prefix or xy.suffix yet. Cut things off // at maxSet just to keep the sets manageable. if !x.exact.have() && !y.exact.have() && x.suffix.size() <= maxSet && y.prefix.size() <= maxSet && x.suffix.minLen()+y.prefix.minLen() >= 3 { xy.match = xy.match.andTrigrams(x.suffix.cross(y.prefix, false)) } xy.simplify(false) return xy }
go
func concat(x, y regexpInfo) (out regexpInfo) { //println("concat", x.String(), "...", y.String()) //defer func() { println("->", out.String()) }() var xy regexpInfo xy.match = x.match.and(y.match) if x.exact.have() && y.exact.have() { xy.exact = x.exact.cross(y.exact, false) } else { if x.exact.have() { xy.prefix = x.exact.cross(y.prefix, false) } else { xy.prefix = x.prefix if x.canEmpty { xy.prefix = xy.prefix.union(y.prefix, false) } } if y.exact.have() { xy.suffix = x.suffix.cross(y.exact, true) } else { xy.suffix = y.suffix if y.canEmpty { xy.suffix = xy.suffix.union(x.suffix, true) } } } // If all the possible strings in the cross product of x.suffix // and y.prefix are long enough, then the trigram for one // of them must be present and would not necessarily be // accounted for in xy.prefix or xy.suffix yet. Cut things off // at maxSet just to keep the sets manageable. if !x.exact.have() && !y.exact.have() && x.suffix.size() <= maxSet && y.prefix.size() <= maxSet && x.suffix.minLen()+y.prefix.minLen() >= 3 { xy.match = xy.match.andTrigrams(x.suffix.cross(y.prefix, false)) } xy.simplify(false) return xy }
[ "func", "concat", "(", "x", ",", "y", "regexpInfo", ")", "(", "out", "regexpInfo", ")", "{", "//println(\"concat\", x.String(), \"...\", y.String())", "//defer func() { println(\"->\", out.String()) }()", "var", "xy", "regexpInfo", "\n", "xy", ".", "match", "=", "x", ".", "match", ".", "and", "(", "y", ".", "match", ")", "\n", "if", "x", ".", "exact", ".", "have", "(", ")", "&&", "y", ".", "exact", ".", "have", "(", ")", "{", "xy", ".", "exact", "=", "x", ".", "exact", ".", "cross", "(", "y", ".", "exact", ",", "false", ")", "\n", "}", "else", "{", "if", "x", ".", "exact", ".", "have", "(", ")", "{", "xy", ".", "prefix", "=", "x", ".", "exact", ".", "cross", "(", "y", ".", "prefix", ",", "false", ")", "\n", "}", "else", "{", "xy", ".", "prefix", "=", "x", ".", "prefix", "\n", "if", "x", ".", "canEmpty", "{", "xy", ".", "prefix", "=", "xy", ".", "prefix", ".", "union", "(", "y", ".", "prefix", ",", "false", ")", "\n", "}", "\n", "}", "\n", "if", "y", ".", "exact", ".", "have", "(", ")", "{", "xy", ".", "suffix", "=", "x", ".", "suffix", ".", "cross", "(", "y", ".", "exact", ",", "true", ")", "\n", "}", "else", "{", "xy", ".", "suffix", "=", "y", ".", "suffix", "\n", "if", "y", ".", "canEmpty", "{", "xy", ".", "suffix", "=", "xy", ".", "suffix", ".", "union", "(", "x", ".", "suffix", ",", "true", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// If all the possible strings in the cross product of x.suffix", "// and y.prefix are long enough, then the trigram for one", "// of them must be present and would not necessarily be", "// accounted for in xy.prefix or xy.suffix yet. Cut things off", "// at maxSet just to keep the sets manageable.", "if", "!", "x", ".", "exact", ".", "have", "(", ")", "&&", "!", "y", ".", "exact", ".", "have", "(", ")", "&&", "x", ".", "suffix", ".", "size", "(", ")", "<=", "maxSet", "&&", "y", ".", "prefix", ".", "size", "(", ")", "<=", "maxSet", "&&", "x", ".", "suffix", ".", "minLen", "(", ")", "+", "y", ".", "prefix", ".", "minLen", "(", ")", ">=", "3", "{", "xy", ".", "match", "=", "xy", ".", "match", ".", "andTrigrams", "(", "x", ".", "suffix", ".", "cross", "(", "y", ".", "prefix", ",", "false", ")", ")", "\n", "}", "\n\n", "xy", ".", "simplify", "(", "false", ")", "\n", "return", "xy", "\n", "}" ]
// concat returns the regexp info for xy given x and y.
[ "concat", "returns", "the", "regexp", "info", "for", "xy", "given", "x", "and", "y", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/regexp.go#L558-L597
train
google/codesearch
index/regexp.go
alternate
func alternate(x, y regexpInfo) (out regexpInfo) { //println("alternate", x.String(), "...", y.String()) //defer func() { println("->", out.String()) }() var xy regexpInfo if x.exact.have() && y.exact.have() { xy.exact = x.exact.union(y.exact, false) } else if x.exact.have() { xy.prefix = x.exact.union(y.prefix, false) xy.suffix = x.exact.union(y.suffix, true) x.addExact() } else if y.exact.have() { xy.prefix = x.prefix.union(y.exact, false) xy.suffix = x.suffix.union(y.exact.copy(), true) y.addExact() } else { xy.prefix = x.prefix.union(y.prefix, false) xy.suffix = x.suffix.union(y.suffix, true) } xy.canEmpty = x.canEmpty || y.canEmpty xy.match = x.match.or(y.match) xy.simplify(false) return xy }
go
func alternate(x, y regexpInfo) (out regexpInfo) { //println("alternate", x.String(), "...", y.String()) //defer func() { println("->", out.String()) }() var xy regexpInfo if x.exact.have() && y.exact.have() { xy.exact = x.exact.union(y.exact, false) } else if x.exact.have() { xy.prefix = x.exact.union(y.prefix, false) xy.suffix = x.exact.union(y.suffix, true) x.addExact() } else if y.exact.have() { xy.prefix = x.prefix.union(y.exact, false) xy.suffix = x.suffix.union(y.exact.copy(), true) y.addExact() } else { xy.prefix = x.prefix.union(y.prefix, false) xy.suffix = x.suffix.union(y.suffix, true) } xy.canEmpty = x.canEmpty || y.canEmpty xy.match = x.match.or(y.match) xy.simplify(false) return xy }
[ "func", "alternate", "(", "x", ",", "y", "regexpInfo", ")", "(", "out", "regexpInfo", ")", "{", "//println(\"alternate\", x.String(), \"...\", y.String())", "//defer func() { println(\"->\", out.String()) }()", "var", "xy", "regexpInfo", "\n", "if", "x", ".", "exact", ".", "have", "(", ")", "&&", "y", ".", "exact", ".", "have", "(", ")", "{", "xy", ".", "exact", "=", "x", ".", "exact", ".", "union", "(", "y", ".", "exact", ",", "false", ")", "\n", "}", "else", "if", "x", ".", "exact", ".", "have", "(", ")", "{", "xy", ".", "prefix", "=", "x", ".", "exact", ".", "union", "(", "y", ".", "prefix", ",", "false", ")", "\n", "xy", ".", "suffix", "=", "x", ".", "exact", ".", "union", "(", "y", ".", "suffix", ",", "true", ")", "\n", "x", ".", "addExact", "(", ")", "\n", "}", "else", "if", "y", ".", "exact", ".", "have", "(", ")", "{", "xy", ".", "prefix", "=", "x", ".", "prefix", ".", "union", "(", "y", ".", "exact", ",", "false", ")", "\n", "xy", ".", "suffix", "=", "x", ".", "suffix", ".", "union", "(", "y", ".", "exact", ".", "copy", "(", ")", ",", "true", ")", "\n", "y", ".", "addExact", "(", ")", "\n", "}", "else", "{", "xy", ".", "prefix", "=", "x", ".", "prefix", ".", "union", "(", "y", ".", "prefix", ",", "false", ")", "\n", "xy", ".", "suffix", "=", "x", ".", "suffix", ".", "union", "(", "y", ".", "suffix", ",", "true", ")", "\n", "}", "\n", "xy", ".", "canEmpty", "=", "x", ".", "canEmpty", "||", "y", ".", "canEmpty", "\n", "xy", ".", "match", "=", "x", ".", "match", ".", "or", "(", "y", ".", "match", ")", "\n\n", "xy", ".", "simplify", "(", "false", ")", "\n", "return", "xy", "\n", "}" ]
// alternate returns the regexpInfo for x|y given x and y.
[ "alternate", "returns", "the", "regexpInfo", "for", "x|y", "given", "x", "and", "y", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/regexp.go#L600-L623
train
google/codesearch
index/regexp.go
addExact
func (info *regexpInfo) addExact() { if info.exact.have() { info.match = info.match.andTrigrams(info.exact) } }
go
func (info *regexpInfo) addExact() { if info.exact.have() { info.match = info.match.andTrigrams(info.exact) } }
[ "func", "(", "info", "*", "regexpInfo", ")", "addExact", "(", ")", "{", "if", "info", ".", "exact", ".", "have", "(", ")", "{", "info", ".", "match", "=", "info", ".", "match", ".", "andTrigrams", "(", "info", ".", "exact", ")", "\n", "}", "\n", "}" ]
// addExact adds to the match query the trigrams for matching info.exact.
[ "addExact", "adds", "to", "the", "match", "query", "the", "trigrams", "for", "matching", "info", ".", "exact", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/regexp.go#L626-L630
train
google/codesearch
index/regexp.go
simplify
func (info *regexpInfo) simplify(force bool) { //println(" simplify", info.String(), " force=", force) //defer func() { println(" ->", info.String()) }() // If there are now too many exact strings, // loop over them, adding trigrams and moving // the relevant pieces into prefix and suffix. info.exact.clean(false) if len(info.exact) > maxExact || (info.exact.minLen() >= 3 && force) || info.exact.minLen() >= 4 { info.addExact() for _, s := range info.exact { n := len(s) if n < 3 { info.prefix.add(s) info.suffix.add(s) } else { info.prefix.add(s[:2]) info.suffix.add(s[n-2:]) } } info.exact = nil } if !info.exact.have() { info.simplifySet(&info.prefix) info.simplifySet(&info.suffix) } }
go
func (info *regexpInfo) simplify(force bool) { //println(" simplify", info.String(), " force=", force) //defer func() { println(" ->", info.String()) }() // If there are now too many exact strings, // loop over them, adding trigrams and moving // the relevant pieces into prefix and suffix. info.exact.clean(false) if len(info.exact) > maxExact || (info.exact.minLen() >= 3 && force) || info.exact.minLen() >= 4 { info.addExact() for _, s := range info.exact { n := len(s) if n < 3 { info.prefix.add(s) info.suffix.add(s) } else { info.prefix.add(s[:2]) info.suffix.add(s[n-2:]) } } info.exact = nil } if !info.exact.have() { info.simplifySet(&info.prefix) info.simplifySet(&info.suffix) } }
[ "func", "(", "info", "*", "regexpInfo", ")", "simplify", "(", "force", "bool", ")", "{", "//println(\" simplify\", info.String(), \" force=\", force)", "//defer func() { println(\" ->\", info.String()) }()", "// If there are now too many exact strings,", "// loop over them, adding trigrams and moving", "// the relevant pieces into prefix and suffix.", "info", ".", "exact", ".", "clean", "(", "false", ")", "\n", "if", "len", "(", "info", ".", "exact", ")", ">", "maxExact", "||", "(", "info", ".", "exact", ".", "minLen", "(", ")", ">=", "3", "&&", "force", ")", "||", "info", ".", "exact", ".", "minLen", "(", ")", ">=", "4", "{", "info", ".", "addExact", "(", ")", "\n", "for", "_", ",", "s", ":=", "range", "info", ".", "exact", "{", "n", ":=", "len", "(", "s", ")", "\n", "if", "n", "<", "3", "{", "info", ".", "prefix", ".", "add", "(", "s", ")", "\n", "info", ".", "suffix", ".", "add", "(", "s", ")", "\n", "}", "else", "{", "info", ".", "prefix", ".", "add", "(", "s", "[", ":", "2", "]", ")", "\n", "info", ".", "suffix", ".", "add", "(", "s", "[", "n", "-", "2", ":", "]", ")", "\n", "}", "\n", "}", "\n", "info", ".", "exact", "=", "nil", "\n", "}", "\n\n", "if", "!", "info", ".", "exact", ".", "have", "(", ")", "{", "info", ".", "simplifySet", "(", "&", "info", ".", "prefix", ")", "\n", "info", ".", "simplifySet", "(", "&", "info", ".", "suffix", ")", "\n", "}", "\n", "}" ]
// simplify simplifies the regexpInfo when the exact set gets too large.
[ "simplify", "simplifies", "the", "regexpInfo", "when", "the", "exact", "set", "gets", "too", "large", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/regexp.go#L633-L659
train
google/codesearch
index/regexp.go
contains
func (s stringSet) contains(str string) bool { for _, ss := range s { if ss == str { return true } } return false }
go
func (s stringSet) contains(str string) bool { for _, ss := range s { if ss == str { return true } } return false }
[ "func", "(", "s", "stringSet", ")", "contains", "(", "str", "string", ")", "bool", "{", "for", "_", ",", "ss", ":=", "range", "s", "{", "if", "ss", "==", "str", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// contains reports whether s contains str.
[ "contains", "reports", "whether", "s", "contains", "str", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/regexp.go#L739-L746
train
google/codesearch
index/regexp.go
clean
func (s *stringSet) clean(isSuffix bool) { t := *s if isSuffix { sort.Sort((*bySuffix)(s)) } else { sort.Sort((*byPrefix)(s)) } w := 0 for _, str := range t { if w == 0 || t[w-1] != str { t[w] = str w++ } } *s = t[:w] }
go
func (s *stringSet) clean(isSuffix bool) { t := *s if isSuffix { sort.Sort((*bySuffix)(s)) } else { sort.Sort((*byPrefix)(s)) } w := 0 for _, str := range t { if w == 0 || t[w-1] != str { t[w] = str w++ } } *s = t[:w] }
[ "func", "(", "s", "*", "stringSet", ")", "clean", "(", "isSuffix", "bool", ")", "{", "t", ":=", "*", "s", "\n", "if", "isSuffix", "{", "sort", ".", "Sort", "(", "(", "*", "bySuffix", ")", "(", "s", ")", ")", "\n", "}", "else", "{", "sort", ".", "Sort", "(", "(", "*", "byPrefix", ")", "(", "s", ")", ")", "\n", "}", "\n", "w", ":=", "0", "\n", "for", "_", ",", "str", ":=", "range", "t", "{", "if", "w", "==", "0", "||", "t", "[", "w", "-", "1", "]", "!=", "str", "{", "t", "[", "w", "]", "=", "str", "\n", "w", "++", "\n", "}", "\n", "}", "\n", "*", "s", "=", "t", "[", ":", "w", "]", "\n", "}" ]
// clean removes duplicates from the stringSet.
[ "clean", "removes", "duplicates", "from", "the", "stringSet", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/regexp.go#L780-L795
train
google/codesearch
index/regexp.go
minLen
func (s stringSet) minLen() int { if len(s) == 0 { return 0 } m := len(s[0]) for _, str := range s { if m > len(str) { m = len(str) } } return m }
go
func (s stringSet) minLen() int { if len(s) == 0 { return 0 } m := len(s[0]) for _, str := range s { if m > len(str) { m = len(str) } } return m }
[ "func", "(", "s", "stringSet", ")", "minLen", "(", ")", "int", "{", "if", "len", "(", "s", ")", "==", "0", "{", "return", "0", "\n", "}", "\n", "m", ":=", "len", "(", "s", "[", "0", "]", ")", "\n", "for", "_", ",", "str", ":=", "range", "s", "{", "if", "m", ">", "len", "(", "str", ")", "{", "m", "=", "len", "(", "str", ")", "\n", "}", "\n", "}", "\n", "return", "m", "\n", "}" ]
// minLen returns the length of the shortest string in s.
[ "minLen", "returns", "the", "length", "of", "the", "shortest", "string", "in", "s", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/regexp.go#L803-L814
train
google/codesearch
index/regexp.go
maxLen
func (s stringSet) maxLen() int { if len(s) == 0 { return 0 } m := len(s[0]) for _, str := range s { if m < len(str) { m = len(str) } } return m }
go
func (s stringSet) maxLen() int { if len(s) == 0 { return 0 } m := len(s[0]) for _, str := range s { if m < len(str) { m = len(str) } } return m }
[ "func", "(", "s", "stringSet", ")", "maxLen", "(", ")", "int", "{", "if", "len", "(", "s", ")", "==", "0", "{", "return", "0", "\n", "}", "\n", "m", ":=", "len", "(", "s", "[", "0", "]", ")", "\n", "for", "_", ",", "str", ":=", "range", "s", "{", "if", "m", "<", "len", "(", "str", ")", "{", "m", "=", "len", "(", "str", ")", "\n", "}", "\n", "}", "\n", "return", "m", "\n", "}" ]
// maxLen returns the length of the longest string in s.
[ "maxLen", "returns", "the", "length", "of", "the", "longest", "string", "in", "s", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/regexp.go#L817-L828
train
google/codesearch
index/regexp.go
union
func (s stringSet) union(t stringSet, isSuffix bool) stringSet { s = append(s, t...) s.clean(isSuffix) return s }
go
func (s stringSet) union(t stringSet, isSuffix bool) stringSet { s = append(s, t...) s.clean(isSuffix) return s }
[ "func", "(", "s", "stringSet", ")", "union", "(", "t", "stringSet", ",", "isSuffix", "bool", ")", "stringSet", "{", "s", "=", "append", "(", "s", ",", "t", "...", ")", "\n", "s", ".", "clean", "(", "isSuffix", ")", "\n", "return", "s", "\n", "}" ]
// union returns the union of s and t, reusing s's storage.
[ "union", "returns", "the", "union", "of", "s", "and", "t", "reusing", "s", "s", "storage", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/regexp.go#L831-L835
train
google/codesearch
index/regexp.go
cross
func (s stringSet) cross(t stringSet, isSuffix bool) stringSet { p := stringSet{} for _, ss := range s { for _, tt := range t { p.add(ss + tt) } } p.clean(isSuffix) return p }
go
func (s stringSet) cross(t stringSet, isSuffix bool) stringSet { p := stringSet{} for _, ss := range s { for _, tt := range t { p.add(ss + tt) } } p.clean(isSuffix) return p }
[ "func", "(", "s", "stringSet", ")", "cross", "(", "t", "stringSet", ",", "isSuffix", "bool", ")", "stringSet", "{", "p", ":=", "stringSet", "{", "}", "\n", "for", "_", ",", "ss", ":=", "range", "s", "{", "for", "_", ",", "tt", ":=", "range", "t", "{", "p", ".", "add", "(", "ss", "+", "tt", ")", "\n", "}", "\n", "}", "\n", "p", ".", "clean", "(", "isSuffix", ")", "\n", "return", "p", "\n", "}" ]
// cross returns the cross product of s and t.
[ "cross", "returns", "the", "cross", "product", "of", "s", "and", "t", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/regexp.go#L838-L847
train
google/codesearch
index/regexp.go
isSubsetOf
func (s stringSet) isSubsetOf(t stringSet) bool { j := 0 for _, ss := range s { for j < len(t) && t[j] < ss { j++ } if j >= len(t) || t[j] != ss { return false } } return true }
go
func (s stringSet) isSubsetOf(t stringSet) bool { j := 0 for _, ss := range s { for j < len(t) && t[j] < ss { j++ } if j >= len(t) || t[j] != ss { return false } } return true }
[ "func", "(", "s", "stringSet", ")", "isSubsetOf", "(", "t", "stringSet", ")", "bool", "{", "j", ":=", "0", "\n", "for", "_", ",", "ss", ":=", "range", "s", "{", "for", "j", "<", "len", "(", "t", ")", "&&", "t", "[", "j", "]", "<", "ss", "{", "j", "++", "\n", "}", "\n", "if", "j", ">=", "len", "(", "t", ")", "||", "t", "[", "j", "]", "!=", "ss", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// isSubsetOf returns true if all strings in s are also in t. // It assumes both sets are sorted.
[ "isSubsetOf", "returns", "true", "if", "all", "strings", "in", "s", "are", "also", "in", "t", ".", "It", "assumes", "both", "sets", "are", "sorted", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/regexp.go#L861-L872
train
google/codesearch
regexp/copy.go
appendRange
func appendRange(r []rune, lo, hi rune) []rune { // Expand last range or next to last range if it overlaps or abuts. // Checking two ranges helps when appending case-folded // alphabets, so that one range can be expanding A-Z and the // other expanding a-z. n := len(r) for i := 2; i <= 4; i += 2 { // twice, using i=2, i=4 if n >= i { rlo, rhi := r[n-i], r[n-i+1] if lo <= rhi+1 && rlo <= hi+1 { if lo < rlo { r[n-i] = lo } if hi > rhi { r[n-i+1] = hi } return r } } } return append(r, lo, hi) }
go
func appendRange(r []rune, lo, hi rune) []rune { // Expand last range or next to last range if it overlaps or abuts. // Checking two ranges helps when appending case-folded // alphabets, so that one range can be expanding A-Z and the // other expanding a-z. n := len(r) for i := 2; i <= 4; i += 2 { // twice, using i=2, i=4 if n >= i { rlo, rhi := r[n-i], r[n-i+1] if lo <= rhi+1 && rlo <= hi+1 { if lo < rlo { r[n-i] = lo } if hi > rhi { r[n-i+1] = hi } return r } } } return append(r, lo, hi) }
[ "func", "appendRange", "(", "r", "[", "]", "rune", ",", "lo", ",", "hi", "rune", ")", "[", "]", "rune", "{", "// Expand last range or next to last range if it overlaps or abuts.", "// Checking two ranges helps when appending case-folded", "// alphabets, so that one range can be expanding A-Z and the", "// other expanding a-z.", "n", ":=", "len", "(", "r", ")", "\n", "for", "i", ":=", "2", ";", "i", "<=", "4", ";", "i", "+=", "2", "{", "// twice, using i=2, i=4", "if", "n", ">=", "i", "{", "rlo", ",", "rhi", ":=", "r", "[", "n", "-", "i", "]", ",", "r", "[", "n", "-", "i", "+", "1", "]", "\n", "if", "lo", "<=", "rhi", "+", "1", "&&", "rlo", "<=", "hi", "+", "1", "{", "if", "lo", "<", "rlo", "{", "r", "[", "n", "-", "i", "]", "=", "lo", "\n", "}", "\n", "if", "hi", ">", "rhi", "{", "r", "[", "n", "-", "i", "+", "1", "]", "=", "hi", "\n", "}", "\n", "return", "r", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "append", "(", "r", ",", "lo", ",", "hi", ")", "\n", "}" ]
// appendRange returns the result of appending the range lo-hi to the class r.
[ "appendRange", "returns", "the", "result", "of", "appending", "the", "range", "lo", "-", "hi", "to", "the", "class", "r", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/regexp/copy.go#L52-L74
train
google/codesearch
regexp/copy.go
appendFoldedRange
func appendFoldedRange(r []rune, lo, hi rune) []rune { // Optimizations. if lo <= minFold && hi >= maxFold { // Range is full: folding can't add more. return appendRange(r, lo, hi) } if hi < minFold || lo > maxFold { // Range is outside folding possibilities. return appendRange(r, lo, hi) } if lo < minFold { // [lo, minFold-1] needs no folding. r = appendRange(r, lo, minFold-1) lo = minFold } if hi > maxFold { // [maxFold+1, hi] needs no folding. r = appendRange(r, maxFold+1, hi) hi = maxFold } // Brute force. Depend on appendRange to coalesce ranges on the fly. for c := lo; c <= hi; c++ { r = appendRange(r, c, c) f := unicode.SimpleFold(c) for f != c { r = appendRange(r, f, f) f = unicode.SimpleFold(f) } } return r }
go
func appendFoldedRange(r []rune, lo, hi rune) []rune { // Optimizations. if lo <= minFold && hi >= maxFold { // Range is full: folding can't add more. return appendRange(r, lo, hi) } if hi < minFold || lo > maxFold { // Range is outside folding possibilities. return appendRange(r, lo, hi) } if lo < minFold { // [lo, minFold-1] needs no folding. r = appendRange(r, lo, minFold-1) lo = minFold } if hi > maxFold { // [maxFold+1, hi] needs no folding. r = appendRange(r, maxFold+1, hi) hi = maxFold } // Brute force. Depend on appendRange to coalesce ranges on the fly. for c := lo; c <= hi; c++ { r = appendRange(r, c, c) f := unicode.SimpleFold(c) for f != c { r = appendRange(r, f, f) f = unicode.SimpleFold(f) } } return r }
[ "func", "appendFoldedRange", "(", "r", "[", "]", "rune", ",", "lo", ",", "hi", "rune", ")", "[", "]", "rune", "{", "// Optimizations.", "if", "lo", "<=", "minFold", "&&", "hi", ">=", "maxFold", "{", "// Range is full: folding can't add more.", "return", "appendRange", "(", "r", ",", "lo", ",", "hi", ")", "\n", "}", "\n", "if", "hi", "<", "minFold", "||", "lo", ">", "maxFold", "{", "// Range is outside folding possibilities.", "return", "appendRange", "(", "r", ",", "lo", ",", "hi", ")", "\n", "}", "\n", "if", "lo", "<", "minFold", "{", "// [lo, minFold-1] needs no folding.", "r", "=", "appendRange", "(", "r", ",", "lo", ",", "minFold", "-", "1", ")", "\n", "lo", "=", "minFold", "\n", "}", "\n", "if", "hi", ">", "maxFold", "{", "// [maxFold+1, hi] needs no folding.", "r", "=", "appendRange", "(", "r", ",", "maxFold", "+", "1", ",", "hi", ")", "\n", "hi", "=", "maxFold", "\n", "}", "\n\n", "// Brute force. Depend on appendRange to coalesce ranges on the fly.", "for", "c", ":=", "lo", ";", "c", "<=", "hi", ";", "c", "++", "{", "r", "=", "appendRange", "(", "r", ",", "c", ",", "c", ")", "\n", "f", ":=", "unicode", ".", "SimpleFold", "(", "c", ")", "\n", "for", "f", "!=", "c", "{", "r", "=", "appendRange", "(", "r", ",", "f", ",", "f", ")", "\n", "f", "=", "unicode", ".", "SimpleFold", "(", "f", ")", "\n", "}", "\n", "}", "\n", "return", "r", "\n", "}" ]
// appendFoldedRange returns the result of appending the range lo-hi // and its case folding-equivalent runes to the class r.
[ "appendFoldedRange", "returns", "the", "result", "of", "appending", "the", "range", "lo", "-", "hi", "and", "its", "case", "folding", "-", "equivalent", "runes", "to", "the", "class", "r", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/regexp/copy.go#L85-L116
train
google/codesearch
regexp/regexp.go
Compile
func Compile(expr string) (*Regexp, error) { re, err := syntax.Parse(expr, syntax.Perl) if err != nil { return nil, err } sre := re.Simplify() prog, err := syntax.Compile(sre) if err != nil { return nil, err } if err := toByteProg(prog); err != nil { return nil, err } r := &Regexp{ Syntax: re, expr: expr, } if err := r.m.init(prog); err != nil { return nil, err } return r, nil }
go
func Compile(expr string) (*Regexp, error) { re, err := syntax.Parse(expr, syntax.Perl) if err != nil { return nil, err } sre := re.Simplify() prog, err := syntax.Compile(sre) if err != nil { return nil, err } if err := toByteProg(prog); err != nil { return nil, err } r := &Regexp{ Syntax: re, expr: expr, } if err := r.m.init(prog); err != nil { return nil, err } return r, nil }
[ "func", "Compile", "(", "expr", "string", ")", "(", "*", "Regexp", ",", "error", ")", "{", "re", ",", "err", ":=", "syntax", ".", "Parse", "(", "expr", ",", "syntax", ".", "Perl", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "sre", ":=", "re", ".", "Simplify", "(", ")", "\n", "prog", ",", "err", ":=", "syntax", ".", "Compile", "(", "sre", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "toByteProg", "(", "prog", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "r", ":=", "&", "Regexp", "{", "Syntax", ":", "re", ",", "expr", ":", "expr", ",", "}", "\n", "if", "err", ":=", "r", ".", "m", ".", "init", "(", "prog", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "r", ",", "nil", "\n", "}" ]
// Compile parses a regular expression and returns, if successful, // a Regexp object that can be used to match against lines of text.
[ "Compile", "parses", "a", "regular", "expression", "and", "returns", "if", "successful", "a", "Regexp", "object", "that", "can", "be", "used", "to", "match", "against", "lines", "of", "text", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/regexp/regexp.go#L30-L51
train
google/codesearch
sparse/set.go
Add
func (s *Set) Add(x uint32) { v := s.sparse[x] if v < uint32(len(s.dense)) && s.dense[v] == x { return } n := len(s.dense) s.sparse[x] = uint32(n) s.dense = append(s.dense, x) }
go
func (s *Set) Add(x uint32) { v := s.sparse[x] if v < uint32(len(s.dense)) && s.dense[v] == x { return } n := len(s.dense) s.sparse[x] = uint32(n) s.dense = append(s.dense, x) }
[ "func", "(", "s", "*", "Set", ")", "Add", "(", "x", "uint32", ")", "{", "v", ":=", "s", ".", "sparse", "[", "x", "]", "\n", "if", "v", "<", "uint32", "(", "len", "(", "s", ".", "dense", ")", ")", "&&", "s", ".", "dense", "[", "v", "]", "==", "x", "{", "return", "\n", "}", "\n", "n", ":=", "len", "(", "s", ".", "dense", ")", "\n", "s", ".", "sparse", "[", "x", "]", "=", "uint32", "(", "n", ")", "\n", "s", ".", "dense", "=", "append", "(", "s", ".", "dense", ",", "x", ")", "\n", "}" ]
// Add adds x to the set if it is not already there.
[ "Add", "adds", "x", "to", "the", "set", "if", "it", "is", "not", "already", "there", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/sparse/set.go#L39-L47
train
google/codesearch
sparse/set.go
Has
func (s *Set) Has(x uint32) bool { v := s.sparse[x] return v < uint32(len(s.dense)) && s.dense[v] == x }
go
func (s *Set) Has(x uint32) bool { v := s.sparse[x] return v < uint32(len(s.dense)) && s.dense[v] == x }
[ "func", "(", "s", "*", "Set", ")", "Has", "(", "x", "uint32", ")", "bool", "{", "v", ":=", "s", ".", "sparse", "[", "x", "]", "\n", "return", "v", "<", "uint32", "(", "len", "(", "s", ".", "dense", ")", ")", "&&", "s", ".", "dense", "[", "v", "]", "==", "x", "\n", "}" ]
// Has reports whether x is in the set.
[ "Has", "reports", "whether", "x", "is", "in", "the", "set", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/sparse/set.go#L50-L53
train
google/codesearch
regexp/match.go
stepEmpty
func (m *matcher) stepEmpty(runq, nextq *sparse.Set, flag syntax.EmptyOp) { nextq.Reset() for _, id := range runq.Dense() { m.addq(nextq, id, flag) } }
go
func (m *matcher) stepEmpty(runq, nextq *sparse.Set, flag syntax.EmptyOp) { nextq.Reset() for _, id := range runq.Dense() { m.addq(nextq, id, flag) } }
[ "func", "(", "m", "*", "matcher", ")", "stepEmpty", "(", "runq", ",", "nextq", "*", "sparse", ".", "Set", ",", "flag", "syntax", ".", "EmptyOp", ")", "{", "nextq", ".", "Reset", "(", ")", "\n", "for", "_", ",", "id", ":=", "range", "runq", ".", "Dense", "(", ")", "{", "m", ".", "addq", "(", "nextq", ",", "id", ",", "flag", ")", "\n", "}", "\n", "}" ]
// stepEmpty steps runq to nextq expanding according to flag.
[ "stepEmpty", "steps", "runq", "to", "nextq", "expanding", "according", "to", "flag", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/regexp/match.go#L148-L153
train
google/codesearch
regexp/match.go
stepByte
func (m *matcher) stepByte(runq, nextq *sparse.Set, c int, flag syntax.EmptyOp) (match bool) { nextq.Reset() m.addq(nextq, uint32(m.prog.Start), flag) for _, id := range runq.Dense() { i := &m.prog.Inst[id] switch i.Op { default: continue case syntax.InstMatch: match = true continue case instByteRange: if c == endText { break } lo := int((i.Arg >> 8) & 0xFF) hi := int(i.Arg & 0xFF) ch := c if i.Arg&argFold != 0 && 'a' <= ch && ch <= 'z' { ch += 'A' - 'a' } if lo <= ch && ch <= hi { m.addq(nextq, i.Out, flag) } } } return }
go
func (m *matcher) stepByte(runq, nextq *sparse.Set, c int, flag syntax.EmptyOp) (match bool) { nextq.Reset() m.addq(nextq, uint32(m.prog.Start), flag) for _, id := range runq.Dense() { i := &m.prog.Inst[id] switch i.Op { default: continue case syntax.InstMatch: match = true continue case instByteRange: if c == endText { break } lo := int((i.Arg >> 8) & 0xFF) hi := int(i.Arg & 0xFF) ch := c if i.Arg&argFold != 0 && 'a' <= ch && ch <= 'z' { ch += 'A' - 'a' } if lo <= ch && ch <= hi { m.addq(nextq, i.Out, flag) } } } return }
[ "func", "(", "m", "*", "matcher", ")", "stepByte", "(", "runq", ",", "nextq", "*", "sparse", ".", "Set", ",", "c", "int", ",", "flag", "syntax", ".", "EmptyOp", ")", "(", "match", "bool", ")", "{", "nextq", ".", "Reset", "(", ")", "\n", "m", ".", "addq", "(", "nextq", ",", "uint32", "(", "m", ".", "prog", ".", "Start", ")", ",", "flag", ")", "\n", "for", "_", ",", "id", ":=", "range", "runq", ".", "Dense", "(", ")", "{", "i", ":=", "&", "m", ".", "prog", ".", "Inst", "[", "id", "]", "\n", "switch", "i", ".", "Op", "{", "default", ":", "continue", "\n", "case", "syntax", ".", "InstMatch", ":", "match", "=", "true", "\n", "continue", "\n", "case", "instByteRange", ":", "if", "c", "==", "endText", "{", "break", "\n", "}", "\n", "lo", ":=", "int", "(", "(", "i", ".", "Arg", ">>", "8", ")", "&", "0xFF", ")", "\n", "hi", ":=", "int", "(", "i", ".", "Arg", "&", "0xFF", ")", "\n", "ch", ":=", "c", "\n", "if", "i", ".", "Arg", "&", "argFold", "!=", "0", "&&", "'a'", "<=", "ch", "&&", "ch", "<=", "'z'", "{", "ch", "+=", "'A'", "-", "'a'", "\n", "}", "\n", "if", "lo", "<=", "ch", "&&", "ch", "<=", "hi", "{", "m", ".", "addq", "(", "nextq", ",", "i", ".", "Out", ",", "flag", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// stepByte steps runq to nextq consuming c and then expanding according to flag. // It returns true if a match ends immediately before c. // c is either an input byte or endText.
[ "stepByte", "steps", "runq", "to", "nextq", "consuming", "c", "and", "then", "expanding", "according", "to", "flag", ".", "It", "returns", "true", "if", "a", "match", "ends", "immediately", "before", "c", ".", "c", "is", "either", "an", "input", "byte", "or", "endText", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/regexp/match.go#L158-L185
train
google/codesearch
regexp/match.go
addq
func (m *matcher) addq(q *sparse.Set, id uint32, flag syntax.EmptyOp) { if q.Has(id) { return } q.Add(id) i := &m.prog.Inst[id] switch i.Op { case syntax.InstCapture, syntax.InstNop: m.addq(q, i.Out, flag) case syntax.InstAlt, syntax.InstAltMatch: m.addq(q, i.Out, flag) m.addq(q, i.Arg, flag) case syntax.InstEmptyWidth: if syntax.EmptyOp(i.Arg)&^flag == 0 { m.addq(q, i.Out, flag) } } }
go
func (m *matcher) addq(q *sparse.Set, id uint32, flag syntax.EmptyOp) { if q.Has(id) { return } q.Add(id) i := &m.prog.Inst[id] switch i.Op { case syntax.InstCapture, syntax.InstNop: m.addq(q, i.Out, flag) case syntax.InstAlt, syntax.InstAltMatch: m.addq(q, i.Out, flag) m.addq(q, i.Arg, flag) case syntax.InstEmptyWidth: if syntax.EmptyOp(i.Arg)&^flag == 0 { m.addq(q, i.Out, flag) } } }
[ "func", "(", "m", "*", "matcher", ")", "addq", "(", "q", "*", "sparse", ".", "Set", ",", "id", "uint32", ",", "flag", "syntax", ".", "EmptyOp", ")", "{", "if", "q", ".", "Has", "(", "id", ")", "{", "return", "\n", "}", "\n", "q", ".", "Add", "(", "id", ")", "\n", "i", ":=", "&", "m", ".", "prog", ".", "Inst", "[", "id", "]", "\n", "switch", "i", ".", "Op", "{", "case", "syntax", ".", "InstCapture", ",", "syntax", ".", "InstNop", ":", "m", ".", "addq", "(", "q", ",", "i", ".", "Out", ",", "flag", ")", "\n", "case", "syntax", ".", "InstAlt", ",", "syntax", ".", "InstAltMatch", ":", "m", ".", "addq", "(", "q", ",", "i", ".", "Out", ",", "flag", ")", "\n", "m", ".", "addq", "(", "q", ",", "i", ".", "Arg", ",", "flag", ")", "\n", "case", "syntax", ".", "InstEmptyWidth", ":", "if", "syntax", ".", "EmptyOp", "(", "i", ".", "Arg", ")", "&^", "flag", "==", "0", "{", "m", ".", "addq", "(", "q", ",", "i", ".", "Out", ",", "flag", ")", "\n", "}", "\n", "}", "\n", "}" ]
// addq adds id to the queue, expanding according to flag.
[ "addq", "adds", "id", "to", "the", "queue", "expanding", "according", "to", "flag", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/regexp/match.go#L188-L205
train
google/codesearch
index/read.go
slice
func (ix *Index) slice(off uint32, n int) []byte { o := int(off) if uint32(o) != off || n >= 0 && o+n > len(ix.data.d) { corrupt() } if n < 0 { return ix.data.d[o:] } return ix.data.d[o : o+n] }
go
func (ix *Index) slice(off uint32, n int) []byte { o := int(off) if uint32(o) != off || n >= 0 && o+n > len(ix.data.d) { corrupt() } if n < 0 { return ix.data.d[o:] } return ix.data.d[o : o+n] }
[ "func", "(", "ix", "*", "Index", ")", "slice", "(", "off", "uint32", ",", "n", "int", ")", "[", "]", "byte", "{", "o", ":=", "int", "(", "off", ")", "\n", "if", "uint32", "(", "o", ")", "!=", "off", "||", "n", ">=", "0", "&&", "o", "+", "n", ">", "len", "(", "ix", ".", "data", ".", "d", ")", "{", "corrupt", "(", ")", "\n", "}", "\n", "if", "n", "<", "0", "{", "return", "ix", ".", "data", ".", "d", "[", "o", ":", "]", "\n", "}", "\n", "return", "ix", ".", "data", ".", "d", "[", "o", ":", "o", "+", "n", "]", "\n", "}" ]
// slice returns the slice of index data starting at the given byte offset. // If n >= 0, the slice must have length at least n and is truncated to length n.
[ "slice", "returns", "the", "slice", "of", "index", "data", "starting", "at", "the", "given", "byte", "offset", ".", "If", "n", ">", "=", "0", "the", "slice", "must", "have", "length", "at", "least", "n", "and", "is", "truncated", "to", "length", "n", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/read.go#L116-L125
train
google/codesearch
index/read.go
uint32
func (ix *Index) uint32(off uint32) uint32 { return binary.BigEndian.Uint32(ix.slice(off, 4)) }
go
func (ix *Index) uint32(off uint32) uint32 { return binary.BigEndian.Uint32(ix.slice(off, 4)) }
[ "func", "(", "ix", "*", "Index", ")", "uint32", "(", "off", "uint32", ")", "uint32", "{", "return", "binary", ".", "BigEndian", ".", "Uint32", "(", "ix", ".", "slice", "(", "off", ",", "4", ")", ")", "\n", "}" ]
// uint32 returns the uint32 value at the given offset in the index data.
[ "uint32", "returns", "the", "uint32", "value", "at", "the", "given", "offset", "in", "the", "index", "data", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/read.go#L128-L130
train
google/codesearch
index/read.go
uvarint
func (ix *Index) uvarint(off uint32) uint32 { v, n := binary.Uvarint(ix.slice(off, -1)) if n <= 0 { corrupt() } return uint32(v) }
go
func (ix *Index) uvarint(off uint32) uint32 { v, n := binary.Uvarint(ix.slice(off, -1)) if n <= 0 { corrupt() } return uint32(v) }
[ "func", "(", "ix", "*", "Index", ")", "uvarint", "(", "off", "uint32", ")", "uint32", "{", "v", ",", "n", ":=", "binary", ".", "Uvarint", "(", "ix", ".", "slice", "(", "off", ",", "-", "1", ")", ")", "\n", "if", "n", "<=", "0", "{", "corrupt", "(", ")", "\n", "}", "\n", "return", "uint32", "(", "v", ")", "\n", "}" ]
// uvarint returns the varint value at the given offset in the index data.
[ "uvarint", "returns", "the", "varint", "value", "at", "the", "given", "offset", "in", "the", "index", "data", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/read.go#L133-L139
train
google/codesearch
index/read.go
Paths
func (ix *Index) Paths() []string { off := ix.pathData var x []string for { s := ix.str(off) if len(s) == 0 { break } x = append(x, string(s)) off += uint32(len(s) + 1) } return x }
go
func (ix *Index) Paths() []string { off := ix.pathData var x []string for { s := ix.str(off) if len(s) == 0 { break } x = append(x, string(s)) off += uint32(len(s) + 1) } return x }
[ "func", "(", "ix", "*", "Index", ")", "Paths", "(", ")", "[", "]", "string", "{", "off", ":=", "ix", ".", "pathData", "\n", "var", "x", "[", "]", "string", "\n", "for", "{", "s", ":=", "ix", ".", "str", "(", "off", ")", "\n", "if", "len", "(", "s", ")", "==", "0", "{", "break", "\n", "}", "\n", "x", "=", "append", "(", "x", ",", "string", "(", "s", ")", ")", "\n", "off", "+=", "uint32", "(", "len", "(", "s", ")", "+", "1", ")", "\n", "}", "\n", "return", "x", "\n", "}" ]
// Paths returns the list of indexed paths.
[ "Paths", "returns", "the", "list", "of", "indexed", "paths", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/read.go#L142-L154
train
google/codesearch
index/read.go
NameBytes
func (ix *Index) NameBytes(fileid uint32) []byte { off := ix.uint32(ix.nameIndex + 4*fileid) return ix.str(ix.nameData + off) }
go
func (ix *Index) NameBytes(fileid uint32) []byte { off := ix.uint32(ix.nameIndex + 4*fileid) return ix.str(ix.nameData + off) }
[ "func", "(", "ix", "*", "Index", ")", "NameBytes", "(", "fileid", "uint32", ")", "[", "]", "byte", "{", "off", ":=", "ix", ".", "uint32", "(", "ix", ".", "nameIndex", "+", "4", "*", "fileid", ")", "\n", "return", "ix", ".", "str", "(", "ix", ".", "nameData", "+", "off", ")", "\n", "}" ]
// NameBytes returns the name corresponding to the given fileid.
[ "NameBytes", "returns", "the", "name", "corresponding", "to", "the", "given", "fileid", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/read.go#L157-L160
train
google/codesearch
index/read.go
Name
func (ix *Index) Name(fileid uint32) string { return string(ix.NameBytes(fileid)) }
go
func (ix *Index) Name(fileid uint32) string { return string(ix.NameBytes(fileid)) }
[ "func", "(", "ix", "*", "Index", ")", "Name", "(", "fileid", "uint32", ")", "string", "{", "return", "string", "(", "ix", ".", "NameBytes", "(", "fileid", ")", ")", "\n", "}" ]
// Name returns the name corresponding to the given fileid.
[ "Name", "returns", "the", "name", "corresponding", "to", "the", "given", "fileid", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/read.go#L172-L174
train
google/codesearch
index/read.go
listAt
func (ix *Index) listAt(off uint32) (trigram, count, offset uint32) { d := ix.slice(ix.postIndex+off, postEntrySize) trigram = uint32(d[0])<<16 | uint32(d[1])<<8 | uint32(d[2]) count = binary.BigEndian.Uint32(d[3:]) offset = binary.BigEndian.Uint32(d[3+4:]) return }
go
func (ix *Index) listAt(off uint32) (trigram, count, offset uint32) { d := ix.slice(ix.postIndex+off, postEntrySize) trigram = uint32(d[0])<<16 | uint32(d[1])<<8 | uint32(d[2]) count = binary.BigEndian.Uint32(d[3:]) offset = binary.BigEndian.Uint32(d[3+4:]) return }
[ "func", "(", "ix", "*", "Index", ")", "listAt", "(", "off", "uint32", ")", "(", "trigram", ",", "count", ",", "offset", "uint32", ")", "{", "d", ":=", "ix", ".", "slice", "(", "ix", ".", "postIndex", "+", "off", ",", "postEntrySize", ")", "\n", "trigram", "=", "uint32", "(", "d", "[", "0", "]", ")", "<<", "16", "|", "uint32", "(", "d", "[", "1", "]", ")", "<<", "8", "|", "uint32", "(", "d", "[", "2", "]", ")", "\n", "count", "=", "binary", ".", "BigEndian", ".", "Uint32", "(", "d", "[", "3", ":", "]", ")", "\n", "offset", "=", "binary", ".", "BigEndian", ".", "Uint32", "(", "d", "[", "3", "+", "4", ":", "]", ")", "\n", "return", "\n", "}" ]
// listAt returns the index list entry at the given offset.
[ "listAt", "returns", "the", "index", "list", "entry", "at", "the", "given", "offset", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/read.go#L177-L183
train
google/codesearch
index/read.go
mmap
func mmap(file string) mmapData { f, err := os.Open(file) if err != nil { log.Fatal(err) } return mmapFile(f) }
go
func mmap(file string) mmapData { f, err := os.Open(file) if err != nil { log.Fatal(err) } return mmapFile(f) }
[ "func", "mmap", "(", "file", "string", ")", "mmapData", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "file", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatal", "(", "err", ")", "\n", "}", "\n", "return", "mmapFile", "(", "f", ")", "\n", "}" ]
// mmap maps the given file into memory.
[ "mmap", "maps", "the", "given", "file", "into", "memory", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/read.go#L421-L427
train
google/codesearch
index/write.go
Create
func Create(file string) *IndexWriter { return &IndexWriter{ trigram: sparse.NewSet(1 << 24), nameData: bufCreate(""), nameIndex: bufCreate(""), postIndex: bufCreate(""), main: bufCreate(file), post: make([]postEntry, 0, npost), inbuf: make([]byte, 16384), } }
go
func Create(file string) *IndexWriter { return &IndexWriter{ trigram: sparse.NewSet(1 << 24), nameData: bufCreate(""), nameIndex: bufCreate(""), postIndex: bufCreate(""), main: bufCreate(file), post: make([]postEntry, 0, npost), inbuf: make([]byte, 16384), } }
[ "func", "Create", "(", "file", "string", ")", "*", "IndexWriter", "{", "return", "&", "IndexWriter", "{", "trigram", ":", "sparse", ".", "NewSet", "(", "1", "<<", "24", ")", ",", "nameData", ":", "bufCreate", "(", "\"", "\"", ")", ",", "nameIndex", ":", "bufCreate", "(", "\"", "\"", ")", ",", "postIndex", ":", "bufCreate", "(", "\"", "\"", ")", ",", "main", ":", "bufCreate", "(", "file", ")", ",", "post", ":", "make", "(", "[", "]", "postEntry", ",", "0", ",", "npost", ")", ",", "inbuf", ":", "make", "(", "[", "]", "byte", ",", "16384", ")", ",", "}", "\n", "}" ]
// Create returns a new IndexWriter that will write the index to file.
[ "Create", "returns", "a", "new", "IndexWriter", "that", "will", "write", "the", "index", "to", "file", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/write.go#L61-L71
train
google/codesearch
index/write.go
AddPaths
func (ix *IndexWriter) AddPaths(paths []string) { ix.paths = append(ix.paths, paths...) }
go
func (ix *IndexWriter) AddPaths(paths []string) { ix.paths = append(ix.paths, paths...) }
[ "func", "(", "ix", "*", "IndexWriter", ")", "AddPaths", "(", "paths", "[", "]", "string", ")", "{", "ix", ".", "paths", "=", "append", "(", "ix", ".", "paths", ",", "paths", "...", ")", "\n", "}" ]
// AddPaths adds the given paths to the index's list of paths.
[ "AddPaths", "adds", "the", "given", "paths", "to", "the", "index", "s", "list", "of", "paths", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/write.go#L100-L102
train
google/codesearch
index/write.go
Add
func (ix *IndexWriter) Add(name string, f io.Reader) { ix.trigram.Reset() var ( c = byte(0) i = 0 buf = ix.inbuf[:0] tv = uint32(0) n = int64(0) linelen = 0 ) for { tv = (tv << 8) & (1<<24 - 1) if i >= len(buf) { n, err := f.Read(buf[:cap(buf)]) if n == 0 { if err != nil { if err == io.EOF { break } log.Printf("%s: %v\n", name, err) return } log.Printf("%s: 0-length read\n", name) return } buf = buf[:n] i = 0 } c = buf[i] i++ tv |= uint32(c) if n++; n >= 3 { ix.trigram.Add(tv) } if !validUTF8((tv>>8)&0xFF, tv&0xFF) { if ix.LogSkip { log.Printf("%s: invalid UTF-8, ignoring\n", name) } return } if n > maxFileLen { if ix.LogSkip { log.Printf("%s: too long, ignoring\n", name) } return } if linelen++; linelen > maxLineLen { if ix.LogSkip { log.Printf("%s: very long lines, ignoring\n", name) } return } if c == '\n' { linelen = 0 } } if ix.trigram.Len() > maxTextTrigrams { if ix.LogSkip { log.Printf("%s: too many trigrams, probably not text, ignoring\n", name) } return } ix.totalBytes += n if ix.Verbose { log.Printf("%d %d %s\n", n, ix.trigram.Len(), name) } fileid := ix.addName(name) for _, trigram := range ix.trigram.Dense() { if len(ix.post) >= cap(ix.post) { ix.flushPost() } ix.post = append(ix.post, makePostEntry(trigram, fileid)) } }
go
func (ix *IndexWriter) Add(name string, f io.Reader) { ix.trigram.Reset() var ( c = byte(0) i = 0 buf = ix.inbuf[:0] tv = uint32(0) n = int64(0) linelen = 0 ) for { tv = (tv << 8) & (1<<24 - 1) if i >= len(buf) { n, err := f.Read(buf[:cap(buf)]) if n == 0 { if err != nil { if err == io.EOF { break } log.Printf("%s: %v\n", name, err) return } log.Printf("%s: 0-length read\n", name) return } buf = buf[:n] i = 0 } c = buf[i] i++ tv |= uint32(c) if n++; n >= 3 { ix.trigram.Add(tv) } if !validUTF8((tv>>8)&0xFF, tv&0xFF) { if ix.LogSkip { log.Printf("%s: invalid UTF-8, ignoring\n", name) } return } if n > maxFileLen { if ix.LogSkip { log.Printf("%s: too long, ignoring\n", name) } return } if linelen++; linelen > maxLineLen { if ix.LogSkip { log.Printf("%s: very long lines, ignoring\n", name) } return } if c == '\n' { linelen = 0 } } if ix.trigram.Len() > maxTextTrigrams { if ix.LogSkip { log.Printf("%s: too many trigrams, probably not text, ignoring\n", name) } return } ix.totalBytes += n if ix.Verbose { log.Printf("%d %d %s\n", n, ix.trigram.Len(), name) } fileid := ix.addName(name) for _, trigram := range ix.trigram.Dense() { if len(ix.post) >= cap(ix.post) { ix.flushPost() } ix.post = append(ix.post, makePostEntry(trigram, fileid)) } }
[ "func", "(", "ix", "*", "IndexWriter", ")", "Add", "(", "name", "string", ",", "f", "io", ".", "Reader", ")", "{", "ix", ".", "trigram", ".", "Reset", "(", ")", "\n", "var", "(", "c", "=", "byte", "(", "0", ")", "\n", "i", "=", "0", "\n", "buf", "=", "ix", ".", "inbuf", "[", ":", "0", "]", "\n", "tv", "=", "uint32", "(", "0", ")", "\n", "n", "=", "int64", "(", "0", ")", "\n", "linelen", "=", "0", "\n", ")", "\n", "for", "{", "tv", "=", "(", "tv", "<<", "8", ")", "&", "(", "1", "<<", "24", "-", "1", ")", "\n", "if", "i", ">=", "len", "(", "buf", ")", "{", "n", ",", "err", ":=", "f", ".", "Read", "(", "buf", "[", ":", "cap", "(", "buf", ")", "]", ")", "\n", "if", "n", "==", "0", "{", "if", "err", "!=", "nil", "{", "if", "err", "==", "io", ".", "EOF", "{", "break", "\n", "}", "\n", "log", ".", "Printf", "(", "\"", "\\n", "\"", ",", "name", ",", "err", ")", "\n", "return", "\n", "}", "\n", "log", ".", "Printf", "(", "\"", "\\n", "\"", ",", "name", ")", "\n", "return", "\n", "}", "\n", "buf", "=", "buf", "[", ":", "n", "]", "\n", "i", "=", "0", "\n", "}", "\n", "c", "=", "buf", "[", "i", "]", "\n", "i", "++", "\n", "tv", "|=", "uint32", "(", "c", ")", "\n", "if", "n", "++", ";", "n", ">=", "3", "{", "ix", ".", "trigram", ".", "Add", "(", "tv", ")", "\n", "}", "\n", "if", "!", "validUTF8", "(", "(", "tv", ">>", "8", ")", "&", "0xFF", ",", "tv", "&", "0xFF", ")", "{", "if", "ix", ".", "LogSkip", "{", "log", ".", "Printf", "(", "\"", "\\n", "\"", ",", "name", ")", "\n", "}", "\n", "return", "\n", "}", "\n", "if", "n", ">", "maxFileLen", "{", "if", "ix", ".", "LogSkip", "{", "log", ".", "Printf", "(", "\"", "\\n", "\"", ",", "name", ")", "\n", "}", "\n", "return", "\n", "}", "\n", "if", "linelen", "++", ";", "linelen", ">", "maxLineLen", "{", "if", "ix", ".", "LogSkip", "{", "log", ".", "Printf", "(", "\"", "\\n", "\"", ",", "name", ")", "\n", "}", "\n", "return", "\n", "}", "\n", "if", "c", "==", "'\\n'", "{", "linelen", "=", "0", "\n", "}", "\n", "}", "\n", "if", "ix", ".", "trigram", ".", "Len", "(", ")", ">", "maxTextTrigrams", "{", "if", "ix", ".", "LogSkip", "{", "log", ".", "Printf", "(", "\"", "\\n", "\"", ",", "name", ")", "\n", "}", "\n", "return", "\n", "}", "\n", "ix", ".", "totalBytes", "+=", "n", "\n\n", "if", "ix", ".", "Verbose", "{", "log", ".", "Printf", "(", "\"", "\\n", "\"", ",", "n", ",", "ix", ".", "trigram", ".", "Len", "(", ")", ",", "name", ")", "\n", "}", "\n\n", "fileid", ":=", "ix", ".", "addName", "(", "name", ")", "\n", "for", "_", ",", "trigram", ":=", "range", "ix", ".", "trigram", ".", "Dense", "(", ")", "{", "if", "len", "(", "ix", ".", "post", ")", ">=", "cap", "(", "ix", ".", "post", ")", "{", "ix", ".", "flushPost", "(", ")", "\n", "}", "\n", "ix", ".", "post", "=", "append", "(", "ix", ".", "post", ",", "makePostEntry", "(", "trigram", ",", "fileid", ")", ")", "\n", "}", "\n", "}" ]
// Add adds the file f to the index under the given name. // It logs errors using package log.
[ "Add", "adds", "the", "file", "f", "to", "the", "index", "under", "the", "given", "name", ".", "It", "logs", "errors", "using", "package", "log", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/write.go#L118-L193
train
google/codesearch
index/write.go
Flush
func (ix *IndexWriter) Flush() { ix.addName("") var off [5]uint32 ix.main.writeString(magic) off[0] = ix.main.offset() for _, p := range ix.paths { ix.main.writeString(p) ix.main.writeString("\x00") } ix.main.writeString("\x00") off[1] = ix.main.offset() copyFile(ix.main, ix.nameData) off[2] = ix.main.offset() ix.mergePost(ix.main) off[3] = ix.main.offset() copyFile(ix.main, ix.nameIndex) off[4] = ix.main.offset() copyFile(ix.main, ix.postIndex) for _, v := range off { ix.main.writeUint32(v) } ix.main.writeString(trailerMagic) os.Remove(ix.nameData.name) for _, f := range ix.postFile { os.Remove(f.Name()) } os.Remove(ix.nameIndex.name) os.Remove(ix.postIndex.name) log.Printf("%d data bytes, %d index bytes", ix.totalBytes, ix.main.offset()) ix.main.flush() }
go
func (ix *IndexWriter) Flush() { ix.addName("") var off [5]uint32 ix.main.writeString(magic) off[0] = ix.main.offset() for _, p := range ix.paths { ix.main.writeString(p) ix.main.writeString("\x00") } ix.main.writeString("\x00") off[1] = ix.main.offset() copyFile(ix.main, ix.nameData) off[2] = ix.main.offset() ix.mergePost(ix.main) off[3] = ix.main.offset() copyFile(ix.main, ix.nameIndex) off[4] = ix.main.offset() copyFile(ix.main, ix.postIndex) for _, v := range off { ix.main.writeUint32(v) } ix.main.writeString(trailerMagic) os.Remove(ix.nameData.name) for _, f := range ix.postFile { os.Remove(f.Name()) } os.Remove(ix.nameIndex.name) os.Remove(ix.postIndex.name) log.Printf("%d data bytes, %d index bytes", ix.totalBytes, ix.main.offset()) ix.main.flush() }
[ "func", "(", "ix", "*", "IndexWriter", ")", "Flush", "(", ")", "{", "ix", ".", "addName", "(", "\"", "\"", ")", "\n\n", "var", "off", "[", "5", "]", "uint32", "\n", "ix", ".", "main", ".", "writeString", "(", "magic", ")", "\n", "off", "[", "0", "]", "=", "ix", ".", "main", ".", "offset", "(", ")", "\n", "for", "_", ",", "p", ":=", "range", "ix", ".", "paths", "{", "ix", ".", "main", ".", "writeString", "(", "p", ")", "\n", "ix", ".", "main", ".", "writeString", "(", "\"", "\\x00", "\"", ")", "\n", "}", "\n", "ix", ".", "main", ".", "writeString", "(", "\"", "\\x00", "\"", ")", "\n", "off", "[", "1", "]", "=", "ix", ".", "main", ".", "offset", "(", ")", "\n", "copyFile", "(", "ix", ".", "main", ",", "ix", ".", "nameData", ")", "\n", "off", "[", "2", "]", "=", "ix", ".", "main", ".", "offset", "(", ")", "\n", "ix", ".", "mergePost", "(", "ix", ".", "main", ")", "\n", "off", "[", "3", "]", "=", "ix", ".", "main", ".", "offset", "(", ")", "\n", "copyFile", "(", "ix", ".", "main", ",", "ix", ".", "nameIndex", ")", "\n", "off", "[", "4", "]", "=", "ix", ".", "main", ".", "offset", "(", ")", "\n", "copyFile", "(", "ix", ".", "main", ",", "ix", ".", "postIndex", ")", "\n", "for", "_", ",", "v", ":=", "range", "off", "{", "ix", ".", "main", ".", "writeUint32", "(", "v", ")", "\n", "}", "\n", "ix", ".", "main", ".", "writeString", "(", "trailerMagic", ")", "\n\n", "os", ".", "Remove", "(", "ix", ".", "nameData", ".", "name", ")", "\n", "for", "_", ",", "f", ":=", "range", "ix", ".", "postFile", "{", "os", ".", "Remove", "(", "f", ".", "Name", "(", ")", ")", "\n", "}", "\n", "os", ".", "Remove", "(", "ix", ".", "nameIndex", ".", "name", ")", "\n", "os", ".", "Remove", "(", "ix", ".", "postIndex", ".", "name", ")", "\n\n", "log", ".", "Printf", "(", "\"", "\"", ",", "ix", ".", "totalBytes", ",", "ix", ".", "main", ".", "offset", "(", ")", ")", "\n\n", "ix", ".", "main", ".", "flush", "(", ")", "\n", "}" ]
// Flush flushes the index entry to the target file.
[ "Flush", "flushes", "the", "index", "entry", "to", "the", "target", "file", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/write.go#L196-L230
train
google/codesearch
index/write.go
addName
func (ix *IndexWriter) addName(name string) uint32 { if strings.Contains(name, "\x00") { log.Fatalf("%q: file has NUL byte in name", name) } ix.nameIndex.writeUint32(ix.nameData.offset()) ix.nameData.writeString(name) ix.nameData.writeByte(0) id := ix.numName ix.numName++ return uint32(id) }
go
func (ix *IndexWriter) addName(name string) uint32 { if strings.Contains(name, "\x00") { log.Fatalf("%q: file has NUL byte in name", name) } ix.nameIndex.writeUint32(ix.nameData.offset()) ix.nameData.writeString(name) ix.nameData.writeByte(0) id := ix.numName ix.numName++ return uint32(id) }
[ "func", "(", "ix", "*", "IndexWriter", ")", "addName", "(", "name", "string", ")", "uint32", "{", "if", "strings", ".", "Contains", "(", "name", ",", "\"", "\\x00", "\"", ")", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n\n", "ix", ".", "nameIndex", ".", "writeUint32", "(", "ix", ".", "nameData", ".", "offset", "(", ")", ")", "\n", "ix", ".", "nameData", ".", "writeString", "(", "name", ")", "\n", "ix", ".", "nameData", ".", "writeByte", "(", "0", ")", "\n", "id", ":=", "ix", ".", "numName", "\n", "ix", ".", "numName", "++", "\n", "return", "uint32", "(", "id", ")", "\n", "}" ]
// addName adds the file with the given name to the index. // It returns the assigned file ID number.
[ "addName", "adds", "the", "file", "with", "the", "given", "name", "to", "the", "index", ".", "It", "returns", "the", "assigned", "file", "ID", "number", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/write.go#L242-L253
train
google/codesearch
index/write.go
flushPost
func (ix *IndexWriter) flushPost() { w, err := ioutil.TempFile("", "csearch-index") if err != nil { log.Fatal(err) } if ix.Verbose { log.Printf("flush %d entries to %s", len(ix.post), w.Name()) } sortPost(ix.post) // Write the raw ix.post array to disk as is. // This process is the one reading it back in, so byte order is not a concern. data := (*[npost * 8]byte)(unsafe.Pointer(&ix.post[0]))[:len(ix.post)*8] if n, err := w.Write(data); err != nil || n < len(data) { if err != nil { log.Fatal(err) } log.Fatalf("short write writing %s", w.Name()) } ix.post = ix.post[:0] w.Seek(0, 0) ix.postFile = append(ix.postFile, w) }
go
func (ix *IndexWriter) flushPost() { w, err := ioutil.TempFile("", "csearch-index") if err != nil { log.Fatal(err) } if ix.Verbose { log.Printf("flush %d entries to %s", len(ix.post), w.Name()) } sortPost(ix.post) // Write the raw ix.post array to disk as is. // This process is the one reading it back in, so byte order is not a concern. data := (*[npost * 8]byte)(unsafe.Pointer(&ix.post[0]))[:len(ix.post)*8] if n, err := w.Write(data); err != nil || n < len(data) { if err != nil { log.Fatal(err) } log.Fatalf("short write writing %s", w.Name()) } ix.post = ix.post[:0] w.Seek(0, 0) ix.postFile = append(ix.postFile, w) }
[ "func", "(", "ix", "*", "IndexWriter", ")", "flushPost", "(", ")", "{", "w", ",", "err", ":=", "ioutil", ".", "TempFile", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatal", "(", "err", ")", "\n", "}", "\n", "if", "ix", ".", "Verbose", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "len", "(", "ix", ".", "post", ")", ",", "w", ".", "Name", "(", ")", ")", "\n", "}", "\n", "sortPost", "(", "ix", ".", "post", ")", "\n\n", "// Write the raw ix.post array to disk as is.", "// This process is the one reading it back in, so byte order is not a concern.", "data", ":=", "(", "*", "[", "npost", "*", "8", "]", "byte", ")", "(", "unsafe", ".", "Pointer", "(", "&", "ix", ".", "post", "[", "0", "]", ")", ")", "[", ":", "len", "(", "ix", ".", "post", ")", "*", "8", "]", "\n", "if", "n", ",", "err", ":=", "w", ".", "Write", "(", "data", ")", ";", "err", "!=", "nil", "||", "n", "<", "len", "(", "data", ")", "{", "if", "err", "!=", "nil", "{", "log", ".", "Fatal", "(", "err", ")", "\n", "}", "\n", "log", ".", "Fatalf", "(", "\"", "\"", ",", "w", ".", "Name", "(", ")", ")", "\n", "}", "\n\n", "ix", ".", "post", "=", "ix", ".", "post", "[", ":", "0", "]", "\n", "w", ".", "Seek", "(", "0", ",", "0", ")", "\n", "ix", ".", "postFile", "=", "append", "(", "ix", ".", "postFile", ",", "w", ")", "\n", "}" ]
// flushPost writes ix.post to a new temporary file and // clears the slice.
[ "flushPost", "writes", "ix", ".", "post", "to", "a", "new", "temporary", "file", "and", "clears", "the", "slice", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/write.go#L257-L280
train
google/codesearch
index/write.go
mergePost
func (ix *IndexWriter) mergePost(out *bufWriter) { var h postHeap log.Printf("merge %d files + mem", len(ix.postFile)) for _, f := range ix.postFile { h.addFile(f) } sortPost(ix.post) h.addMem(ix.post) npost := 0 e := h.next() offset0 := out.offset() for { npost++ offset := out.offset() - offset0 trigram := e.trigram() ix.buf[0] = byte(trigram >> 16) ix.buf[1] = byte(trigram >> 8) ix.buf[2] = byte(trigram) // posting list fileid := ^uint32(0) nfile := uint32(0) out.write(ix.buf[:3]) for ; e.trigram() == trigram && trigram != 1<<24-1; e = h.next() { out.writeUvarint(e.fileid() - fileid) fileid = e.fileid() nfile++ } out.writeUvarint(0) // index entry ix.postIndex.write(ix.buf[:3]) ix.postIndex.writeUint32(nfile) ix.postIndex.writeUint32(offset) if trigram == 1<<24-1 { break } } }
go
func (ix *IndexWriter) mergePost(out *bufWriter) { var h postHeap log.Printf("merge %d files + mem", len(ix.postFile)) for _, f := range ix.postFile { h.addFile(f) } sortPost(ix.post) h.addMem(ix.post) npost := 0 e := h.next() offset0 := out.offset() for { npost++ offset := out.offset() - offset0 trigram := e.trigram() ix.buf[0] = byte(trigram >> 16) ix.buf[1] = byte(trigram >> 8) ix.buf[2] = byte(trigram) // posting list fileid := ^uint32(0) nfile := uint32(0) out.write(ix.buf[:3]) for ; e.trigram() == trigram && trigram != 1<<24-1; e = h.next() { out.writeUvarint(e.fileid() - fileid) fileid = e.fileid() nfile++ } out.writeUvarint(0) // index entry ix.postIndex.write(ix.buf[:3]) ix.postIndex.writeUint32(nfile) ix.postIndex.writeUint32(offset) if trigram == 1<<24-1 { break } } }
[ "func", "(", "ix", "*", "IndexWriter", ")", "mergePost", "(", "out", "*", "bufWriter", ")", "{", "var", "h", "postHeap", "\n\n", "log", ".", "Printf", "(", "\"", "\"", ",", "len", "(", "ix", ".", "postFile", ")", ")", "\n", "for", "_", ",", "f", ":=", "range", "ix", ".", "postFile", "{", "h", ".", "addFile", "(", "f", ")", "\n", "}", "\n", "sortPost", "(", "ix", ".", "post", ")", "\n", "h", ".", "addMem", "(", "ix", ".", "post", ")", "\n\n", "npost", ":=", "0", "\n", "e", ":=", "h", ".", "next", "(", ")", "\n", "offset0", ":=", "out", ".", "offset", "(", ")", "\n", "for", "{", "npost", "++", "\n", "offset", ":=", "out", ".", "offset", "(", ")", "-", "offset0", "\n", "trigram", ":=", "e", ".", "trigram", "(", ")", "\n", "ix", ".", "buf", "[", "0", "]", "=", "byte", "(", "trigram", ">>", "16", ")", "\n", "ix", ".", "buf", "[", "1", "]", "=", "byte", "(", "trigram", ">>", "8", ")", "\n", "ix", ".", "buf", "[", "2", "]", "=", "byte", "(", "trigram", ")", "\n\n", "// posting list", "fileid", ":=", "^", "uint32", "(", "0", ")", "\n", "nfile", ":=", "uint32", "(", "0", ")", "\n", "out", ".", "write", "(", "ix", ".", "buf", "[", ":", "3", "]", ")", "\n", "for", ";", "e", ".", "trigram", "(", ")", "==", "trigram", "&&", "trigram", "!=", "1", "<<", "24", "-", "1", ";", "e", "=", "h", ".", "next", "(", ")", "{", "out", ".", "writeUvarint", "(", "e", ".", "fileid", "(", ")", "-", "fileid", ")", "\n", "fileid", "=", "e", ".", "fileid", "(", ")", "\n", "nfile", "++", "\n", "}", "\n", "out", ".", "writeUvarint", "(", "0", ")", "\n\n", "// index entry", "ix", ".", "postIndex", ".", "write", "(", "ix", ".", "buf", "[", ":", "3", "]", ")", "\n", "ix", ".", "postIndex", ".", "writeUint32", "(", "nfile", ")", "\n", "ix", ".", "postIndex", ".", "writeUint32", "(", "offset", ")", "\n\n", "if", "trigram", "==", "1", "<<", "24", "-", "1", "{", "break", "\n", "}", "\n", "}", "\n", "}" ]
// mergePost reads the flushed index entries and merges them // into posting lists, writing the resulting lists to out.
[ "mergePost", "reads", "the", "flushed", "index", "entries", "and", "merges", "them", "into", "posting", "lists", "writing", "the", "resulting", "lists", "to", "out", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/write.go#L284-L325
train
google/codesearch
index/write.go
step
func (h *postHeap) step(ch *postChunk) bool { old := ch.e m := ch.m if len(m) == 0 { return false } ch.e = postEntry(m[0]) m = m[1:] ch.m = m if old >= ch.e { panic("bad sort") } return true }
go
func (h *postHeap) step(ch *postChunk) bool { old := ch.e m := ch.m if len(m) == 0 { return false } ch.e = postEntry(m[0]) m = m[1:] ch.m = m if old >= ch.e { panic("bad sort") } return true }
[ "func", "(", "h", "*", "postHeap", ")", "step", "(", "ch", "*", "postChunk", ")", "bool", "{", "old", ":=", "ch", ".", "e", "\n", "m", ":=", "ch", ".", "m", "\n", "if", "len", "(", "m", ")", "==", "0", "{", "return", "false", "\n", "}", "\n", "ch", ".", "e", "=", "postEntry", "(", "m", "[", "0", "]", ")", "\n", "m", "=", "m", "[", "1", ":", "]", "\n", "ch", ".", "m", "=", "m", "\n", "if", "old", ">=", "ch", ".", "e", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "true", "\n", "}" ]
// step reads the next entry from ch and saves it in ch.e. // It returns false if ch is over.
[ "step", "reads", "the", "next", "entry", "from", "ch", "and", "saves", "it", "in", "ch", ".", "e", ".", "It", "returns", "false", "if", "ch", "is", "over", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/write.go#L353-L366
train
google/codesearch
index/write.go
add
func (h *postHeap) add(ch *postChunk) { if len(ch.m) > 0 { ch.e = ch.m[0] ch.m = ch.m[1:] h.push(ch) } }
go
func (h *postHeap) add(ch *postChunk) { if len(ch.m) > 0 { ch.e = ch.m[0] ch.m = ch.m[1:] h.push(ch) } }
[ "func", "(", "h", "*", "postHeap", ")", "add", "(", "ch", "*", "postChunk", ")", "{", "if", "len", "(", "ch", ".", "m", ")", ">", "0", "{", "ch", ".", "e", "=", "ch", ".", "m", "[", "0", "]", "\n", "ch", ".", "m", "=", "ch", ".", "m", "[", "1", ":", "]", "\n", "h", ".", "push", "(", "ch", ")", "\n", "}", "\n", "}" ]
// add adds the chunk to the postHeap. // All adds must be called before the first call to next.
[ "add", "adds", "the", "chunk", "to", "the", "postHeap", ".", "All", "adds", "must", "be", "called", "before", "the", "first", "call", "to", "next", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/write.go#L370-L376
train
google/codesearch
index/write.go
next
func (h *postHeap) next() postEntry { if len(h.ch) == 0 { return makePostEntry(1<<24-1, 0) } ch := h.ch[0] e := ch.e m := ch.m if len(m) == 0 { h.pop() } else { ch.e = m[0] ch.m = m[1:] h.siftDown(0) } return e }
go
func (h *postHeap) next() postEntry { if len(h.ch) == 0 { return makePostEntry(1<<24-1, 0) } ch := h.ch[0] e := ch.e m := ch.m if len(m) == 0 { h.pop() } else { ch.e = m[0] ch.m = m[1:] h.siftDown(0) } return e }
[ "func", "(", "h", "*", "postHeap", ")", "next", "(", ")", "postEntry", "{", "if", "len", "(", "h", ".", "ch", ")", "==", "0", "{", "return", "makePostEntry", "(", "1", "<<", "24", "-", "1", ",", "0", ")", "\n", "}", "\n", "ch", ":=", "h", ".", "ch", "[", "0", "]", "\n", "e", ":=", "ch", ".", "e", "\n", "m", ":=", "ch", ".", "m", "\n", "if", "len", "(", "m", ")", "==", "0", "{", "h", ".", "pop", "(", ")", "\n", "}", "else", "{", "ch", ".", "e", "=", "m", "[", "0", "]", "\n", "ch", ".", "m", "=", "m", "[", "1", ":", "]", "\n", "h", ".", "siftDown", "(", "0", ")", "\n", "}", "\n", "return", "e", "\n", "}" ]
// next returns the next entry from the postHeap. // It returns a postEntry with trigram == 1<<24 - 1 if h is empty.
[ "next", "returns", "the", "next", "entry", "from", "the", "postHeap", ".", "It", "returns", "a", "postEntry", "with", "trigram", "==", "1<<24", "-", "1", "if", "h", "is", "empty", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/write.go#L385-L400
train
google/codesearch
index/write.go
bufCreate
func bufCreate(name string) *bufWriter { var ( f *os.File err error ) if name != "" { f, err = os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) } else { f, err = ioutil.TempFile("", "csearch") } if err != nil { log.Fatal(err) } return &bufWriter{ name: f.Name(), buf: make([]byte, 0, 256<<10), file: f, } }
go
func bufCreate(name string) *bufWriter { var ( f *os.File err error ) if name != "" { f, err = os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) } else { f, err = ioutil.TempFile("", "csearch") } if err != nil { log.Fatal(err) } return &bufWriter{ name: f.Name(), buf: make([]byte, 0, 256<<10), file: f, } }
[ "func", "bufCreate", "(", "name", "string", ")", "*", "bufWriter", "{", "var", "(", "f", "*", "os", ".", "File", "\n", "err", "error", "\n", ")", "\n", "if", "name", "!=", "\"", "\"", "{", "f", ",", "err", "=", "os", ".", "OpenFile", "(", "name", ",", "os", ".", "O_RDWR", "|", "os", ".", "O_CREATE", "|", "os", ".", "O_TRUNC", ",", "0600", ")", "\n", "}", "else", "{", "f", ",", "err", "=", "ioutil", ".", "TempFile", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatal", "(", "err", ")", "\n", "}", "\n", "return", "&", "bufWriter", "{", "name", ":", "f", ".", "Name", "(", ")", ",", "buf", ":", "make", "(", "[", "]", "byte", ",", "0", ",", "256", "<<", "10", ")", ",", "file", ":", "f", ",", "}", "\n", "}" ]
// bufCreate creates a new file with the given name and returns a // corresponding bufWriter. If name is empty, bufCreate uses a // temporary file.
[ "bufCreate", "creates", "a", "new", "file", "with", "the", "given", "name", "and", "returns", "a", "corresponding", "bufWriter", ".", "If", "name", "is", "empty", "bufCreate", "uses", "a", "temporary", "file", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/write.go#L463-L481
train
google/codesearch
index/write.go
offset
func (b *bufWriter) offset() uint32 { off, _ := b.file.Seek(0, 1) off += int64(len(b.buf)) if int64(uint32(off)) != off { log.Fatalf("index is larger than 4GB") } return uint32(off) }
go
func (b *bufWriter) offset() uint32 { off, _ := b.file.Seek(0, 1) off += int64(len(b.buf)) if int64(uint32(off)) != off { log.Fatalf("index is larger than 4GB") } return uint32(off) }
[ "func", "(", "b", "*", "bufWriter", ")", "offset", "(", ")", "uint32", "{", "off", ",", "_", ":=", "b", ".", "file", ".", "Seek", "(", "0", ",", "1", ")", "\n", "off", "+=", "int64", "(", "len", "(", "b", ".", "buf", ")", ")", "\n", "if", "int64", "(", "uint32", "(", "off", ")", ")", "!=", "off", "{", "log", ".", "Fatalf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "uint32", "(", "off", ")", "\n", "}" ]
// offset returns the current write offset.
[ "offset", "returns", "the", "current", "write", "offset", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/write.go#L519-L526
train
google/codesearch
index/write.go
finish
func (b *bufWriter) finish() *os.File { b.flush() f := b.file f.Seek(0, 0) return f }
go
func (b *bufWriter) finish() *os.File { b.flush() f := b.file f.Seek(0, 0) return f }
[ "func", "(", "b", "*", "bufWriter", ")", "finish", "(", ")", "*", "os", ".", "File", "{", "b", ".", "flush", "(", ")", "\n", "f", ":=", "b", ".", "file", "\n", "f", ".", "Seek", "(", "0", ",", "0", ")", "\n", "return", "f", "\n", "}" ]
// finish flushes the file to disk and returns an open file ready for reading.
[ "finish", "flushes", "the", "file", "to", "disk", "and", "returns", "an", "open", "file", "ready", "for", "reading", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/write.go#L540-L545
train
google/codesearch
index/write.go
validUTF8
func validUTF8(c1, c2 uint32) bool { switch { case c1 < 0x80: // 1-byte, must be followed by 1-byte or first of multi-byte return c2 < 0x80 || 0xc0 <= c2 && c2 < 0xf8 case c1 < 0xc0: // continuation byte, can be followed by nearly anything return c2 < 0xf8 case c1 < 0xf8: // first of multi-byte, must be followed by continuation byte return 0x80 <= c2 && c2 < 0xc0 } return false }
go
func validUTF8(c1, c2 uint32) bool { switch { case c1 < 0x80: // 1-byte, must be followed by 1-byte or first of multi-byte return c2 < 0x80 || 0xc0 <= c2 && c2 < 0xf8 case c1 < 0xc0: // continuation byte, can be followed by nearly anything return c2 < 0xf8 case c1 < 0xf8: // first of multi-byte, must be followed by continuation byte return 0x80 <= c2 && c2 < 0xc0 } return false }
[ "func", "validUTF8", "(", "c1", ",", "c2", "uint32", ")", "bool", "{", "switch", "{", "case", "c1", "<", "0x80", ":", "// 1-byte, must be followed by 1-byte or first of multi-byte", "return", "c2", "<", "0x80", "||", "0xc0", "<=", "c2", "&&", "c2", "<", "0xf8", "\n", "case", "c1", "<", "0xc0", ":", "// continuation byte, can be followed by nearly anything", "return", "c2", "<", "0xf8", "\n", "case", "c1", "<", "0xf8", ":", "// first of multi-byte, must be followed by continuation byte", "return", "0x80", "<=", "c2", "&&", "c2", "<", "0xc0", "\n", "}", "\n", "return", "false", "\n", "}" ]
// validUTF8 reports whether the byte pair can appear in a // valid sequence of UTF-8-encoded code points.
[ "validUTF8", "reports", "whether", "the", "byte", "pair", "can", "appear", "in", "a", "valid", "sequence", "of", "UTF", "-", "8", "-", "encoded", "code", "points", "." ]
4fe90b597ae534f90238f82c7b5b1bb6d6d52dff
https://github.com/google/codesearch/blob/4fe90b597ae534f90238f82c7b5b1bb6d6d52dff/index/write.go#L581-L594
train
hyperledger/fabric-sdk-go
pkg/client/common/selection/dynamicselection/ccpolicyprovider.go
newCCPolicyProvider
func newCCPolicyProvider(ctx context.Client, discovery fab.DiscoveryService, channelID string) (CCPolicyProvider, error) { if channelID == "" { return nil, errors.New("Must provide channel ID for cc policy provider") } cpp := ccPolicyProvider{ context: ctx, channelID: channelID, discovery: discovery, ccDataMap: make(map[string]*ccprovider.ChaincodeData), } return &cpp, nil }
go
func newCCPolicyProvider(ctx context.Client, discovery fab.DiscoveryService, channelID string) (CCPolicyProvider, error) { if channelID == "" { return nil, errors.New("Must provide channel ID for cc policy provider") } cpp := ccPolicyProvider{ context: ctx, channelID: channelID, discovery: discovery, ccDataMap: make(map[string]*ccprovider.ChaincodeData), } return &cpp, nil }
[ "func", "newCCPolicyProvider", "(", "ctx", "context", ".", "Client", ",", "discovery", "fab", ".", "DiscoveryService", ",", "channelID", "string", ")", "(", "CCPolicyProvider", ",", "error", ")", "{", "if", "channelID", "==", "\"", "\"", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "cpp", ":=", "ccPolicyProvider", "{", "context", ":", "ctx", ",", "channelID", ":", "channelID", ",", "discovery", ":", "discovery", ",", "ccDataMap", ":", "make", "(", "map", "[", "string", "]", "*", "ccprovider", ".", "ChaincodeData", ")", ",", "}", "\n\n", "return", "&", "cpp", ",", "nil", "\n", "}" ]
// NewCCPolicyProvider creates new chaincode policy data provider
[ "NewCCPolicyProvider", "creates", "new", "chaincode", "policy", "data", "provider" ]
48bb0d199e2cee03ad3af0a413bdfc064fc69bfe
https://github.com/hyperledger/fabric-sdk-go/blob/48bb0d199e2cee03ad3af0a413bdfc064fc69bfe/pkg/client/common/selection/dynamicselection/ccpolicyprovider.go#L43-L56
train
hyperledger/fabric-sdk-go
pkg/fab/mocks/mockidentity.go
NewMockIdentity
func NewMockIdentity(err error) (msp.Identity, error) { return &MockIdentity{Err: err}, nil }
go
func NewMockIdentity(err error) (msp.Identity, error) { return &MockIdentity{Err: err}, nil }
[ "func", "NewMockIdentity", "(", "err", "error", ")", "(", "msp", ".", "Identity", ",", "error", ")", "{", "return", "&", "MockIdentity", "{", "Err", ":", "err", "}", ",", "nil", "\n", "}" ]
// NewMockIdentity creates new mock identity
[ "NewMockIdentity", "creates", "new", "mock", "identity" ]
48bb0d199e2cee03ad3af0a413bdfc064fc69bfe
https://github.com/hyperledger/fabric-sdk-go/blob/48bb0d199e2cee03ad3af0a413bdfc064fc69bfe/pkg/fab/mocks/mockidentity.go#L24-L26
train
hyperledger/fabric-sdk-go
pkg/fab/mocks/mockidentity.go
Validate
func (id *MockIdentity) Validate() error { if id.Err != nil && id.Err.Error() == "Validate" { return id.Err } return nil }
go
func (id *MockIdentity) Validate() error { if id.Err != nil && id.Err.Error() == "Validate" { return id.Err } return nil }
[ "func", "(", "id", "*", "MockIdentity", ")", "Validate", "(", ")", "error", "{", "if", "id", ".", "Err", "!=", "nil", "&&", "id", ".", "Err", ".", "Error", "(", ")", "==", "\"", "\"", "{", "return", "id", ".", "Err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Validate returns nil if this instance is a valid identity or an error otherwise
[ "Validate", "returns", "nil", "if", "this", "instance", "is", "a", "valid", "identity", "or", "an", "error", "otherwise" ]
48bb0d199e2cee03ad3af0a413bdfc064fc69bfe
https://github.com/hyperledger/fabric-sdk-go/blob/48bb0d199e2cee03ad3af0a413bdfc064fc69bfe/pkg/fab/mocks/mockidentity.go#L49-L54
train
hyperledger/fabric-sdk-go
pkg/fab/comm/streamconnection.go
NewStreamConnection
func NewStreamConnection(ctx fabcontext.Client, chConfig fab.ChannelCfg, streamProvider StreamProvider, url string, opts ...options.Opt) (*StreamConnection, error) { conn, err := NewConnection(ctx, url, opts...) if err != nil { return nil, err } stream, err := streamProvider(conn.conn) if err != nil { conn.commManager.ReleaseConn(conn.conn) return nil, errors.Wrapf(err, "could not create stream to %s", url) } if stream == nil { return nil, errors.New("unexpected nil stream received from provider") } peer, ok := peer.FromContext(stream.Context()) if !ok || peer == nil { //return error - certificate is not available return nil, errors.Wrap(err, "No peer cert in GRPC stream") } if peer.AuthInfo != nil { tlsInfo := peer.AuthInfo.(credentials.TLSInfo) for _, peercert := range tlsInfo.State.PeerCertificates { err := verifier.ValidateCertificateDates(peercert) if err != nil { logger.Error(err) return nil, errors.Wrapf(err, "error validating certificate dates for [%v]", peercert.Subject) } } } return &StreamConnection{ GRPCConnection: conn, chConfig: chConfig, stream: stream, }, nil }
go
func NewStreamConnection(ctx fabcontext.Client, chConfig fab.ChannelCfg, streamProvider StreamProvider, url string, opts ...options.Opt) (*StreamConnection, error) { conn, err := NewConnection(ctx, url, opts...) if err != nil { return nil, err } stream, err := streamProvider(conn.conn) if err != nil { conn.commManager.ReleaseConn(conn.conn) return nil, errors.Wrapf(err, "could not create stream to %s", url) } if stream == nil { return nil, errors.New("unexpected nil stream received from provider") } peer, ok := peer.FromContext(stream.Context()) if !ok || peer == nil { //return error - certificate is not available return nil, errors.Wrap(err, "No peer cert in GRPC stream") } if peer.AuthInfo != nil { tlsInfo := peer.AuthInfo.(credentials.TLSInfo) for _, peercert := range tlsInfo.State.PeerCertificates { err := verifier.ValidateCertificateDates(peercert) if err != nil { logger.Error(err) return nil, errors.Wrapf(err, "error validating certificate dates for [%v]", peercert.Subject) } } } return &StreamConnection{ GRPCConnection: conn, chConfig: chConfig, stream: stream, }, nil }
[ "func", "NewStreamConnection", "(", "ctx", "fabcontext", ".", "Client", ",", "chConfig", "fab", ".", "ChannelCfg", ",", "streamProvider", "StreamProvider", ",", "url", "string", ",", "opts", "...", "options", ".", "Opt", ")", "(", "*", "StreamConnection", ",", "error", ")", "{", "conn", ",", "err", ":=", "NewConnection", "(", "ctx", ",", "url", ",", "opts", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "stream", ",", "err", ":=", "streamProvider", "(", "conn", ".", "conn", ")", "\n", "if", "err", "!=", "nil", "{", "conn", ".", "commManager", ".", "ReleaseConn", "(", "conn", ".", "conn", ")", "\n", "return", "nil", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "url", ")", "\n", "}", "\n\n", "if", "stream", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "peer", ",", "ok", ":=", "peer", ".", "FromContext", "(", "stream", ".", "Context", "(", ")", ")", "\n", "if", "!", "ok", "||", "peer", "==", "nil", "{", "//return error - certificate is not available", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n\n", "}", "\n\n", "if", "peer", ".", "AuthInfo", "!=", "nil", "{", "tlsInfo", ":=", "peer", ".", "AuthInfo", ".", "(", "credentials", ".", "TLSInfo", ")", "\n", "for", "_", ",", "peercert", ":=", "range", "tlsInfo", ".", "State", ".", "PeerCertificates", "{", "err", ":=", "verifier", ".", "ValidateCertificateDates", "(", "peercert", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Error", "(", "err", ")", "\n", "return", "nil", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "peercert", ".", "Subject", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "&", "StreamConnection", "{", "GRPCConnection", ":", "conn", ",", "chConfig", ":", "chConfig", ",", "stream", ":", "stream", ",", "}", ",", "nil", "\n", "}" ]
// NewStreamConnection creates a new connection with stream
[ "NewStreamConnection", "creates", "a", "new", "connection", "with", "stream" ]
48bb0d199e2cee03ad3af0a413bdfc064fc69bfe
https://github.com/hyperledger/fabric-sdk-go/blob/48bb0d199e2cee03ad3af0a413bdfc064fc69bfe/pkg/fab/comm/streamconnection.go#L35-L74
train
hyperledger/fabric-sdk-go
pkg/fab/resource/config.go
CreateConfigSignature
func CreateConfigSignature(ctx context.Client, config []byte) (*common.ConfigSignature, error) { cfd, e := GetConfigSignatureData(ctx, config) if e != nil { return nil, e } signingMgr := ctx.SigningManager() signature, err := signingMgr.Sign(cfd.SigningBytes, ctx.PrivateKey()) if err != nil { return nil, errors.WithMessage(err, "signing of channel config failed") } // build the return object configSignature := common.ConfigSignature{ SignatureHeader: cfd.SignatureHeaderBytes, Signature: signature, } return &configSignature, nil }
go
func CreateConfigSignature(ctx context.Client, config []byte) (*common.ConfigSignature, error) { cfd, e := GetConfigSignatureData(ctx, config) if e != nil { return nil, e } signingMgr := ctx.SigningManager() signature, err := signingMgr.Sign(cfd.SigningBytes, ctx.PrivateKey()) if err != nil { return nil, errors.WithMessage(err, "signing of channel config failed") } // build the return object configSignature := common.ConfigSignature{ SignatureHeader: cfd.SignatureHeaderBytes, Signature: signature, } return &configSignature, nil }
[ "func", "CreateConfigSignature", "(", "ctx", "context", ".", "Client", ",", "config", "[", "]", "byte", ")", "(", "*", "common", ".", "ConfigSignature", ",", "error", ")", "{", "cfd", ",", "e", ":=", "GetConfigSignatureData", "(", "ctx", ",", "config", ")", "\n", "if", "e", "!=", "nil", "{", "return", "nil", ",", "e", "\n", "}", "\n\n", "signingMgr", ":=", "ctx", ".", "SigningManager", "(", ")", "\n", "signature", ",", "err", ":=", "signingMgr", ".", "Sign", "(", "cfd", ".", "SigningBytes", ",", "ctx", ".", "PrivateKey", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "WithMessage", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// build the return object", "configSignature", ":=", "common", ".", "ConfigSignature", "{", "SignatureHeader", ":", "cfd", ".", "SignatureHeaderBytes", ",", "Signature", ":", "signature", ",", "}", "\n", "return", "&", "configSignature", ",", "nil", "\n", "}" ]
// CreateConfigSignature creates a ConfigSignature for the current context
[ "CreateConfigSignature", "creates", "a", "ConfigSignature", "for", "the", "current", "context" ]
48bb0d199e2cee03ad3af0a413bdfc064fc69bfe
https://github.com/hyperledger/fabric-sdk-go/blob/48bb0d199e2cee03ad3af0a413bdfc064fc69bfe/pkg/fab/resource/config.go#L20-L38
train
hyperledger/fabric-sdk-go
pkg/fab/resource/config.go
ExtractChannelConfig
func ExtractChannelConfig(configEnvelope []byte) ([]byte, error) { envelope := &common.Envelope{} err := proto.Unmarshal(configEnvelope, envelope) if err != nil { return nil, errors.Wrap(err, "unmarshal config envelope failed") } payload := &common.Payload{} err = proto.Unmarshal(envelope.Payload, payload) if err != nil { return nil, errors.Wrap(err, "unmarshal envelope payload failed") } configUpdateEnvelope := &common.ConfigUpdateEnvelope{} err = proto.Unmarshal(payload.Data, configUpdateEnvelope) if err != nil { return nil, errors.Wrap(err, "unmarshal config update envelope") } return configUpdateEnvelope.ConfigUpdate, nil }
go
func ExtractChannelConfig(configEnvelope []byte) ([]byte, error) { envelope := &common.Envelope{} err := proto.Unmarshal(configEnvelope, envelope) if err != nil { return nil, errors.Wrap(err, "unmarshal config envelope failed") } payload := &common.Payload{} err = proto.Unmarshal(envelope.Payload, payload) if err != nil { return nil, errors.Wrap(err, "unmarshal envelope payload failed") } configUpdateEnvelope := &common.ConfigUpdateEnvelope{} err = proto.Unmarshal(payload.Data, configUpdateEnvelope) if err != nil { return nil, errors.Wrap(err, "unmarshal config update envelope") } return configUpdateEnvelope.ConfigUpdate, nil }
[ "func", "ExtractChannelConfig", "(", "configEnvelope", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "envelope", ":=", "&", "common", ".", "Envelope", "{", "}", "\n", "err", ":=", "proto", ".", "Unmarshal", "(", "configEnvelope", ",", "envelope", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "payload", ":=", "&", "common", ".", "Payload", "{", "}", "\n", "err", "=", "proto", ".", "Unmarshal", "(", "envelope", ".", "Payload", ",", "payload", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "configUpdateEnvelope", ":=", "&", "common", ".", "ConfigUpdateEnvelope", "{", "}", "\n", "err", "=", "proto", ".", "Unmarshal", "(", "payload", ".", "Data", ",", "configUpdateEnvelope", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "configUpdateEnvelope", ".", "ConfigUpdate", ",", "nil", "\n", "}" ]
// ExtractChannelConfig extracts the protobuf 'ConfigUpdate' object out of the 'ConfigEnvelope'.
[ "ExtractChannelConfig", "extracts", "the", "protobuf", "ConfigUpdate", "object", "out", "of", "the", "ConfigEnvelope", "." ]
48bb0d199e2cee03ad3af0a413bdfc064fc69bfe
https://github.com/hyperledger/fabric-sdk-go/blob/48bb0d199e2cee03ad3af0a413bdfc064fc69bfe/pkg/fab/resource/config.go#L90-L111
train
hyperledger/fabric-sdk-go
pkg/fab/resource/config.go
CreateConfigEnvelope
func CreateConfigEnvelope(data []byte) (*common.ConfigEnvelope, error) { envelope := &common.Envelope{} if err := proto.Unmarshal(data, envelope); err != nil { return nil, errors.Wrap(err, "unmarshal envelope from config block failed") } payload := &common.Payload{} if err := proto.Unmarshal(envelope.Payload, payload); err != nil { return nil, errors.Wrap(err, "unmarshal payload from envelope failed") } channelHeader := &common.ChannelHeader{} if err := proto.Unmarshal(payload.Header.ChannelHeader, channelHeader); err != nil { return nil, errors.Wrap(err, "unmarshal payload from envelope failed") } if common.HeaderType(channelHeader.Type) != common.HeaderType_CONFIG { return nil, errors.New("block must be of type 'CONFIG'") } configEnvelope := &common.ConfigEnvelope{} if err := proto.Unmarshal(payload.Data, configEnvelope); err != nil { return nil, errors.Wrap(err, "unmarshal config envelope failed") } return configEnvelope, nil }
go
func CreateConfigEnvelope(data []byte) (*common.ConfigEnvelope, error) { envelope := &common.Envelope{} if err := proto.Unmarshal(data, envelope); err != nil { return nil, errors.Wrap(err, "unmarshal envelope from config block failed") } payload := &common.Payload{} if err := proto.Unmarshal(envelope.Payload, payload); err != nil { return nil, errors.Wrap(err, "unmarshal payload from envelope failed") } channelHeader := &common.ChannelHeader{} if err := proto.Unmarshal(payload.Header.ChannelHeader, channelHeader); err != nil { return nil, errors.Wrap(err, "unmarshal payload from envelope failed") } if common.HeaderType(channelHeader.Type) != common.HeaderType_CONFIG { return nil, errors.New("block must be of type 'CONFIG'") } configEnvelope := &common.ConfigEnvelope{} if err := proto.Unmarshal(payload.Data, configEnvelope); err != nil { return nil, errors.Wrap(err, "unmarshal config envelope failed") } return configEnvelope, nil }
[ "func", "CreateConfigEnvelope", "(", "data", "[", "]", "byte", ")", "(", "*", "common", ".", "ConfigEnvelope", ",", "error", ")", "{", "envelope", ":=", "&", "common", ".", "Envelope", "{", "}", "\n", "if", "err", ":=", "proto", ".", "Unmarshal", "(", "data", ",", "envelope", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "payload", ":=", "&", "common", ".", "Payload", "{", "}", "\n", "if", "err", ":=", "proto", ".", "Unmarshal", "(", "envelope", ".", "Payload", ",", "payload", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "channelHeader", ":=", "&", "common", ".", "ChannelHeader", "{", "}", "\n", "if", "err", ":=", "proto", ".", "Unmarshal", "(", "payload", ".", "Header", ".", "ChannelHeader", ",", "channelHeader", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "common", ".", "HeaderType", "(", "channelHeader", ".", "Type", ")", "!=", "common", ".", "HeaderType_CONFIG", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "configEnvelope", ":=", "&", "common", ".", "ConfigEnvelope", "{", "}", "\n", "if", "err", ":=", "proto", ".", "Unmarshal", "(", "payload", ".", "Data", ",", "configEnvelope", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "configEnvelope", ",", "nil", "\n", "}" ]
// CreateConfigEnvelope creates configuration envelope proto
[ "CreateConfigEnvelope", "creates", "configuration", "envelope", "proto" ]
48bb0d199e2cee03ad3af0a413bdfc064fc69bfe
https://github.com/hyperledger/fabric-sdk-go/blob/48bb0d199e2cee03ad3af0a413bdfc064fc69bfe/pkg/fab/resource/config.go#L114-L137
train
hyperledger/fabric-sdk-go
pkg/fab/resource/config.go
GetLastConfigFromBlock
func GetLastConfigFromBlock(block *common.Block) (*common.LastConfig, error) { if block.Metadata == nil { return nil, errors.New("block metadata is nil") } metadata := &common.Metadata{} err := proto.Unmarshal(block.Metadata.Metadata[common.BlockMetadataIndex_LAST_CONFIG], metadata) if err != nil { return nil, errors.Wrap(err, "unmarshal block metadata failed") } lastConfig := &common.LastConfig{} err = proto.Unmarshal(metadata.Value, lastConfig) if err != nil { return nil, errors.Wrap(err, "unmarshal last config from metadata failed") } return lastConfig, err }
go
func GetLastConfigFromBlock(block *common.Block) (*common.LastConfig, error) { if block.Metadata == nil { return nil, errors.New("block metadata is nil") } metadata := &common.Metadata{} err := proto.Unmarshal(block.Metadata.Metadata[common.BlockMetadataIndex_LAST_CONFIG], metadata) if err != nil { return nil, errors.Wrap(err, "unmarshal block metadata failed") } lastConfig := &common.LastConfig{} err = proto.Unmarshal(metadata.Value, lastConfig) if err != nil { return nil, errors.Wrap(err, "unmarshal last config from metadata failed") } return lastConfig, err }
[ "func", "GetLastConfigFromBlock", "(", "block", "*", "common", ".", "Block", ")", "(", "*", "common", ".", "LastConfig", ",", "error", ")", "{", "if", "block", ".", "Metadata", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "metadata", ":=", "&", "common", ".", "Metadata", "{", "}", "\n", "err", ":=", "proto", ".", "Unmarshal", "(", "block", ".", "Metadata", ".", "Metadata", "[", "common", ".", "BlockMetadataIndex_LAST_CONFIG", "]", ",", "metadata", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "lastConfig", ":=", "&", "common", ".", "LastConfig", "{", "}", "\n", "err", "=", "proto", ".", "Unmarshal", "(", "metadata", ".", "Value", ",", "lastConfig", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "lastConfig", ",", "err", "\n", "}" ]
// GetLastConfigFromBlock returns the LastConfig data from the given block
[ "GetLastConfigFromBlock", "returns", "the", "LastConfig", "data", "from", "the", "given", "block" ]
48bb0d199e2cee03ad3af0a413bdfc064fc69bfe
https://github.com/hyperledger/fabric-sdk-go/blob/48bb0d199e2cee03ad3af0a413bdfc064fc69bfe/pkg/fab/resource/config.go#L166-L183
train
hyperledger/fabric-sdk-go
pkg/core/cryptosuite/cryptoconfig.go
ConfigFromBackend
func ConfigFromBackend(coreBackend ...core.ConfigBackend) core.CryptoSuiteConfig { return &Config{backend: lookup.New(coreBackend...)} }
go
func ConfigFromBackend(coreBackend ...core.ConfigBackend) core.CryptoSuiteConfig { return &Config{backend: lookup.New(coreBackend...)} }
[ "func", "ConfigFromBackend", "(", "coreBackend", "...", "core", ".", "ConfigBackend", ")", "core", ".", "CryptoSuiteConfig", "{", "return", "&", "Config", "{", "backend", ":", "lookup", ".", "New", "(", "coreBackend", "...", ")", "}", "\n", "}" ]
//ConfigFromBackend returns CryptoSuite config implementation for given backend
[ "ConfigFromBackend", "returns", "CryptoSuite", "config", "implementation", "for", "given", "backend" ]
48bb0d199e2cee03ad3af0a413bdfc064fc69bfe
https://github.com/hyperledger/fabric-sdk-go/blob/48bb0d199e2cee03ad3af0a413bdfc064fc69bfe/pkg/core/cryptosuite/cryptoconfig.go#L29-L31
train