id int32 0 167k | repo stringlengths 5 54 | path stringlengths 4 155 | func_name stringlengths 1 118 | original_string stringlengths 52 85.5k | language stringclasses 1
value | code stringlengths 52 85.5k | code_tokens listlengths 21 1.41k | docstring stringlengths 6 2.61k | docstring_tokens listlengths 3 215 | sha stringlengths 40 40 | url stringlengths 85 252 |
|---|---|---|---|---|---|---|---|---|---|---|---|
16,300 | openfaas/faas-provider | proxy/proxy.go | buildProxyRequest | func buildProxyRequest(originalReq *http.Request, baseURL url.URL, extraPath string) (*http.Request, error) {
host := baseURL.Host
if baseURL.Port() == "" {
host = baseURL.Host + ":" + watchdogPort
}
url := url.URL{
Scheme: baseURL.Scheme,
Host: host,
Path: extraPath,
RawQuery: originalReq.URL.RawQuery,
}
upstreamReq, err := http.NewRequest(originalReq.Method, url.String(), nil)
if err != nil {
return nil, err
}
copyHeaders(upstreamReq.Header, &originalReq.Header)
if len(originalReq.Host) > 0 && upstreamReq.Header.Get("X-Forwarded-Host") == "" {
upstreamReq.Header["X-Forwarded-Host"] = []string{originalReq.Host}
}
if upstreamReq.Header.Get("X-Forwarded-For") == "" {
upstreamReq.Header["X-Forwarded-For"] = []string{originalReq.RemoteAddr}
}
if originalReq.Body != nil {
upstreamReq.Body = originalReq.Body
}
return upstreamReq, nil
} | go | func buildProxyRequest(originalReq *http.Request, baseURL url.URL, extraPath string) (*http.Request, error) {
host := baseURL.Host
if baseURL.Port() == "" {
host = baseURL.Host + ":" + watchdogPort
}
url := url.URL{
Scheme: baseURL.Scheme,
Host: host,
Path: extraPath,
RawQuery: originalReq.URL.RawQuery,
}
upstreamReq, err := http.NewRequest(originalReq.Method, url.String(), nil)
if err != nil {
return nil, err
}
copyHeaders(upstreamReq.Header, &originalReq.Header)
if len(originalReq.Host) > 0 && upstreamReq.Header.Get("X-Forwarded-Host") == "" {
upstreamReq.Header["X-Forwarded-Host"] = []string{originalReq.Host}
}
if upstreamReq.Header.Get("X-Forwarded-For") == "" {
upstreamReq.Header["X-Forwarded-For"] = []string{originalReq.RemoteAddr}
}
if originalReq.Body != nil {
upstreamReq.Body = originalReq.Body
}
return upstreamReq, nil
} | [
"func",
"buildProxyRequest",
"(",
"originalReq",
"*",
"http",
".",
"Request",
",",
"baseURL",
"url",
".",
"URL",
",",
"extraPath",
"string",
")",
"(",
"*",
"http",
".",
"Request",
",",
"error",
")",
"{",
"host",
":=",
"baseURL",
".",
"Host",
"\n",
"if"... | // buildProxyRequest creates a request object for the proxy request, it will ensure that
// the original request headers are preserved as well as setting openfaas system headers | [
"buildProxyRequest",
"creates",
"a",
"request",
"object",
"for",
"the",
"proxy",
"request",
"it",
"will",
"ensure",
"that",
"the",
"original",
"request",
"headers",
"are",
"preserved",
"as",
"well",
"as",
"setting",
"openfaas",
"system",
"headers"
] | 6a76a052deb12fd94b373c082963d8a8ad44d4d1 | https://github.com/openfaas/faas-provider/blob/6a76a052deb12fd94b373c082963d8a8ad44d4d1/proxy/proxy.go#L157-L189 |
16,301 | openfaas/faas-provider | proxy/proxy.go | copyHeaders | func copyHeaders(destination http.Header, source *http.Header) {
for k, v := range *source {
vClone := make([]string, len(v))
copy(vClone, v)
destination[k] = vClone
}
} | go | func copyHeaders(destination http.Header, source *http.Header) {
for k, v := range *source {
vClone := make([]string, len(v))
copy(vClone, v)
destination[k] = vClone
}
} | [
"func",
"copyHeaders",
"(",
"destination",
"http",
".",
"Header",
",",
"source",
"*",
"http",
".",
"Header",
")",
"{",
"for",
"k",
",",
"v",
":=",
"range",
"*",
"source",
"{",
"vClone",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"v",
... | // copyHeaders clones the header values from the source into the destination. | [
"copyHeaders",
"clones",
"the",
"header",
"values",
"from",
"the",
"source",
"into",
"the",
"destination",
"."
] | 6a76a052deb12fd94b373c082963d8a8ad44d4d1 | https://github.com/openfaas/faas-provider/blob/6a76a052deb12fd94b373c082963d8a8ad44d4d1/proxy/proxy.go#L192-L198 |
16,302 | openfaas/faas-provider | proxy/proxy.go | getContentType | func getContentType(request http.Header, proxyResponse http.Header) (headerContentType string) {
responseHeader := proxyResponse.Get("Content-Type")
requestHeader := request.Get("Content-Type")
if len(responseHeader) > 0 {
headerContentType = responseHeader
} else if len(requestHeader) > 0 {
headerContentType = requestHeader
} else {
headerContentType = defaultContentType
}
return headerContentType
} | go | func getContentType(request http.Header, proxyResponse http.Header) (headerContentType string) {
responseHeader := proxyResponse.Get("Content-Type")
requestHeader := request.Get("Content-Type")
if len(responseHeader) > 0 {
headerContentType = responseHeader
} else if len(requestHeader) > 0 {
headerContentType = requestHeader
} else {
headerContentType = defaultContentType
}
return headerContentType
} | [
"func",
"getContentType",
"(",
"request",
"http",
".",
"Header",
",",
"proxyResponse",
"http",
".",
"Header",
")",
"(",
"headerContentType",
"string",
")",
"{",
"responseHeader",
":=",
"proxyResponse",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"requestHeader",
... | // getContentType resolves the correct Content-Type for a proxied function. | [
"getContentType",
"resolves",
"the",
"correct",
"Content",
"-",
"Type",
"for",
"a",
"proxied",
"function",
"."
] | 6a76a052deb12fd94b373c082963d8a8ad44d4d1 | https://github.com/openfaas/faas-provider/blob/6a76a052deb12fd94b373c082963d8a8ad44d4d1/proxy/proxy.go#L201-L214 |
16,303 | openfaas/faas-provider | proxy/proxy.go | writeError | func writeError(w http.ResponseWriter, statusCode int, msg string, args ...interface{}) {
w.WriteHeader(statusCode)
w.Write([]byte(fmt.Sprintf(msg, args...)))
} | go | func writeError(w http.ResponseWriter, statusCode int, msg string, args ...interface{}) {
w.WriteHeader(statusCode)
w.Write([]byte(fmt.Sprintf(msg, args...)))
} | [
"func",
"writeError",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"statusCode",
"int",
",",
"msg",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"w",
".",
"WriteHeader",
"(",
"statusCode",
")",
"\n",
"w",
".",
"Write",
"(",
"[",
"]... | // writeError sets the response status code and write formats the provided message as the
// response body | [
"writeError",
"sets",
"the",
"response",
"status",
"code",
"and",
"write",
"formats",
"the",
"provided",
"message",
"as",
"the",
"response",
"body"
] | 6a76a052deb12fd94b373c082963d8a8ad44d4d1 | https://github.com/openfaas/faas-provider/blob/6a76a052deb12fd94b373c082963d8a8ad44d4d1/proxy/proxy.go#L218-L221 |
16,304 | openfaas/faas-provider | serve.go | Serve | func Serve(handlers *types.FaaSHandlers, config *types.FaaSConfig) {
if config.EnableBasicAuth {
reader := auth.ReadBasicAuthFromDisk{
SecretMountPath: config.SecretMountPath,
}
credentials, err := reader.Read()
if err != nil {
log.Fatal(err)
}
handlers.FunctionReader = auth.DecorateWithBasicAuth(handlers.FunctionReader, credentials)
handlers.DeployHandler = auth.DecorateWithBasicAuth(handlers.DeployHandler, credentials)
handlers.DeleteHandler = auth.DecorateWithBasicAuth(handlers.DeleteHandler, credentials)
handlers.UpdateHandler = auth.DecorateWithBasicAuth(handlers.UpdateHandler, credentials)
handlers.ReplicaReader = auth.DecorateWithBasicAuth(handlers.ReplicaReader, credentials)
handlers.ReplicaUpdater = auth.DecorateWithBasicAuth(handlers.ReplicaUpdater, credentials)
handlers.InfoHandler = auth.DecorateWithBasicAuth(handlers.InfoHandler, credentials)
handlers.SecretHandler = auth.DecorateWithBasicAuth(handlers.SecretHandler, credentials)
}
// System (auth) endpoints
r.HandleFunc("/system/functions", handlers.FunctionReader).Methods("GET")
r.HandleFunc("/system/functions", handlers.DeployHandler).Methods("POST")
r.HandleFunc("/system/functions", handlers.DeleteHandler).Methods("DELETE")
r.HandleFunc("/system/functions", handlers.UpdateHandler).Methods("PUT")
r.HandleFunc("/system/function/{name:[-a-zA-Z_0-9]+}", handlers.ReplicaReader).Methods("GET")
r.HandleFunc("/system/scale-function/{name:[-a-zA-Z_0-9]+}", handlers.ReplicaUpdater).Methods("POST")
r.HandleFunc("/system/info", handlers.InfoHandler).Methods("GET")
r.HandleFunc("/system/secrets", handlers.SecretHandler).Methods(http.MethodGet, http.MethodPut, http.MethodPost, http.MethodDelete)
// Open endpoints
r.HandleFunc("/function/{name:[-a-zA-Z_0-9]+}", handlers.FunctionProxy)
r.HandleFunc("/function/{name:[-a-zA-Z_0-9]+}/", handlers.FunctionProxy)
r.HandleFunc("/function/{name:[-a-zA-Z_0-9]+}/{params:.*}", handlers.FunctionProxy)
if config.EnableHealth {
r.HandleFunc("/healthz", handlers.HealthHandler).Methods("GET")
}
readTimeout := config.ReadTimeout
writeTimeout := config.WriteTimeout
tcpPort := 8080
if config.TCPPort != nil {
tcpPort = *config.TCPPort
}
s := &http.Server{
Addr: fmt.Sprintf(":%d", tcpPort),
ReadTimeout: readTimeout,
WriteTimeout: writeTimeout,
MaxHeaderBytes: http.DefaultMaxHeaderBytes, // 1MB - can be overridden by setting Server.MaxHeaderBytes.
Handler: r,
}
log.Fatal(s.ListenAndServe())
} | go | func Serve(handlers *types.FaaSHandlers, config *types.FaaSConfig) {
if config.EnableBasicAuth {
reader := auth.ReadBasicAuthFromDisk{
SecretMountPath: config.SecretMountPath,
}
credentials, err := reader.Read()
if err != nil {
log.Fatal(err)
}
handlers.FunctionReader = auth.DecorateWithBasicAuth(handlers.FunctionReader, credentials)
handlers.DeployHandler = auth.DecorateWithBasicAuth(handlers.DeployHandler, credentials)
handlers.DeleteHandler = auth.DecorateWithBasicAuth(handlers.DeleteHandler, credentials)
handlers.UpdateHandler = auth.DecorateWithBasicAuth(handlers.UpdateHandler, credentials)
handlers.ReplicaReader = auth.DecorateWithBasicAuth(handlers.ReplicaReader, credentials)
handlers.ReplicaUpdater = auth.DecorateWithBasicAuth(handlers.ReplicaUpdater, credentials)
handlers.InfoHandler = auth.DecorateWithBasicAuth(handlers.InfoHandler, credentials)
handlers.SecretHandler = auth.DecorateWithBasicAuth(handlers.SecretHandler, credentials)
}
// System (auth) endpoints
r.HandleFunc("/system/functions", handlers.FunctionReader).Methods("GET")
r.HandleFunc("/system/functions", handlers.DeployHandler).Methods("POST")
r.HandleFunc("/system/functions", handlers.DeleteHandler).Methods("DELETE")
r.HandleFunc("/system/functions", handlers.UpdateHandler).Methods("PUT")
r.HandleFunc("/system/function/{name:[-a-zA-Z_0-9]+}", handlers.ReplicaReader).Methods("GET")
r.HandleFunc("/system/scale-function/{name:[-a-zA-Z_0-9]+}", handlers.ReplicaUpdater).Methods("POST")
r.HandleFunc("/system/info", handlers.InfoHandler).Methods("GET")
r.HandleFunc("/system/secrets", handlers.SecretHandler).Methods(http.MethodGet, http.MethodPut, http.MethodPost, http.MethodDelete)
// Open endpoints
r.HandleFunc("/function/{name:[-a-zA-Z_0-9]+}", handlers.FunctionProxy)
r.HandleFunc("/function/{name:[-a-zA-Z_0-9]+}/", handlers.FunctionProxy)
r.HandleFunc("/function/{name:[-a-zA-Z_0-9]+}/{params:.*}", handlers.FunctionProxy)
if config.EnableHealth {
r.HandleFunc("/healthz", handlers.HealthHandler).Methods("GET")
}
readTimeout := config.ReadTimeout
writeTimeout := config.WriteTimeout
tcpPort := 8080
if config.TCPPort != nil {
tcpPort = *config.TCPPort
}
s := &http.Server{
Addr: fmt.Sprintf(":%d", tcpPort),
ReadTimeout: readTimeout,
WriteTimeout: writeTimeout,
MaxHeaderBytes: http.DefaultMaxHeaderBytes, // 1MB - can be overridden by setting Server.MaxHeaderBytes.
Handler: r,
}
log.Fatal(s.ListenAndServe())
} | [
"func",
"Serve",
"(",
"handlers",
"*",
"types",
".",
"FaaSHandlers",
",",
"config",
"*",
"types",
".",
"FaaSConfig",
")",
"{",
"if",
"config",
".",
"EnableBasicAuth",
"{",
"reader",
":=",
"auth",
".",
"ReadBasicAuthFromDisk",
"{",
"SecretMountPath",
":",
"co... | // Serve load your handlers into the correct OpenFaaS route spec. This function is blocking. | [
"Serve",
"load",
"your",
"handlers",
"into",
"the",
"correct",
"OpenFaaS",
"route",
"spec",
".",
"This",
"function",
"is",
"blocking",
"."
] | 6a76a052deb12fd94b373c082963d8a8ad44d4d1 | https://github.com/openfaas/faas-provider/blob/6a76a052deb12fd94b373c082963d8a8ad44d4d1/serve.go#L29-L89 |
16,305 | tcnksm/go-input | input.go | setDefault | func (i *UI) setDefault() {
// Set the default writer & reader if not provided
if i.Writer == nil {
i.Writer = defaultWriter
}
if i.Reader == nil {
i.Reader = defaultReader
}
if i.bReader == nil {
i.bReader = bufio.NewReader(i.Reader)
}
} | go | func (i *UI) setDefault() {
// Set the default writer & reader if not provided
if i.Writer == nil {
i.Writer = defaultWriter
}
if i.Reader == nil {
i.Reader = defaultReader
}
if i.bReader == nil {
i.bReader = bufio.NewReader(i.Reader)
}
} | [
"func",
"(",
"i",
"*",
"UI",
")",
"setDefault",
"(",
")",
"{",
"// Set the default writer & reader if not provided",
"if",
"i",
".",
"Writer",
"==",
"nil",
"{",
"i",
".",
"Writer",
"=",
"defaultWriter",
"\n",
"}",
"\n\n",
"if",
"i",
".",
"Reader",
"==",
... | // setDefault sets the default value for UI struct. | [
"setDefault",
"sets",
"the",
"default",
"value",
"for",
"UI",
"struct",
"."
] | 548a7d7a8ee8fcb3d013fae6acf857da56165975 | https://github.com/tcnksm/go-input/blob/548a7d7a8ee8fcb3d013fae6acf857da56165975/input.go#L72-L85 |
16,306 | tcnksm/go-input | input.go | validateFunc | func (o *Options) validateFunc() ValidateFunc {
if o.ValidateFunc == nil {
return defaultValidateFunc
}
return o.ValidateFunc
} | go | func (o *Options) validateFunc() ValidateFunc {
if o.ValidateFunc == nil {
return defaultValidateFunc
}
return o.ValidateFunc
} | [
"func",
"(",
"o",
"*",
"Options",
")",
"validateFunc",
"(",
")",
"ValidateFunc",
"{",
"if",
"o",
".",
"ValidateFunc",
"==",
"nil",
"{",
"return",
"defaultValidateFunc",
"\n",
"}",
"\n\n",
"return",
"o",
".",
"ValidateFunc",
"\n",
"}"
] | // validateFunc returns ValidateFunc. If it's specified by
// user it returns it. If not returns default function. | [
"validateFunc",
"returns",
"ValidateFunc",
".",
"If",
"it",
"s",
"specified",
"by",
"user",
"it",
"returns",
"it",
".",
"If",
"not",
"returns",
"default",
"function",
"."
] | 548a7d7a8ee8fcb3d013fae6acf857da56165975 | https://github.com/tcnksm/go-input/blob/548a7d7a8ee8fcb3d013fae6acf857da56165975/input.go#L132-L138 |
16,307 | tcnksm/go-input | input.go | readOpts | func (o *Options) readOpts() *readOptions {
var mask bool
var maskVal string
// Hide input and prompt nothing on screen.
if o.Hide {
mask = true
}
// Mask input and prompt default maskVal.
if o.Mask {
mask = true
maskVal = defaultMaskVal
}
// Mask input and prompt custom maskVal.
if o.MaskVal != "" {
maskVal = o.MaskVal
}
return &readOptions{
mask: mask,
maskVal: maskVal,
}
} | go | func (o *Options) readOpts() *readOptions {
var mask bool
var maskVal string
// Hide input and prompt nothing on screen.
if o.Hide {
mask = true
}
// Mask input and prompt default maskVal.
if o.Mask {
mask = true
maskVal = defaultMaskVal
}
// Mask input and prompt custom maskVal.
if o.MaskVal != "" {
maskVal = o.MaskVal
}
return &readOptions{
mask: mask,
maskVal: maskVal,
}
} | [
"func",
"(",
"o",
"*",
"Options",
")",
"readOpts",
"(",
")",
"*",
"readOptions",
"{",
"var",
"mask",
"bool",
"\n",
"var",
"maskVal",
"string",
"\n\n",
"// Hide input and prompt nothing on screen.",
"if",
"o",
".",
"Hide",
"{",
"mask",
"=",
"true",
"\n",
"}... | // readOpts returns readOptions from given the Options. | [
"readOpts",
"returns",
"readOptions",
"from",
"given",
"the",
"Options",
"."
] | 548a7d7a8ee8fcb3d013fae6acf857da56165975 | https://github.com/tcnksm/go-input/blob/548a7d7a8ee8fcb3d013fae6acf857da56165975/input.go#L147-L171 |
16,308 | tcnksm/go-input | read.go | read | func (i *UI) read(opts *readOptions) (string, error) {
i.once.Do(i.setDefault)
// sigCh is channel which is watch Interruptted signal (SIGINT)
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, os.Interrupt)
defer signal.Stop(sigCh)
var resultStr string
var resultErr error
doneCh := make(chan struct{})
go func() {
defer close(doneCh)
if opts.mask {
f, ok := i.Reader.(*os.File)
if !ok {
resultErr = fmt.Errorf("reader must be a file")
return
}
i.mask, i.maskVal = opts.mask, opts.maskVal
resultStr, resultErr = i.rawRead(f)
} else {
line, err := i.bReader.ReadString('\n')
if err != nil && err != io.EOF {
resultErr = fmt.Errorf("failed to read the input: %s", err)
}
resultStr = strings.TrimSuffix(line, LineSep)
// brute force for the moment
resultStr = strings.TrimSuffix(line, "\n")
}
}()
select {
case <-sigCh:
return "", ErrInterrupted
case <-doneCh:
return resultStr, resultErr
}
} | go | func (i *UI) read(opts *readOptions) (string, error) {
i.once.Do(i.setDefault)
// sigCh is channel which is watch Interruptted signal (SIGINT)
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, os.Interrupt)
defer signal.Stop(sigCh)
var resultStr string
var resultErr error
doneCh := make(chan struct{})
go func() {
defer close(doneCh)
if opts.mask {
f, ok := i.Reader.(*os.File)
if !ok {
resultErr = fmt.Errorf("reader must be a file")
return
}
i.mask, i.maskVal = opts.mask, opts.maskVal
resultStr, resultErr = i.rawRead(f)
} else {
line, err := i.bReader.ReadString('\n')
if err != nil && err != io.EOF {
resultErr = fmt.Errorf("failed to read the input: %s", err)
}
resultStr = strings.TrimSuffix(line, LineSep)
// brute force for the moment
resultStr = strings.TrimSuffix(line, "\n")
}
}()
select {
case <-sigCh:
return "", ErrInterrupted
case <-doneCh:
return resultStr, resultErr
}
} | [
"func",
"(",
"i",
"*",
"UI",
")",
"read",
"(",
"opts",
"*",
"readOptions",
")",
"(",
"string",
",",
"error",
")",
"{",
"i",
".",
"once",
".",
"Do",
"(",
"i",
".",
"setDefault",
")",
"\n\n",
"// sigCh is channel which is watch Interruptted signal (SIGINT)",
... | // read reads input from UI.Reader | [
"read",
"reads",
"input",
"from",
"UI",
".",
"Reader"
] | 548a7d7a8ee8fcb3d013fae6acf857da56165975 | https://github.com/tcnksm/go-input/blob/548a7d7a8ee8fcb3d013fae6acf857da56165975/read.go#L19-L61 |
16,309 | wunderlist/ttlcache | cache.go | Set | func (cache *Cache) Set(key string, data string) {
cache.mutex.Lock()
item := &Item{data: data}
item.touch(cache.ttl)
cache.items[key] = item
cache.mutex.Unlock()
} | go | func (cache *Cache) Set(key string, data string) {
cache.mutex.Lock()
item := &Item{data: data}
item.touch(cache.ttl)
cache.items[key] = item
cache.mutex.Unlock()
} | [
"func",
"(",
"cache",
"*",
"Cache",
")",
"Set",
"(",
"key",
"string",
",",
"data",
"string",
")",
"{",
"cache",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"item",
":=",
"&",
"Item",
"{",
"data",
":",
"data",
"}",
"\n",
"item",
".",
"touch",
"("... | // Set is a thread-safe way to add new items to the map | [
"Set",
"is",
"a",
"thread",
"-",
"safe",
"way",
"to",
"add",
"new",
"items",
"to",
"the",
"map"
] | 7dbceb0d509466e07d5d066ea0859f1d8fc8f2fd | https://github.com/wunderlist/ttlcache/blob/7dbceb0d509466e07d5d066ea0859f1d8fc8f2fd/cache.go#L16-L22 |
16,310 | wunderlist/ttlcache | cache.go | Get | func (cache *Cache) Get(key string) (data string, found bool) {
cache.mutex.Lock()
item, exists := cache.items[key]
if !exists || item.expired() {
data = ""
found = false
} else {
item.touch(cache.ttl)
data = item.data
found = true
}
cache.mutex.Unlock()
return
} | go | func (cache *Cache) Get(key string) (data string, found bool) {
cache.mutex.Lock()
item, exists := cache.items[key]
if !exists || item.expired() {
data = ""
found = false
} else {
item.touch(cache.ttl)
data = item.data
found = true
}
cache.mutex.Unlock()
return
} | [
"func",
"(",
"cache",
"*",
"Cache",
")",
"Get",
"(",
"key",
"string",
")",
"(",
"data",
"string",
",",
"found",
"bool",
")",
"{",
"cache",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"item",
",",
"exists",
":=",
"cache",
".",
"items",
"[",
"key",
... | // Get is a thread-safe way to lookup items
// Every lookup, also touches the item, hence extending it's life | [
"Get",
"is",
"a",
"thread",
"-",
"safe",
"way",
"to",
"lookup",
"items",
"Every",
"lookup",
"also",
"touches",
"the",
"item",
"hence",
"extending",
"it",
"s",
"life"
] | 7dbceb0d509466e07d5d066ea0859f1d8fc8f2fd | https://github.com/wunderlist/ttlcache/blob/7dbceb0d509466e07d5d066ea0859f1d8fc8f2fd/cache.go#L26-L39 |
16,311 | wunderlist/ttlcache | cache.go | NewCache | func NewCache(duration time.Duration) *Cache {
cache := &Cache{
ttl: duration,
items: map[string]*Item{},
}
cache.startCleanupTimer()
return cache
} | go | func NewCache(duration time.Duration) *Cache {
cache := &Cache{
ttl: duration,
items: map[string]*Item{},
}
cache.startCleanupTimer()
return cache
} | [
"func",
"NewCache",
"(",
"duration",
"time",
".",
"Duration",
")",
"*",
"Cache",
"{",
"cache",
":=",
"&",
"Cache",
"{",
"ttl",
":",
"duration",
",",
"items",
":",
"map",
"[",
"string",
"]",
"*",
"Item",
"{",
"}",
",",
"}",
"\n",
"cache",
".",
"st... | // NewCache is a helper to create instance of the Cache struct | [
"NewCache",
"is",
"a",
"helper",
"to",
"create",
"instance",
"of",
"the",
"Cache",
"struct"
] | 7dbceb0d509466e07d5d066ea0859f1d8fc8f2fd | https://github.com/wunderlist/ttlcache/blob/7dbceb0d509466e07d5d066ea0859f1d8fc8f2fd/cache.go#L77-L84 |
16,312 | dlclark/regexp2 | syntax/code.go | OpcodeDescription | func (c *Code) OpcodeDescription(offset int) string {
buf := &bytes.Buffer{}
op := InstOp(c.Codes[offset])
fmt.Fprintf(buf, "%06d ", offset)
if opcodeBacktracks(op & Mask) {
buf.WriteString("*")
} else {
buf.WriteString(" ")
}
buf.WriteString(operatorDescription(op))
buf.WriteString("(")
op &= Mask
switch op {
case One, Notone, Onerep, Notonerep, Oneloop, Notoneloop, Onelazy, Notonelazy:
buf.WriteString("Ch = ")
buf.WriteString(CharDescription(rune(c.Codes[offset+1])))
case Set, Setrep, Setloop, Setlazy:
buf.WriteString("Set = ")
buf.WriteString(c.Sets[c.Codes[offset+1]].String())
case Multi:
fmt.Fprintf(buf, "String = %s", string(c.Strings[c.Codes[offset+1]]))
case Ref, Testref:
fmt.Fprintf(buf, "Index = %d", c.Codes[offset+1])
case Capturemark:
fmt.Fprintf(buf, "Index = %d", c.Codes[offset+1])
if c.Codes[offset+2] != -1 {
fmt.Fprintf(buf, ", Unindex = %d", c.Codes[offset+2])
}
case Nullcount, Setcount:
fmt.Fprintf(buf, "Value = %d", c.Codes[offset+1])
case Goto, Lazybranch, Branchmark, Lazybranchmark, Branchcount, Lazybranchcount:
fmt.Fprintf(buf, "Addr = %d", c.Codes[offset+1])
}
switch op {
case Onerep, Notonerep, Oneloop, Notoneloop, Onelazy, Notonelazy, Setrep, Setloop, Setlazy:
buf.WriteString(", Rep = ")
if c.Codes[offset+2] == math.MaxInt32 {
buf.WriteString("inf")
} else {
fmt.Fprintf(buf, "%d", c.Codes[offset+2])
}
case Branchcount, Lazybranchcount:
buf.WriteString(", Limit = ")
if c.Codes[offset+2] == math.MaxInt32 {
buf.WriteString("inf")
} else {
fmt.Fprintf(buf, "%d", c.Codes[offset+2])
}
}
buf.WriteString(")")
return buf.String()
} | go | func (c *Code) OpcodeDescription(offset int) string {
buf := &bytes.Buffer{}
op := InstOp(c.Codes[offset])
fmt.Fprintf(buf, "%06d ", offset)
if opcodeBacktracks(op & Mask) {
buf.WriteString("*")
} else {
buf.WriteString(" ")
}
buf.WriteString(operatorDescription(op))
buf.WriteString("(")
op &= Mask
switch op {
case One, Notone, Onerep, Notonerep, Oneloop, Notoneloop, Onelazy, Notonelazy:
buf.WriteString("Ch = ")
buf.WriteString(CharDescription(rune(c.Codes[offset+1])))
case Set, Setrep, Setloop, Setlazy:
buf.WriteString("Set = ")
buf.WriteString(c.Sets[c.Codes[offset+1]].String())
case Multi:
fmt.Fprintf(buf, "String = %s", string(c.Strings[c.Codes[offset+1]]))
case Ref, Testref:
fmt.Fprintf(buf, "Index = %d", c.Codes[offset+1])
case Capturemark:
fmt.Fprintf(buf, "Index = %d", c.Codes[offset+1])
if c.Codes[offset+2] != -1 {
fmt.Fprintf(buf, ", Unindex = %d", c.Codes[offset+2])
}
case Nullcount, Setcount:
fmt.Fprintf(buf, "Value = %d", c.Codes[offset+1])
case Goto, Lazybranch, Branchmark, Lazybranchmark, Branchcount, Lazybranchcount:
fmt.Fprintf(buf, "Addr = %d", c.Codes[offset+1])
}
switch op {
case Onerep, Notonerep, Oneloop, Notoneloop, Onelazy, Notonelazy, Setrep, Setloop, Setlazy:
buf.WriteString(", Rep = ")
if c.Codes[offset+2] == math.MaxInt32 {
buf.WriteString("inf")
} else {
fmt.Fprintf(buf, "%d", c.Codes[offset+2])
}
case Branchcount, Lazybranchcount:
buf.WriteString(", Limit = ")
if c.Codes[offset+2] == math.MaxInt32 {
buf.WriteString("inf")
} else {
fmt.Fprintf(buf, "%d", c.Codes[offset+2])
}
}
buf.WriteString(")")
return buf.String()
} | [
"func",
"(",
"c",
"*",
"Code",
")",
"OpcodeDescription",
"(",
"offset",
"int",
")",
"string",
"{",
"buf",
":=",
"&",
"bytes",
".",
"Buffer",
"{",
"}",
"\n\n",
"op",
":=",
"InstOp",
"(",
"c",
".",
"Codes",
"[",
"offset",
"]",
")",
"\n",
"fmt",
"."... | // OpcodeDescription is a humman readable string of the specific offset | [
"OpcodeDescription",
"is",
"a",
"humman",
"readable",
"string",
"of",
"the",
"specific",
"offset"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/code.go#L175-L240 |
16,313 | dlclark/regexp2 | match.go | String | func (c *Capture) String() string {
return string(c.text[c.Index : c.Index+c.Length])
} | go | func (c *Capture) String() string {
return string(c.text[c.Index : c.Index+c.Length])
} | [
"func",
"(",
"c",
"*",
"Capture",
")",
"String",
"(",
")",
"string",
"{",
"return",
"string",
"(",
"c",
".",
"text",
"[",
"c",
".",
"Index",
":",
"c",
".",
"Index",
"+",
"c",
".",
"Length",
"]",
")",
"\n",
"}"
] | // String returns the captured text as a String | [
"String",
"returns",
"the",
"captured",
"text",
"as",
"a",
"String"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/match.go#L54-L56 |
16,314 | dlclark/regexp2 | match.go | Runes | func (c *Capture) Runes() []rune {
return c.text[c.Index : c.Index+c.Length]
} | go | func (c *Capture) Runes() []rune {
return c.text[c.Index : c.Index+c.Length]
} | [
"func",
"(",
"c",
"*",
"Capture",
")",
"Runes",
"(",
")",
"[",
"]",
"rune",
"{",
"return",
"c",
".",
"text",
"[",
"c",
".",
"Index",
":",
"c",
".",
"Index",
"+",
"c",
".",
"Length",
"]",
"\n",
"}"
] | // Runes returns the captured text as a rune slice | [
"Runes",
"returns",
"the",
"captured",
"text",
"as",
"a",
"rune",
"slice"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/match.go#L59-L61 |
16,315 | dlclark/regexp2 | match.go | isMatched | func (m *Match) isMatched(cap int) bool {
return cap < len(m.matchcount) && m.matchcount[cap] > 0 && m.matches[cap][m.matchcount[cap]*2-1] != (-3+1)
} | go | func (m *Match) isMatched(cap int) bool {
return cap < len(m.matchcount) && m.matchcount[cap] > 0 && m.matches[cap][m.matchcount[cap]*2-1] != (-3+1)
} | [
"func",
"(",
"m",
"*",
"Match",
")",
"isMatched",
"(",
"cap",
"int",
")",
"bool",
"{",
"return",
"cap",
"<",
"len",
"(",
"m",
".",
"matchcount",
")",
"&&",
"m",
".",
"matchcount",
"[",
"cap",
"]",
">",
"0",
"&&",
"m",
".",
"matches",
"[",
"cap"... | // isMatched tells if a group was matched by capnum | [
"isMatched",
"tells",
"if",
"a",
"group",
"was",
"matched",
"by",
"capnum"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/match.go#L143-L145 |
16,316 | dlclark/regexp2 | match.go | matchIndex | func (m *Match) matchIndex(cap int) int {
i := m.matches[cap][m.matchcount[cap]*2-2]
if i >= 0 {
return i
}
return m.matches[cap][-3-i]
} | go | func (m *Match) matchIndex(cap int) int {
i := m.matches[cap][m.matchcount[cap]*2-2]
if i >= 0 {
return i
}
return m.matches[cap][-3-i]
} | [
"func",
"(",
"m",
"*",
"Match",
")",
"matchIndex",
"(",
"cap",
"int",
")",
"int",
"{",
"i",
":=",
"m",
".",
"matches",
"[",
"cap",
"]",
"[",
"m",
".",
"matchcount",
"[",
"cap",
"]",
"*",
"2",
"-",
"2",
"]",
"\n",
"if",
"i",
">=",
"0",
"{",
... | // matchIndex returns the index of the last specified matched group by capnum | [
"matchIndex",
"returns",
"the",
"index",
"of",
"the",
"last",
"specified",
"matched",
"group",
"by",
"capnum"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/match.go#L148-L155 |
16,317 | dlclark/regexp2 | match.go | matchLength | func (m *Match) matchLength(cap int) int {
i := m.matches[cap][m.matchcount[cap]*2-1]
if i >= 0 {
return i
}
return m.matches[cap][-3-i]
} | go | func (m *Match) matchLength(cap int) int {
i := m.matches[cap][m.matchcount[cap]*2-1]
if i >= 0 {
return i
}
return m.matches[cap][-3-i]
} | [
"func",
"(",
"m",
"*",
"Match",
")",
"matchLength",
"(",
"cap",
"int",
")",
"int",
"{",
"i",
":=",
"m",
".",
"matches",
"[",
"cap",
"]",
"[",
"m",
".",
"matchcount",
"[",
"cap",
"]",
"*",
"2",
"-",
"1",
"]",
"\n",
"if",
"i",
">=",
"0",
"{",... | // matchLength returns the length of the last specified matched group by capnum | [
"matchLength",
"returns",
"the",
"length",
"of",
"the",
"last",
"specified",
"matched",
"group",
"by",
"capnum"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/match.go#L158-L165 |
16,318 | dlclark/regexp2 | match.go | GroupByName | func (m *Match) GroupByName(name string) *Group {
num := m.regex.GroupNumberFromName(name)
if num < 0 {
return nil
}
return m.GroupByNumber(num)
} | go | func (m *Match) GroupByName(name string) *Group {
num := m.regex.GroupNumberFromName(name)
if num < 0 {
return nil
}
return m.GroupByNumber(num)
} | [
"func",
"(",
"m",
"*",
"Match",
")",
"GroupByName",
"(",
"name",
"string",
")",
"*",
"Group",
"{",
"num",
":=",
"m",
".",
"regex",
".",
"GroupNumberFromName",
"(",
"name",
")",
"\n",
"if",
"num",
"<",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"... | // GroupByName returns a group based on the name of the group, or nil if the group name does not exist | [
"GroupByName",
"returns",
"a",
"group",
"based",
"on",
"the",
"name",
"of",
"the",
"group",
"or",
"nil",
"if",
"the",
"group",
"name",
"does",
"not",
"exist"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/match.go#L229-L235 |
16,319 | dlclark/regexp2 | match.go | GroupByNumber | func (m *Match) GroupByNumber(num int) *Group {
// check our sparse map
if m.sparseCaps != nil {
if newNum, ok := m.sparseCaps[num]; ok {
num = newNum
}
}
if num >= len(m.matchcount) || num < 0 {
return nil
}
if num == 0 {
return &m.Group
}
m.populateOtherGroups()
return &m.otherGroups[num-1]
} | go | func (m *Match) GroupByNumber(num int) *Group {
// check our sparse map
if m.sparseCaps != nil {
if newNum, ok := m.sparseCaps[num]; ok {
num = newNum
}
}
if num >= len(m.matchcount) || num < 0 {
return nil
}
if num == 0 {
return &m.Group
}
m.populateOtherGroups()
return &m.otherGroups[num-1]
} | [
"func",
"(",
"m",
"*",
"Match",
")",
"GroupByNumber",
"(",
"num",
"int",
")",
"*",
"Group",
"{",
"// check our sparse map",
"if",
"m",
".",
"sparseCaps",
"!=",
"nil",
"{",
"if",
"newNum",
",",
"ok",
":=",
"m",
".",
"sparseCaps",
"[",
"num",
"]",
";",... | // GroupByNumber returns a group based on the number of the group, or nil if the group number does not exist | [
"GroupByNumber",
"returns",
"a",
"group",
"based",
"on",
"the",
"number",
"of",
"the",
"group",
"or",
"nil",
"if",
"the",
"group",
"number",
"does",
"not",
"exist"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/match.go#L238-L256 |
16,320 | dlclark/regexp2 | regexp.go | Compile | func Compile(expr string, opt RegexOptions) (*Regexp, error) {
// parse it
tree, err := syntax.Parse(expr, syntax.RegexOptions(opt))
if err != nil {
return nil, err
}
// translate it to code
code, err := syntax.Write(tree)
if err != nil {
return nil, err
}
// return it
return &Regexp{
pattern: expr,
options: opt,
caps: code.Caps,
capnames: tree.Capnames,
capslist: tree.Caplist,
capsize: code.Capsize,
code: code,
MatchTimeout: DefaultMatchTimeout,
}, nil
} | go | func Compile(expr string, opt RegexOptions) (*Regexp, error) {
// parse it
tree, err := syntax.Parse(expr, syntax.RegexOptions(opt))
if err != nil {
return nil, err
}
// translate it to code
code, err := syntax.Write(tree)
if err != nil {
return nil, err
}
// return it
return &Regexp{
pattern: expr,
options: opt,
caps: code.Caps,
capnames: tree.Capnames,
capslist: tree.Caplist,
capsize: code.Capsize,
code: code,
MatchTimeout: DefaultMatchTimeout,
}, nil
} | [
"func",
"Compile",
"(",
"expr",
"string",
",",
"opt",
"RegexOptions",
")",
"(",
"*",
"Regexp",
",",
"error",
")",
"{",
"// parse it",
"tree",
",",
"err",
":=",
"syntax",
".",
"Parse",
"(",
"expr",
",",
"syntax",
".",
"RegexOptions",
"(",
"opt",
")",
... | // Compile parses a regular expression and returns, if successful,
// a Regexp object that can be used to match against text. | [
"Compile",
"parses",
"a",
"regular",
"expression",
"and",
"returns",
"if",
"successful",
"a",
"Regexp",
"object",
"that",
"can",
"be",
"used",
"to",
"match",
"against",
"text",
"."
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/regexp.go#L48-L72 |
16,321 | dlclark/regexp2 | regexp.go | MustCompile | func MustCompile(str string, opt RegexOptions) *Regexp {
regexp, error := Compile(str, opt)
if error != nil {
panic(`regexp2: Compile(` + quote(str) + `): ` + error.Error())
}
return regexp
} | go | func MustCompile(str string, opt RegexOptions) *Regexp {
regexp, error := Compile(str, opt)
if error != nil {
panic(`regexp2: Compile(` + quote(str) + `): ` + error.Error())
}
return regexp
} | [
"func",
"MustCompile",
"(",
"str",
"string",
",",
"opt",
"RegexOptions",
")",
"*",
"Regexp",
"{",
"regexp",
",",
"error",
":=",
"Compile",
"(",
"str",
",",
"opt",
")",
"\n",
"if",
"error",
"!=",
"nil",
"{",
"panic",
"(",
"`regexp2: Compile(`",
"+",
"qu... | // MustCompile is like Compile but panics if the expression cannot be parsed.
// It simplifies safe initialization of global variables holding compiled regular
// expressions. | [
"MustCompile",
"is",
"like",
"Compile",
"but",
"panics",
"if",
"the",
"expression",
"cannot",
"be",
"parsed",
".",
"It",
"simplifies",
"safe",
"initialization",
"of",
"global",
"variables",
"holding",
"compiled",
"regular",
"expressions",
"."
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/regexp.go#L77-L83 |
16,322 | dlclark/regexp2 | regexp.go | FindStringMatch | func (re *Regexp) FindStringMatch(s string) (*Match, error) {
// convert string to runes
return re.run(false, -1, getRunes(s))
} | go | func (re *Regexp) FindStringMatch(s string) (*Match, error) {
// convert string to runes
return re.run(false, -1, getRunes(s))
} | [
"func",
"(",
"re",
"*",
"Regexp",
")",
"FindStringMatch",
"(",
"s",
"string",
")",
"(",
"*",
"Match",
",",
"error",
")",
"{",
"// convert string to runes",
"return",
"re",
".",
"run",
"(",
"false",
",",
"-",
"1",
",",
"getRunes",
"(",
"s",
")",
")",
... | // FindStringMatch searches the input string for a Regexp match | [
"FindStringMatch",
"searches",
"the",
"input",
"string",
"for",
"a",
"Regexp",
"match"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/regexp.go#L156-L159 |
16,323 | dlclark/regexp2 | regexp.go | FindRunesMatch | func (re *Regexp) FindRunesMatch(r []rune) (*Match, error) {
return re.run(false, -1, r)
} | go | func (re *Regexp) FindRunesMatch(r []rune) (*Match, error) {
return re.run(false, -1, r)
} | [
"func",
"(",
"re",
"*",
"Regexp",
")",
"FindRunesMatch",
"(",
"r",
"[",
"]",
"rune",
")",
"(",
"*",
"Match",
",",
"error",
")",
"{",
"return",
"re",
".",
"run",
"(",
"false",
",",
"-",
"1",
",",
"r",
")",
"\n",
"}"
] | // FindRunesMatch searches the input rune slice for a Regexp match | [
"FindRunesMatch",
"searches",
"the",
"input",
"rune",
"slice",
"for",
"a",
"Regexp",
"match"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/regexp.go#L162-L164 |
16,324 | dlclark/regexp2 | regexp.go | FindStringMatchStartingAt | func (re *Regexp) FindStringMatchStartingAt(s string, startAt int) (*Match, error) {
if startAt > len(s) {
return nil, errors.New("startAt must be less than the length of the input string")
}
r, startAt := re.getRunesAndStart(s, startAt)
if startAt == -1 {
// we didn't find our start index in the string -- that's a problem
return nil, errors.New("startAt must align to the start of a valid rune in the input string")
}
return re.run(false, startAt, r)
} | go | func (re *Regexp) FindStringMatchStartingAt(s string, startAt int) (*Match, error) {
if startAt > len(s) {
return nil, errors.New("startAt must be less than the length of the input string")
}
r, startAt := re.getRunesAndStart(s, startAt)
if startAt == -1 {
// we didn't find our start index in the string -- that's a problem
return nil, errors.New("startAt must align to the start of a valid rune in the input string")
}
return re.run(false, startAt, r)
} | [
"func",
"(",
"re",
"*",
"Regexp",
")",
"FindStringMatchStartingAt",
"(",
"s",
"string",
",",
"startAt",
"int",
")",
"(",
"*",
"Match",
",",
"error",
")",
"{",
"if",
"startAt",
">",
"len",
"(",
"s",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"Ne... | // FindStringMatchStartingAt searches the input string for a Regexp match starting at the startAt index | [
"FindStringMatchStartingAt",
"searches",
"the",
"input",
"string",
"for",
"a",
"Regexp",
"match",
"starting",
"at",
"the",
"startAt",
"index"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/regexp.go#L167-L178 |
16,325 | dlclark/regexp2 | regexp.go | FindRunesMatchStartingAt | func (re *Regexp) FindRunesMatchStartingAt(r []rune, startAt int) (*Match, error) {
return re.run(false, startAt, r)
} | go | func (re *Regexp) FindRunesMatchStartingAt(r []rune, startAt int) (*Match, error) {
return re.run(false, startAt, r)
} | [
"func",
"(",
"re",
"*",
"Regexp",
")",
"FindRunesMatchStartingAt",
"(",
"r",
"[",
"]",
"rune",
",",
"startAt",
"int",
")",
"(",
"*",
"Match",
",",
"error",
")",
"{",
"return",
"re",
".",
"run",
"(",
"false",
",",
"startAt",
",",
"r",
")",
"\n",
"... | // FindRunesMatchStartingAt searches the input rune slice for a Regexp match starting at the startAt index | [
"FindRunesMatchStartingAt",
"searches",
"the",
"input",
"rune",
"slice",
"for",
"a",
"Regexp",
"match",
"starting",
"at",
"the",
"startAt",
"index"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/regexp.go#L181-L183 |
16,326 | dlclark/regexp2 | regexp.go | FindNextMatch | func (re *Regexp) FindNextMatch(m *Match) (*Match, error) {
if m == nil {
return nil, nil
}
// If previous match was empty, advance by one before matching to prevent
// infinite loop
startAt := m.textpos
if m.Length == 0 {
if m.textpos == len(m.text) {
return nil, nil
}
if re.RightToLeft() {
startAt--
} else {
startAt++
}
}
return re.run(false, startAt, m.text)
} | go | func (re *Regexp) FindNextMatch(m *Match) (*Match, error) {
if m == nil {
return nil, nil
}
// If previous match was empty, advance by one before matching to prevent
// infinite loop
startAt := m.textpos
if m.Length == 0 {
if m.textpos == len(m.text) {
return nil, nil
}
if re.RightToLeft() {
startAt--
} else {
startAt++
}
}
return re.run(false, startAt, m.text)
} | [
"func",
"(",
"re",
"*",
"Regexp",
")",
"FindNextMatch",
"(",
"m",
"*",
"Match",
")",
"(",
"*",
"Match",
",",
"error",
")",
"{",
"if",
"m",
"==",
"nil",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n\n",
"// If previous match was empty, advance by one b... | // FindNextMatch returns the next match in the same input string as the match parameter.
// Will return nil if there is no next match or if given a nil match. | [
"FindNextMatch",
"returns",
"the",
"next",
"match",
"in",
"the",
"same",
"input",
"string",
"as",
"the",
"match",
"parameter",
".",
"Will",
"return",
"nil",
"if",
"there",
"is",
"no",
"next",
"match",
"or",
"if",
"given",
"a",
"nil",
"match",
"."
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/regexp.go#L187-L207 |
16,327 | dlclark/regexp2 | regexp.go | MatchString | func (re *Regexp) MatchString(s string) (bool, error) {
m, err := re.run(true, -1, getRunes(s))
if err != nil {
return false, err
}
return m != nil, nil
} | go | func (re *Regexp) MatchString(s string) (bool, error) {
m, err := re.run(true, -1, getRunes(s))
if err != nil {
return false, err
}
return m != nil, nil
} | [
"func",
"(",
"re",
"*",
"Regexp",
")",
"MatchString",
"(",
"s",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"m",
",",
"err",
":=",
"re",
".",
"run",
"(",
"true",
",",
"-",
"1",
",",
"getRunes",
"(",
"s",
")",
")",
"\n",
"if",
"err",
... | // MatchString return true if the string matches the regex
// error will be set if a timeout occurs | [
"MatchString",
"return",
"true",
"if",
"the",
"string",
"matches",
"the",
"regex",
"error",
"will",
"be",
"set",
"if",
"a",
"timeout",
"occurs"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/regexp.go#L211-L217 |
16,328 | dlclark/regexp2 | regexp.go | MatchRunes | func (re *Regexp) MatchRunes(r []rune) (bool, error) {
m, err := re.run(true, -1, r)
if err != nil {
return false, err
}
return m != nil, nil
} | go | func (re *Regexp) MatchRunes(r []rune) (bool, error) {
m, err := re.run(true, -1, r)
if err != nil {
return false, err
}
return m != nil, nil
} | [
"func",
"(",
"re",
"*",
"Regexp",
")",
"MatchRunes",
"(",
"r",
"[",
"]",
"rune",
")",
"(",
"bool",
",",
"error",
")",
"{",
"m",
",",
"err",
":=",
"re",
".",
"run",
"(",
"true",
",",
"-",
"1",
",",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
... | // MatchRunes return true if the runes matches the regex
// error will be set if a timeout occurs | [
"MatchRunes",
"return",
"true",
"if",
"the",
"runes",
"matches",
"the",
"regex",
"error",
"will",
"be",
"set",
"if",
"a",
"timeout",
"occurs"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/regexp.go#L252-L258 |
16,329 | dlclark/regexp2 | regexp.go | GetGroupNames | func (re *Regexp) GetGroupNames() []string {
var result []string
if re.capslist == nil {
result = make([]string, re.capsize)
for i := 0; i < len(result); i++ {
result[i] = strconv.Itoa(i)
}
} else {
result = make([]string, len(re.capslist))
copy(result, re.capslist)
}
return result
} | go | func (re *Regexp) GetGroupNames() []string {
var result []string
if re.capslist == nil {
result = make([]string, re.capsize)
for i := 0; i < len(result); i++ {
result[i] = strconv.Itoa(i)
}
} else {
result = make([]string, len(re.capslist))
copy(result, re.capslist)
}
return result
} | [
"func",
"(",
"re",
"*",
"Regexp",
")",
"GetGroupNames",
"(",
")",
"[",
"]",
"string",
"{",
"var",
"result",
"[",
"]",
"string",
"\n\n",
"if",
"re",
".",
"capslist",
"==",
"nil",
"{",
"result",
"=",
"make",
"(",
"[",
"]",
"string",
",",
"re",
".",... | // GetGroupNames Returns the set of strings used to name capturing groups in the expression. | [
"GetGroupNames",
"Returns",
"the",
"set",
"of",
"strings",
"used",
"to",
"name",
"capturing",
"groups",
"in",
"the",
"expression",
"."
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/regexp.go#L261-L276 |
16,330 | dlclark/regexp2 | regexp.go | GetGroupNumbers | func (re *Regexp) GetGroupNumbers() []int {
var result []int
if re.caps == nil {
result = make([]int, re.capsize)
for i := 0; i < len(result); i++ {
result[i] = i
}
} else {
result = make([]int, len(re.caps))
for k, v := range re.caps {
result[v] = k
}
}
return result
} | go | func (re *Regexp) GetGroupNumbers() []int {
var result []int
if re.caps == nil {
result = make([]int, re.capsize)
for i := 0; i < len(result); i++ {
result[i] = i
}
} else {
result = make([]int, len(re.caps))
for k, v := range re.caps {
result[v] = k
}
}
return result
} | [
"func",
"(",
"re",
"*",
"Regexp",
")",
"GetGroupNumbers",
"(",
")",
"[",
"]",
"int",
"{",
"var",
"result",
"[",
"]",
"int",
"\n\n",
"if",
"re",
".",
"caps",
"==",
"nil",
"{",
"result",
"=",
"make",
"(",
"[",
"]",
"int",
",",
"re",
".",
"capsize... | // GetGroupNumbers returns the integer group numbers corresponding to a group name. | [
"GetGroupNumbers",
"returns",
"the",
"integer",
"group",
"numbers",
"corresponding",
"to",
"a",
"group",
"name",
"."
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/regexp.go#L279-L297 |
16,331 | dlclark/regexp2 | regexp.go | GroupNameFromNumber | func (re *Regexp) GroupNameFromNumber(i int) string {
if re.capslist == nil {
if i >= 0 && i < re.capsize {
return strconv.Itoa(i)
}
return ""
}
if re.caps != nil {
var ok bool
if i, ok = re.caps[i]; !ok {
return ""
}
}
if i >= 0 && i < len(re.capslist) {
return re.capslist[i]
}
return ""
} | go | func (re *Regexp) GroupNameFromNumber(i int) string {
if re.capslist == nil {
if i >= 0 && i < re.capsize {
return strconv.Itoa(i)
}
return ""
}
if re.caps != nil {
var ok bool
if i, ok = re.caps[i]; !ok {
return ""
}
}
if i >= 0 && i < len(re.capslist) {
return re.capslist[i]
}
return ""
} | [
"func",
"(",
"re",
"*",
"Regexp",
")",
"GroupNameFromNumber",
"(",
"i",
"int",
")",
"string",
"{",
"if",
"re",
".",
"capslist",
"==",
"nil",
"{",
"if",
"i",
">=",
"0",
"&&",
"i",
"<",
"re",
".",
"capsize",
"{",
"return",
"strconv",
".",
"Itoa",
"... | // GroupNameFromNumber retrieves a group name that corresponds to a group number.
// It will return "" for and unknown group number. Unnamed groups automatically
// receive a name that is the decimal string equivalent of its number. | [
"GroupNameFromNumber",
"retrieves",
"a",
"group",
"name",
"that",
"corresponds",
"to",
"a",
"group",
"number",
".",
"It",
"will",
"return",
"for",
"and",
"unknown",
"group",
"number",
".",
"Unnamed",
"groups",
"automatically",
"receive",
"a",
"name",
"that",
"... | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/regexp.go#L302-L323 |
16,332 | dlclark/regexp2 | regexp.go | GroupNumberFromName | func (re *Regexp) GroupNumberFromName(name string) int {
// look up name if we have a hashtable of names
if re.capnames != nil {
if k, ok := re.capnames[name]; ok {
return k
}
return -1
}
// convert to an int if it looks like a number
result := 0
for i := 0; i < len(name); i++ {
ch := name[i]
if ch > '9' || ch < '0' {
return -1
}
result *= 10
result += int(ch - '0')
}
// return int if it's in range
if result >= 0 && result < re.capsize {
return result
}
return -1
} | go | func (re *Regexp) GroupNumberFromName(name string) int {
// look up name if we have a hashtable of names
if re.capnames != nil {
if k, ok := re.capnames[name]; ok {
return k
}
return -1
}
// convert to an int if it looks like a number
result := 0
for i := 0; i < len(name); i++ {
ch := name[i]
if ch > '9' || ch < '0' {
return -1
}
result *= 10
result += int(ch - '0')
}
// return int if it's in range
if result >= 0 && result < re.capsize {
return result
}
return -1
} | [
"func",
"(",
"re",
"*",
"Regexp",
")",
"GroupNumberFromName",
"(",
"name",
"string",
")",
"int",
"{",
"// look up name if we have a hashtable of names",
"if",
"re",
".",
"capnames",
"!=",
"nil",
"{",
"if",
"k",
",",
"ok",
":=",
"re",
".",
"capnames",
"[",
... | // GroupNumberFromName returns a group number that corresponds to a group name.
// Returns -1 if the name is not a recognized group name. Numbered groups
// automatically get a group name that is the decimal string equivalent of its number. | [
"GroupNumberFromName",
"returns",
"a",
"group",
"number",
"that",
"corresponds",
"to",
"a",
"group",
"name",
".",
"Returns",
"-",
"1",
"if",
"the",
"name",
"is",
"not",
"a",
"recognized",
"group",
"name",
".",
"Numbered",
"groups",
"automatically",
"get",
"a... | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/regexp.go#L328-L357 |
16,333 | dlclark/regexp2 | syntax/writer.go | codeFromTree | func (w *writer) codeFromTree(tree *RegexTree) (*Code, error) {
var (
curNode *regexNode
curChild int
capsize int
)
// construct sparse capnum mapping if some numbers are unused
if tree.capnumlist == nil || tree.captop == len(tree.capnumlist) {
capsize = tree.captop
w.caps = nil
} else {
capsize = len(tree.capnumlist)
w.caps = tree.caps
for i := 0; i < len(tree.capnumlist); i++ {
w.caps[tree.capnumlist[i]] = i
}
}
w.counting = true
for {
if !w.counting {
w.emitted = make([]int, w.count)
}
curNode = tree.root
curChild = 0
w.emit1(Lazybranch, 0)
for {
if len(curNode.children) == 0 {
w.emitFragment(curNode.t, curNode, 0)
} else if curChild < len(curNode.children) {
w.emitFragment(curNode.t|beforeChild, curNode, curChild)
curNode = curNode.children[curChild]
w.pushInt(curChild)
curChild = 0
continue
}
if w.emptyStack() {
break
}
curChild = w.popInt()
curNode = curNode.next
w.emitFragment(curNode.t|afterChild, curNode, curChild)
curChild++
}
w.patchJump(0, w.curPos())
w.emit(Stop)
if !w.counting {
break
}
w.counting = false
}
fcPrefix := getFirstCharsPrefix(tree)
prefix := getPrefix(tree)
rtl := (tree.options & RightToLeft) != 0
var bmPrefix *BmPrefix
//TODO: benchmark string prefixes
if prefix != nil && len(prefix.PrefixStr) > 0 && MaxPrefixSize > 0 {
if len(prefix.PrefixStr) > MaxPrefixSize {
// limit prefix changes to 10k
prefix.PrefixStr = prefix.PrefixStr[:MaxPrefixSize]
}
bmPrefix = newBmPrefix(prefix.PrefixStr, prefix.CaseInsensitive, rtl)
} else {
bmPrefix = nil
}
return &Code{
Codes: w.emitted,
Strings: w.stringtable,
Sets: w.settable,
TrackCount: w.trackcount,
Caps: w.caps,
Capsize: capsize,
FcPrefix: fcPrefix,
BmPrefix: bmPrefix,
Anchors: getAnchors(tree),
RightToLeft: rtl,
}, nil
} | go | func (w *writer) codeFromTree(tree *RegexTree) (*Code, error) {
var (
curNode *regexNode
curChild int
capsize int
)
// construct sparse capnum mapping if some numbers are unused
if tree.capnumlist == nil || tree.captop == len(tree.capnumlist) {
capsize = tree.captop
w.caps = nil
} else {
capsize = len(tree.capnumlist)
w.caps = tree.caps
for i := 0; i < len(tree.capnumlist); i++ {
w.caps[tree.capnumlist[i]] = i
}
}
w.counting = true
for {
if !w.counting {
w.emitted = make([]int, w.count)
}
curNode = tree.root
curChild = 0
w.emit1(Lazybranch, 0)
for {
if len(curNode.children) == 0 {
w.emitFragment(curNode.t, curNode, 0)
} else if curChild < len(curNode.children) {
w.emitFragment(curNode.t|beforeChild, curNode, curChild)
curNode = curNode.children[curChild]
w.pushInt(curChild)
curChild = 0
continue
}
if w.emptyStack() {
break
}
curChild = w.popInt()
curNode = curNode.next
w.emitFragment(curNode.t|afterChild, curNode, curChild)
curChild++
}
w.patchJump(0, w.curPos())
w.emit(Stop)
if !w.counting {
break
}
w.counting = false
}
fcPrefix := getFirstCharsPrefix(tree)
prefix := getPrefix(tree)
rtl := (tree.options & RightToLeft) != 0
var bmPrefix *BmPrefix
//TODO: benchmark string prefixes
if prefix != nil && len(prefix.PrefixStr) > 0 && MaxPrefixSize > 0 {
if len(prefix.PrefixStr) > MaxPrefixSize {
// limit prefix changes to 10k
prefix.PrefixStr = prefix.PrefixStr[:MaxPrefixSize]
}
bmPrefix = newBmPrefix(prefix.PrefixStr, prefix.CaseInsensitive, rtl)
} else {
bmPrefix = nil
}
return &Code{
Codes: w.emitted,
Strings: w.stringtable,
Sets: w.settable,
TrackCount: w.trackcount,
Caps: w.caps,
Capsize: capsize,
FcPrefix: fcPrefix,
BmPrefix: bmPrefix,
Anchors: getAnchors(tree),
RightToLeft: rtl,
}, nil
} | [
"func",
"(",
"w",
"*",
"writer",
")",
"codeFromTree",
"(",
"tree",
"*",
"RegexTree",
")",
"(",
"*",
"Code",
",",
"error",
")",
"{",
"var",
"(",
"curNode",
"*",
"regexNode",
"\n",
"curChild",
"int",
"\n",
"capsize",
"int",
"\n",
")",
"\n",
"// constru... | // The top level RegexCode generator. It does a depth-first walk
// through the tree and calls EmitFragment to emits code before
// and after each child of an interior node, and at each leaf.
//
// It runs two passes, first to count the size of the generated
// code, and second to generate the code.
//
// We should time it against the alternative, which is
// to just generate the code and grow the array as we go. | [
"The",
"top",
"level",
"RegexCode",
"generator",
".",
"It",
"does",
"a",
"depth",
"-",
"first",
"walk",
"through",
"the",
"tree",
"and",
"calls",
"EmitFragment",
"to",
"emits",
"code",
"before",
"and",
"after",
"each",
"child",
"of",
"an",
"interior",
"nod... | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/writer.go#L59-L152 |
16,334 | dlclark/regexp2 | syntax/writer.go | patchJump | func (w *writer) patchJump(offset, jumpDest int) {
w.emitted[offset+1] = jumpDest
} | go | func (w *writer) patchJump(offset, jumpDest int) {
w.emitted[offset+1] = jumpDest
} | [
"func",
"(",
"w",
"*",
"writer",
")",
"patchJump",
"(",
"offset",
",",
"jumpDest",
"int",
")",
"{",
"w",
".",
"emitted",
"[",
"offset",
"+",
"1",
"]",
"=",
"jumpDest",
"\n",
"}"
] | // Fixes up a jump instruction at the specified offset
// so that it jumps to the specified jumpDest. | [
"Fixes",
"up",
"a",
"jump",
"instruction",
"at",
"the",
"specified",
"offset",
"so",
"that",
"it",
"jumps",
"to",
"the",
"specified",
"jumpDest",
"."
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/writer.go#L397-L399 |
16,335 | dlclark/regexp2 | syntax/writer.go | setCode | func (w *writer) setCode(set *CharSet) int {
if w.counting {
return 0
}
buf := &bytes.Buffer{}
set.mapHashFill(buf)
hash := buf.String()
i, ok := w.sethash[hash]
if !ok {
i = len(w.sethash)
w.sethash[hash] = i
w.settable = append(w.settable, set)
}
return i
} | go | func (w *writer) setCode(set *CharSet) int {
if w.counting {
return 0
}
buf := &bytes.Buffer{}
set.mapHashFill(buf)
hash := buf.String()
i, ok := w.sethash[hash]
if !ok {
i = len(w.sethash)
w.sethash[hash] = i
w.settable = append(w.settable, set)
}
return i
} | [
"func",
"(",
"w",
"*",
"writer",
")",
"setCode",
"(",
"set",
"*",
"CharSet",
")",
"int",
"{",
"if",
"w",
".",
"counting",
"{",
"return",
"0",
"\n",
"}",
"\n\n",
"buf",
":=",
"&",
"bytes",
".",
"Buffer",
"{",
"}",
"\n\n",
"set",
".",
"mapHashFill"... | // Returns an index in the set table for a charset
// uses a map to eliminate duplicates. | [
"Returns",
"an",
"index",
"in",
"the",
"set",
"table",
"for",
"a",
"charset",
"uses",
"a",
"map",
"to",
"eliminate",
"duplicates",
"."
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/writer.go#L403-L419 |
16,336 | dlclark/regexp2 | syntax/writer.go | stringCode | func (w *writer) stringCode(str []rune) int {
if w.counting {
return 0
}
hash := string(str)
i, ok := w.stringhash[hash]
if !ok {
i = len(w.stringhash)
w.stringhash[hash] = i
w.stringtable = append(w.stringtable, str)
}
return i
} | go | func (w *writer) stringCode(str []rune) int {
if w.counting {
return 0
}
hash := string(str)
i, ok := w.stringhash[hash]
if !ok {
i = len(w.stringhash)
w.stringhash[hash] = i
w.stringtable = append(w.stringtable, str)
}
return i
} | [
"func",
"(",
"w",
"*",
"writer",
")",
"stringCode",
"(",
"str",
"[",
"]",
"rune",
")",
"int",
"{",
"if",
"w",
".",
"counting",
"{",
"return",
"0",
"\n",
"}",
"\n\n",
"hash",
":=",
"string",
"(",
"str",
")",
"\n",
"i",
",",
"ok",
":=",
"w",
".... | // Returns an index in the string table for a string.
// uses a map to eliminate duplicates. | [
"Returns",
"an",
"index",
"in",
"the",
"string",
"table",
"for",
"a",
"string",
".",
"uses",
"a",
"map",
"to",
"eliminate",
"duplicates",
"."
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/writer.go#L423-L437 |
16,337 | dlclark/regexp2 | syntax/writer.go | mapCapnum | func (w *writer) mapCapnum(capnum int) int {
if capnum == -1 {
return -1
}
if w.caps != nil {
return w.caps[capnum]
}
return capnum
} | go | func (w *writer) mapCapnum(capnum int) int {
if capnum == -1 {
return -1
}
if w.caps != nil {
return w.caps[capnum]
}
return capnum
} | [
"func",
"(",
"w",
"*",
"writer",
")",
"mapCapnum",
"(",
"capnum",
"int",
")",
"int",
"{",
"if",
"capnum",
"==",
"-",
"1",
"{",
"return",
"-",
"1",
"\n",
"}",
"\n\n",
"if",
"w",
".",
"caps",
"!=",
"nil",
"{",
"return",
"w",
".",
"caps",
"[",
"... | // When generating code on a regex that uses a sparse set
// of capture slots, we hash them to a dense set of indices
// for an array of capture slots. Instead of doing the hash
// at match time, it's done at compile time, here. | [
"When",
"generating",
"code",
"on",
"a",
"regex",
"that",
"uses",
"a",
"sparse",
"set",
"of",
"capture",
"slots",
"we",
"hash",
"them",
"to",
"a",
"dense",
"set",
"of",
"indices",
"for",
"an",
"array",
"of",
"capture",
"slots",
".",
"Instead",
"of",
"d... | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/writer.go#L443-L453 |
16,338 | dlclark/regexp2 | syntax/writer.go | emit1 | func (w *writer) emit1(op InstOp, opd1 int) {
if w.counting {
w.count += 2
if opcodeBacktracks(op) {
w.trackcount++
}
return
}
w.emitted[w.curpos] = int(op)
w.curpos++
w.emitted[w.curpos] = opd1
w.curpos++
} | go | func (w *writer) emit1(op InstOp, opd1 int) {
if w.counting {
w.count += 2
if opcodeBacktracks(op) {
w.trackcount++
}
return
}
w.emitted[w.curpos] = int(op)
w.curpos++
w.emitted[w.curpos] = opd1
w.curpos++
} | [
"func",
"(",
"w",
"*",
"writer",
")",
"emit1",
"(",
"op",
"InstOp",
",",
"opd1",
"int",
")",
"{",
"if",
"w",
".",
"counting",
"{",
"w",
".",
"count",
"+=",
"2",
"\n",
"if",
"opcodeBacktracks",
"(",
"op",
")",
"{",
"w",
".",
"trackcount",
"++",
... | // Emits a one-argument operation. | [
"Emits",
"a",
"one",
"-",
"argument",
"operation",
"."
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/writer.go#L471-L483 |
16,339 | dlclark/regexp2 | runner.go | ensureStorage | func (r *runner) ensureStorage() {
if r.runstackpos < r.runtrackcount*4 {
doubleIntSlice(&r.runstack, &r.runstackpos)
}
if r.runtrackpos < r.runtrackcount*4 {
doubleIntSlice(&r.runtrack, &r.runtrackpos)
}
} | go | func (r *runner) ensureStorage() {
if r.runstackpos < r.runtrackcount*4 {
doubleIntSlice(&r.runstack, &r.runstackpos)
}
if r.runtrackpos < r.runtrackcount*4 {
doubleIntSlice(&r.runtrack, &r.runtrackpos)
}
} | [
"func",
"(",
"r",
"*",
"runner",
")",
"ensureStorage",
"(",
")",
"{",
"if",
"r",
".",
"runstackpos",
"<",
"r",
".",
"runtrackcount",
"*",
"4",
"{",
"doubleIntSlice",
"(",
"&",
"r",
".",
"runstack",
",",
"&",
"r",
".",
"runstackpos",
")",
"\n",
"}",... | // increase the size of stack and track storage | [
"increase",
"the",
"size",
"of",
"stack",
"and",
"track",
"storage"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/runner.go#L896-L903 |
16,340 | dlclark/regexp2 | runner.go | crawl | func (r *runner) crawl(i int) {
if r.runcrawlpos == 0 {
doubleIntSlice(&r.runcrawl, &r.runcrawlpos)
}
r.runcrawlpos--
r.runcrawl[r.runcrawlpos] = i
} | go | func (r *runner) crawl(i int) {
if r.runcrawlpos == 0 {
doubleIntSlice(&r.runcrawl, &r.runcrawlpos)
}
r.runcrawlpos--
r.runcrawl[r.runcrawlpos] = i
} | [
"func",
"(",
"r",
"*",
"runner",
")",
"crawl",
"(",
"i",
"int",
")",
"{",
"if",
"r",
".",
"runcrawlpos",
"==",
"0",
"{",
"doubleIntSlice",
"(",
"&",
"r",
".",
"runcrawl",
",",
"&",
"r",
".",
"runcrawlpos",
")",
"\n",
"}",
"\n",
"r",
".",
"runcr... | // Save a number on the longjump unrolling stack | [
"Save",
"a",
"number",
"on",
"the",
"longjump",
"unrolling",
"stack"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/runner.go#L915-L921 |
16,341 | dlclark/regexp2 | runner.go | popcrawl | func (r *runner) popcrawl() int {
val := r.runcrawl[r.runcrawlpos]
r.runcrawlpos++
return val
} | go | func (r *runner) popcrawl() int {
val := r.runcrawl[r.runcrawlpos]
r.runcrawlpos++
return val
} | [
"func",
"(",
"r",
"*",
"runner",
")",
"popcrawl",
"(",
")",
"int",
"{",
"val",
":=",
"r",
".",
"runcrawl",
"[",
"r",
".",
"runcrawlpos",
"]",
"\n",
"r",
".",
"runcrawlpos",
"++",
"\n",
"return",
"val",
"\n",
"}"
] | // Remove a number from the longjump unrolling stack | [
"Remove",
"a",
"number",
"from",
"the",
"longjump",
"unrolling",
"stack"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/runner.go#L924-L928 |
16,342 | dlclark/regexp2 | runner.go | trackPeekN | func (r *runner) trackPeekN(i int) int {
return r.runtrack[r.runtrackpos-i-1]
} | go | func (r *runner) trackPeekN(i int) int {
return r.runtrack[r.runtrackpos-i-1]
} | [
"func",
"(",
"r",
"*",
"runner",
")",
"trackPeekN",
"(",
"i",
"int",
")",
"int",
"{",
"return",
"r",
".",
"runtrack",
"[",
"r",
".",
"runtrackpos",
"-",
"i",
"-",
"1",
"]",
"\n",
"}"
] | // get the ith element down on the backtracking stack | [
"get",
"the",
"ith",
"element",
"down",
"on",
"the",
"backtracking",
"stack"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/runner.go#L1070-L1072 |
16,343 | dlclark/regexp2 | runner.go | stackPush | func (r *runner) stackPush(I1 int) {
r.runstackpos--
r.runstack[r.runstackpos] = I1
} | go | func (r *runner) stackPush(I1 int) {
r.runstackpos--
r.runstack[r.runstackpos] = I1
} | [
"func",
"(",
"r",
"*",
"runner",
")",
"stackPush",
"(",
"I1",
"int",
")",
"{",
"r",
".",
"runstackpos",
"--",
"\n",
"r",
".",
"runstack",
"[",
"r",
".",
"runstackpos",
"]",
"=",
"I1",
"\n",
"}"
] | // Push onto the grouping stack | [
"Push",
"onto",
"the",
"grouping",
"stack"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/runner.go#L1075-L1078 |
16,344 | dlclark/regexp2 | runner.go | stackPeekN | func (r *runner) stackPeekN(i int) int {
return r.runstack[r.runstackpos-i-1]
} | go | func (r *runner) stackPeekN(i int) int {
return r.runstack[r.runstackpos-i-1]
} | [
"func",
"(",
"r",
"*",
"runner",
")",
"stackPeekN",
"(",
"i",
"int",
")",
"int",
"{",
"return",
"r",
".",
"runstack",
"[",
"r",
".",
"runstackpos",
"-",
"i",
"-",
"1",
"]",
"\n",
"}"
] | // get the ith element down on the grouping stack | [
"get",
"the",
"ith",
"element",
"down",
"on",
"the",
"grouping",
"stack"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/runner.go#L1105-L1107 |
16,345 | dlclark/regexp2 | runner.go | uncapture | func (r *runner) uncapture() {
capnum := r.popcrawl()
r.runmatch.removeMatch(capnum)
} | go | func (r *runner) uncapture() {
capnum := r.popcrawl()
r.runmatch.removeMatch(capnum)
} | [
"func",
"(",
"r",
"*",
"runner",
")",
"uncapture",
"(",
")",
"{",
"capnum",
":=",
"r",
".",
"popcrawl",
"(",
")",
"\n",
"r",
".",
"runmatch",
".",
"removeMatch",
"(",
"capnum",
")",
"\n",
"}"
] | // revert the last capture | [
"revert",
"the",
"last",
"capture"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/runner.go#L1453-L1456 |
16,346 | dlclark/regexp2 | runner.go | isBoundary | func (r *runner) isBoundary(index, startpos, endpos int) bool {
return (index > startpos && syntax.IsWordChar(r.runtext[index-1])) !=
(index < endpos && syntax.IsWordChar(r.runtext[index]))
} | go | func (r *runner) isBoundary(index, startpos, endpos int) bool {
return (index > startpos && syntax.IsWordChar(r.runtext[index-1])) !=
(index < endpos && syntax.IsWordChar(r.runtext[index]))
} | [
"func",
"(",
"r",
"*",
"runner",
")",
"isBoundary",
"(",
"index",
",",
"startpos",
",",
"endpos",
"int",
")",
"bool",
"{",
"return",
"(",
"index",
">",
"startpos",
"&&",
"syntax",
".",
"IsWordChar",
"(",
"r",
".",
"runtext",
"[",
"index",
"-",
"1",
... | // decide whether the pos
// at the specified index is a boundary or not. It's just not worth
// emitting inline code for this logic. | [
"decide",
"whether",
"the",
"pos",
"at",
"the",
"specified",
"index",
"is",
"a",
"boundary",
"or",
"not",
".",
"It",
"s",
"just",
"not",
"worth",
"emitting",
"inline",
"code",
"for",
"this",
"logic",
"."
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/runner.go#L1531-L1534 |
16,347 | dlclark/regexp2 | runner.go | getRunner | func (re *Regexp) getRunner() *runner {
re.muRun.Lock()
if n := len(re.runner); n > 0 {
z := re.runner[n-1]
re.runner = re.runner[:n-1]
re.muRun.Unlock()
return z
}
re.muRun.Unlock()
z := &runner{
re: re,
code: re.code,
}
return z
} | go | func (re *Regexp) getRunner() *runner {
re.muRun.Lock()
if n := len(re.runner); n > 0 {
z := re.runner[n-1]
re.runner = re.runner[:n-1]
re.muRun.Unlock()
return z
}
re.muRun.Unlock()
z := &runner{
re: re,
code: re.code,
}
return z
} | [
"func",
"(",
"re",
"*",
"Regexp",
")",
"getRunner",
"(",
")",
"*",
"runner",
"{",
"re",
".",
"muRun",
".",
"Lock",
"(",
")",
"\n",
"if",
"n",
":=",
"len",
"(",
"re",
".",
"runner",
")",
";",
"n",
">",
"0",
"{",
"z",
":=",
"re",
".",
"runner... | // getRunner returns a run to use for matching re.
// It uses the re's runner cache if possible, to avoid
// unnecessary allocation. | [
"getRunner",
"returns",
"a",
"run",
"to",
"use",
"for",
"matching",
"re",
".",
"It",
"uses",
"the",
"re",
"s",
"runner",
"cache",
"if",
"possible",
"to",
"avoid",
"unnecessary",
"allocation",
"."
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/runner.go#L1597-L1611 |
16,348 | dlclark/regexp2 | syntax/charclass.go | Copy | func (c CharSet) Copy() CharSet {
ret := CharSet{
anything: c.anything,
negate: c.negate,
}
ret.ranges = append(ret.ranges, c.ranges...)
ret.categories = append(ret.categories, c.categories...)
if c.sub != nil {
sub := c.sub.Copy()
ret.sub = &sub
}
return ret
} | go | func (c CharSet) Copy() CharSet {
ret := CharSet{
anything: c.anything,
negate: c.negate,
}
ret.ranges = append(ret.ranges, c.ranges...)
ret.categories = append(ret.categories, c.categories...)
if c.sub != nil {
sub := c.sub.Copy()
ret.sub = &sub
}
return ret
} | [
"func",
"(",
"c",
"CharSet",
")",
"Copy",
"(",
")",
"CharSet",
"{",
"ret",
":=",
"CharSet",
"{",
"anything",
":",
"c",
".",
"anything",
",",
"negate",
":",
"c",
".",
"negate",
",",
"}",
"\n\n",
"ret",
".",
"ranges",
"=",
"append",
"(",
"ret",
"."... | // Copy makes a deep copy to prevent accidental mutation of a set | [
"Copy",
"makes",
"a",
"deep",
"copy",
"to",
"prevent",
"accidental",
"mutation",
"of",
"a",
"set"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/charclass.go#L144-L159 |
16,349 | dlclark/regexp2 | syntax/charclass.go | String | func (c CharSet) String() string {
buf := &bytes.Buffer{}
buf.WriteRune('[')
if c.IsNegated() {
buf.WriteRune('^')
}
for _, r := range c.ranges {
buf.WriteString(CharDescription(r.first))
if r.first != r.last {
if r.last-r.first != 1 {
//groups that are 1 char apart skip the dash
buf.WriteRune('-')
}
buf.WriteString(CharDescription(r.last))
}
}
for _, c := range c.categories {
buf.WriteString(c.String())
}
if c.sub != nil {
buf.WriteRune('-')
buf.WriteString(c.sub.String())
}
buf.WriteRune(']')
return buf.String()
} | go | func (c CharSet) String() string {
buf := &bytes.Buffer{}
buf.WriteRune('[')
if c.IsNegated() {
buf.WriteRune('^')
}
for _, r := range c.ranges {
buf.WriteString(CharDescription(r.first))
if r.first != r.last {
if r.last-r.first != 1 {
//groups that are 1 char apart skip the dash
buf.WriteRune('-')
}
buf.WriteString(CharDescription(r.last))
}
}
for _, c := range c.categories {
buf.WriteString(c.String())
}
if c.sub != nil {
buf.WriteRune('-')
buf.WriteString(c.sub.String())
}
buf.WriteRune(']')
return buf.String()
} | [
"func",
"(",
"c",
"CharSet",
")",
"String",
"(",
")",
"string",
"{",
"buf",
":=",
"&",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"buf",
".",
"WriteRune",
"(",
"'['",
")",
"\n\n",
"if",
"c",
".",
"IsNegated",
"(",
")",
"{",
"buf",
".",
"WriteRune",
... | // gets a human-readable description for a set string | [
"gets",
"a",
"human",
"-",
"readable",
"description",
"for",
"a",
"set",
"string"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/charclass.go#L162-L194 |
16,350 | dlclark/regexp2 | syntax/charclass.go | mapHashFill | func (c CharSet) mapHashFill(buf *bytes.Buffer) {
if c.negate {
buf.WriteByte(0)
} else {
buf.WriteByte(1)
}
binary.Write(buf, binary.LittleEndian, len(c.ranges))
binary.Write(buf, binary.LittleEndian, len(c.categories))
for _, r := range c.ranges {
buf.WriteRune(r.first)
buf.WriteRune(r.last)
}
for _, ct := range c.categories {
buf.WriteString(ct.cat)
if ct.negate {
buf.WriteByte(1)
} else {
buf.WriteByte(0)
}
}
if c.sub != nil {
c.sub.mapHashFill(buf)
}
} | go | func (c CharSet) mapHashFill(buf *bytes.Buffer) {
if c.negate {
buf.WriteByte(0)
} else {
buf.WriteByte(1)
}
binary.Write(buf, binary.LittleEndian, len(c.ranges))
binary.Write(buf, binary.LittleEndian, len(c.categories))
for _, r := range c.ranges {
buf.WriteRune(r.first)
buf.WriteRune(r.last)
}
for _, ct := range c.categories {
buf.WriteString(ct.cat)
if ct.negate {
buf.WriteByte(1)
} else {
buf.WriteByte(0)
}
}
if c.sub != nil {
c.sub.mapHashFill(buf)
}
} | [
"func",
"(",
"c",
"CharSet",
")",
"mapHashFill",
"(",
"buf",
"*",
"bytes",
".",
"Buffer",
")",
"{",
"if",
"c",
".",
"negate",
"{",
"buf",
".",
"WriteByte",
"(",
"0",
")",
"\n",
"}",
"else",
"{",
"buf",
".",
"WriteByte",
"(",
"1",
")",
"\n",
"}"... | // mapHashFill converts a charset into a buffer for use in maps | [
"mapHashFill",
"converts",
"a",
"charset",
"into",
"a",
"buffer",
"for",
"use",
"in",
"maps"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/charclass.go#L197-L222 |
16,351 | dlclark/regexp2 | syntax/charclass.go | CharDescription | func CharDescription(ch rune) string {
/*if ch == '\\' {
return "\\\\"
}
if ch > ' ' && ch <= '~' {
return string(ch)
} else if ch == '\n' {
return "\\n"
} else if ch == ' ' {
return "\\ "
}*/
b := &bytes.Buffer{}
escape(b, ch, false) //fmt.Sprintf("%U", ch)
return b.String()
} | go | func CharDescription(ch rune) string {
/*if ch == '\\' {
return "\\\\"
}
if ch > ' ' && ch <= '~' {
return string(ch)
} else if ch == '\n' {
return "\\n"
} else if ch == ' ' {
return "\\ "
}*/
b := &bytes.Buffer{}
escape(b, ch, false) //fmt.Sprintf("%U", ch)
return b.String()
} | [
"func",
"CharDescription",
"(",
"ch",
"rune",
")",
"string",
"{",
"/*if ch == '\\\\' {\n\t\treturn \"\\\\\\\\\"\n\t}\n\n\tif ch > ' ' && ch <= '~' {\n\t\treturn string(ch)\n\t} else if ch == '\\n' {\n\t\treturn \"\\\\n\"\n\t} else if ch == ' ' {\n\t\treturn \"\\\\ \"\n\t}*/",
"b",
":=",
"&",
... | // CharDescription Produces a human-readable description for a single character. | [
"CharDescription",
"Produces",
"a",
"human",
"-",
"readable",
"description",
"for",
"a",
"single",
"character",
"."
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/charclass.go#L314-L330 |
16,352 | dlclark/regexp2 | syntax/charclass.go | addRanges | func (c *CharSet) addRanges(ranges []singleRange) {
if c.anything {
return
}
c.ranges = append(c.ranges, ranges...)
c.canonicalize()
} | go | func (c *CharSet) addRanges(ranges []singleRange) {
if c.anything {
return
}
c.ranges = append(c.ranges, ranges...)
c.canonicalize()
} | [
"func",
"(",
"c",
"*",
"CharSet",
")",
"addRanges",
"(",
"ranges",
"[",
"]",
"singleRange",
")",
"{",
"if",
"c",
".",
"anything",
"{",
"return",
"\n",
"}",
"\n",
"c",
".",
"ranges",
"=",
"append",
"(",
"c",
".",
"ranges",
",",
"ranges",
"...",
")... | // Merges new ranges to our own | [
"Merges",
"new",
"ranges",
"to",
"our",
"own"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/charclass.go#L479-L485 |
16,353 | dlclark/regexp2 | syntax/charclass.go | canonicalize | func (c *CharSet) canonicalize() {
var i, j int
var last rune
//
// Find and eliminate overlapping or abutting ranges
//
if len(c.ranges) > 1 {
sort.Sort(singleRangeSorter(c.ranges))
done := false
for i, j = 1, 0; ; i++ {
for last = c.ranges[j].last; ; i++ {
if i == len(c.ranges) || last == utf8.MaxRune {
done = true
break
}
CurrentRange := c.ranges[i]
if CurrentRange.first > last+1 {
break
}
if last < CurrentRange.last {
last = CurrentRange.last
}
}
c.ranges[j] = singleRange{first: c.ranges[j].first, last: last}
j++
if done {
break
}
if j < i {
c.ranges[j] = c.ranges[i]
}
}
c.ranges = append(c.ranges[:j], c.ranges[len(c.ranges):]...)
}
} | go | func (c *CharSet) canonicalize() {
var i, j int
var last rune
//
// Find and eliminate overlapping or abutting ranges
//
if len(c.ranges) > 1 {
sort.Sort(singleRangeSorter(c.ranges))
done := false
for i, j = 1, 0; ; i++ {
for last = c.ranges[j].last; ; i++ {
if i == len(c.ranges) || last == utf8.MaxRune {
done = true
break
}
CurrentRange := c.ranges[i]
if CurrentRange.first > last+1 {
break
}
if last < CurrentRange.last {
last = CurrentRange.last
}
}
c.ranges[j] = singleRange{first: c.ranges[j].first, last: last}
j++
if done {
break
}
if j < i {
c.ranges[j] = c.ranges[i]
}
}
c.ranges = append(c.ranges[:j], c.ranges[len(c.ranges):]...)
}
} | [
"func",
"(",
"c",
"*",
"CharSet",
")",
"canonicalize",
"(",
")",
"{",
"var",
"i",
",",
"j",
"int",
"\n",
"var",
"last",
"rune",
"\n\n",
"//",
"// Find and eliminate overlapping or abutting ranges",
"//",
"if",
"len",
"(",
"c",
".",
"ranges",
")",
">",
"1... | // Logic to reduce a character class to a unique, sorted form. | [
"Logic",
"to",
"reduce",
"a",
"character",
"class",
"to",
"a",
"unique",
"sorted",
"form",
"."
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/charclass.go#L525-L570 |
16,354 | dlclark/regexp2 | syntax/charclass.go | addLowercase | func (c *CharSet) addLowercase() {
if c.anything {
return
}
toAdd := []singleRange{}
for i := 0; i < len(c.ranges); i++ {
r := c.ranges[i]
if r.first == r.last {
lower := unicode.ToLower(r.first)
c.ranges[i] = singleRange{first: lower, last: lower}
} else {
toAdd = append(toAdd, r)
}
}
for _, r := range toAdd {
c.addLowercaseRange(r.first, r.last)
}
c.canonicalize()
} | go | func (c *CharSet) addLowercase() {
if c.anything {
return
}
toAdd := []singleRange{}
for i := 0; i < len(c.ranges); i++ {
r := c.ranges[i]
if r.first == r.last {
lower := unicode.ToLower(r.first)
c.ranges[i] = singleRange{first: lower, last: lower}
} else {
toAdd = append(toAdd, r)
}
}
for _, r := range toAdd {
c.addLowercaseRange(r.first, r.last)
}
c.canonicalize()
} | [
"func",
"(",
"c",
"*",
"CharSet",
")",
"addLowercase",
"(",
")",
"{",
"if",
"c",
".",
"anything",
"{",
"return",
"\n",
"}",
"\n",
"toAdd",
":=",
"[",
"]",
"singleRange",
"{",
"}",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"c",
"... | // Adds to the class any lowercase versions of characters already
// in the class. Used for case-insensitivity. | [
"Adds",
"to",
"the",
"class",
"any",
"lowercase",
"versions",
"of",
"characters",
"already",
"in",
"the",
"class",
".",
"Used",
"for",
"case",
"-",
"insensitivity",
"."
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/charclass.go#L574-L593 |
16,355 | dlclark/regexp2 | syntax/parser.go | Parse | func Parse(re string, op RegexOptions) (*RegexTree, error) {
p := parser{
options: op,
caps: make(map[int]int),
}
p.setPattern(re)
if err := p.countCaptures(); err != nil {
return nil, err
}
p.reset(op)
root, err := p.scanRegex()
if err != nil {
return nil, err
}
tree := &RegexTree{
root: root,
caps: p.caps,
capnumlist: p.capnumlist,
captop: p.captop,
Capnames: p.capnames,
Caplist: p.capnamelist,
options: op,
}
if tree.options&Debug > 0 {
os.Stdout.WriteString(tree.Dump())
}
return tree, nil
} | go | func Parse(re string, op RegexOptions) (*RegexTree, error) {
p := parser{
options: op,
caps: make(map[int]int),
}
p.setPattern(re)
if err := p.countCaptures(); err != nil {
return nil, err
}
p.reset(op)
root, err := p.scanRegex()
if err != nil {
return nil, err
}
tree := &RegexTree{
root: root,
caps: p.caps,
capnumlist: p.capnumlist,
captop: p.captop,
Capnames: p.capnames,
Caplist: p.capnamelist,
options: op,
}
if tree.options&Debug > 0 {
os.Stdout.WriteString(tree.Dump())
}
return tree, nil
} | [
"func",
"Parse",
"(",
"re",
"string",
",",
"op",
"RegexOptions",
")",
"(",
"*",
"RegexTree",
",",
"error",
")",
"{",
"p",
":=",
"parser",
"{",
"options",
":",
"op",
",",
"caps",
":",
"make",
"(",
"map",
"[",
"int",
"]",
"int",
")",
",",
"}",
"\... | // Parse converts a regex string into a parse tree | [
"Parse",
"converts",
"a",
"regex",
"string",
"into",
"a",
"parse",
"tree"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/parser.go#L148-L180 |
16,356 | dlclark/regexp2 | syntax/parser.go | countCaptures | func (p *parser) countCaptures() error {
var ch rune
p.noteCaptureSlot(0, 0)
p.autocap = 1
for p.charsRight() > 0 {
pos := p.textpos()
ch = p.moveRightGetChar()
switch ch {
case '\\':
if p.charsRight() > 0 {
p.moveRight(1)
}
case '#':
if p.useOptionX() {
p.moveLeft()
p.scanBlank()
}
case '[':
p.scanCharSet(false, true)
case ')':
if !p.emptyOptionsStack() {
p.popOptions()
}
case '(':
if p.charsRight() >= 2 && p.rightChar(1) == '#' && p.rightChar(0) == '?' {
p.moveLeft()
p.scanBlank()
} else {
p.pushOptions()
if p.charsRight() > 0 && p.rightChar(0) == '?' {
// we have (?...
p.moveRight(1)
if p.charsRight() > 1 && (p.rightChar(0) == '<' || p.rightChar(0) == '\'') {
// named group: (?<... or (?'...
p.moveRight(1)
ch = p.rightChar(0)
if ch != '0' && IsWordChar(ch) {
if ch >= '1' && ch <= '9' {
dec, err := p.scanDecimal()
if err != nil {
return err
}
p.noteCaptureSlot(dec, pos)
} else {
p.noteCaptureName(p.scanCapname(), pos)
}
}
} else {
// (?...
// get the options if it's an option construct (?cimsx-cimsx...)
p.scanOptions()
if p.charsRight() > 0 {
if p.rightChar(0) == ')' {
// (?cimsx-cimsx)
p.moveRight(1)
p.popKeepOptions()
} else if p.rightChar(0) == '(' {
// alternation construct: (?(foo)yes|no)
// ignore the next paren so we don't capture the condition
p.ignoreNextParen = true
// break from here so we don't reset ignoreNextParen
continue
}
}
}
} else {
if !p.useOptionN() && !p.ignoreNextParen {
p.noteCaptureSlot(p.consumeAutocap(), pos)
}
}
}
p.ignoreNextParen = false
}
}
p.assignNameSlots()
return nil
} | go | func (p *parser) countCaptures() error {
var ch rune
p.noteCaptureSlot(0, 0)
p.autocap = 1
for p.charsRight() > 0 {
pos := p.textpos()
ch = p.moveRightGetChar()
switch ch {
case '\\':
if p.charsRight() > 0 {
p.moveRight(1)
}
case '#':
if p.useOptionX() {
p.moveLeft()
p.scanBlank()
}
case '[':
p.scanCharSet(false, true)
case ')':
if !p.emptyOptionsStack() {
p.popOptions()
}
case '(':
if p.charsRight() >= 2 && p.rightChar(1) == '#' && p.rightChar(0) == '?' {
p.moveLeft()
p.scanBlank()
} else {
p.pushOptions()
if p.charsRight() > 0 && p.rightChar(0) == '?' {
// we have (?...
p.moveRight(1)
if p.charsRight() > 1 && (p.rightChar(0) == '<' || p.rightChar(0) == '\'') {
// named group: (?<... or (?'...
p.moveRight(1)
ch = p.rightChar(0)
if ch != '0' && IsWordChar(ch) {
if ch >= '1' && ch <= '9' {
dec, err := p.scanDecimal()
if err != nil {
return err
}
p.noteCaptureSlot(dec, pos)
} else {
p.noteCaptureName(p.scanCapname(), pos)
}
}
} else {
// (?...
// get the options if it's an option construct (?cimsx-cimsx...)
p.scanOptions()
if p.charsRight() > 0 {
if p.rightChar(0) == ')' {
// (?cimsx-cimsx)
p.moveRight(1)
p.popKeepOptions()
} else if p.rightChar(0) == '(' {
// alternation construct: (?(foo)yes|no)
// ignore the next paren so we don't capture the condition
p.ignoreNextParen = true
// break from here so we don't reset ignoreNextParen
continue
}
}
}
} else {
if !p.useOptionN() && !p.ignoreNextParen {
p.noteCaptureSlot(p.consumeAutocap(), pos)
}
}
}
p.ignoreNextParen = false
}
}
p.assignNameSlots()
return nil
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"countCaptures",
"(",
")",
"error",
"{",
"var",
"ch",
"rune",
"\n\n",
"p",
".",
"noteCaptureSlot",
"(",
"0",
",",
"0",
")",
"\n\n",
"p",
".",
"autocap",
"=",
"1",
"\n\n",
"for",
"p",
".",
"charsRight",
"(",
"... | // CountCaptures is a prescanner for deducing the slots used for
// captures by doing a partial tokenization of the pattern. | [
"CountCaptures",
"is",
"a",
"prescanner",
"for",
"deducing",
"the",
"slots",
"used",
"for",
"captures",
"by",
"doing",
"a",
"partial",
"tokenization",
"of",
"the",
"pattern",
"."
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/parser.go#L300-L392 |
16,357 | dlclark/regexp2 | syntax/parser.go | scanBackslash | func (p *parser) scanBackslash() (*regexNode, error) {
if p.charsRight() == 0 {
return nil, p.getErr(ErrIllegalEndEscape)
}
switch ch := p.rightChar(0); ch {
case 'b', 'B', 'A', 'G', 'Z', 'z':
p.moveRight(1)
return newRegexNode(p.typeFromCode(ch), p.options), nil
case 'w':
p.moveRight(1)
if p.useOptionE() {
return newRegexNodeSet(ntSet, p.options, ECMAWordClass()), nil
}
return newRegexNodeSet(ntSet, p.options, WordClass()), nil
case 'W':
p.moveRight(1)
if p.useOptionE() {
return newRegexNodeSet(ntSet, p.options, NotECMAWordClass()), nil
}
return newRegexNodeSet(ntSet, p.options, NotWordClass()), nil
case 's':
p.moveRight(1)
if p.useOptionE() {
return newRegexNodeSet(ntSet, p.options, ECMASpaceClass()), nil
}
return newRegexNodeSet(ntSet, p.options, SpaceClass()), nil
case 'S':
p.moveRight(1)
if p.useOptionE() {
return newRegexNodeSet(ntSet, p.options, NotECMASpaceClass()), nil
}
return newRegexNodeSet(ntSet, p.options, NotSpaceClass()), nil
case 'd':
p.moveRight(1)
if p.useOptionE() {
return newRegexNodeSet(ntSet, p.options, ECMADigitClass()), nil
}
return newRegexNodeSet(ntSet, p.options, DigitClass()), nil
case 'D':
p.moveRight(1)
if p.useOptionE() {
return newRegexNodeSet(ntSet, p.options, NotECMADigitClass()), nil
}
return newRegexNodeSet(ntSet, p.options, NotDigitClass()), nil
case 'p', 'P':
p.moveRight(1)
prop, err := p.parseProperty()
if err != nil {
return nil, err
}
cc := &CharSet{}
cc.addCategory(prop, (ch != 'p'), p.useOptionI(), p.patternRaw)
if p.useOptionI() {
cc.addLowercase()
}
return newRegexNodeSet(ntSet, p.options, cc), nil
default:
return p.scanBasicBackslash()
}
} | go | func (p *parser) scanBackslash() (*regexNode, error) {
if p.charsRight() == 0 {
return nil, p.getErr(ErrIllegalEndEscape)
}
switch ch := p.rightChar(0); ch {
case 'b', 'B', 'A', 'G', 'Z', 'z':
p.moveRight(1)
return newRegexNode(p.typeFromCode(ch), p.options), nil
case 'w':
p.moveRight(1)
if p.useOptionE() {
return newRegexNodeSet(ntSet, p.options, ECMAWordClass()), nil
}
return newRegexNodeSet(ntSet, p.options, WordClass()), nil
case 'W':
p.moveRight(1)
if p.useOptionE() {
return newRegexNodeSet(ntSet, p.options, NotECMAWordClass()), nil
}
return newRegexNodeSet(ntSet, p.options, NotWordClass()), nil
case 's':
p.moveRight(1)
if p.useOptionE() {
return newRegexNodeSet(ntSet, p.options, ECMASpaceClass()), nil
}
return newRegexNodeSet(ntSet, p.options, SpaceClass()), nil
case 'S':
p.moveRight(1)
if p.useOptionE() {
return newRegexNodeSet(ntSet, p.options, NotECMASpaceClass()), nil
}
return newRegexNodeSet(ntSet, p.options, NotSpaceClass()), nil
case 'd':
p.moveRight(1)
if p.useOptionE() {
return newRegexNodeSet(ntSet, p.options, ECMADigitClass()), nil
}
return newRegexNodeSet(ntSet, p.options, DigitClass()), nil
case 'D':
p.moveRight(1)
if p.useOptionE() {
return newRegexNodeSet(ntSet, p.options, NotECMADigitClass()), nil
}
return newRegexNodeSet(ntSet, p.options, NotDigitClass()), nil
case 'p', 'P':
p.moveRight(1)
prop, err := p.parseProperty()
if err != nil {
return nil, err
}
cc := &CharSet{}
cc.addCategory(prop, (ch != 'p'), p.useOptionI(), p.patternRaw)
if p.useOptionI() {
cc.addLowercase()
}
return newRegexNodeSet(ntSet, p.options, cc), nil
default:
return p.scanBasicBackslash()
}
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"scanBackslash",
"(",
")",
"(",
"*",
"regexNode",
",",
"error",
")",
"{",
"if",
"p",
".",
"charsRight",
"(",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"p",
".",
"getErr",
"(",
"ErrIllegalEndEscape",
")",
"\n",... | // scans backslash specials and basics | [
"scans",
"backslash",
"specials",
"and",
"basics"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/parser.go#L1058-L1128 |
16,358 | dlclark/regexp2 | syntax/parser.go | typeFromCode | func (p *parser) typeFromCode(ch rune) nodeType {
switch ch {
case 'b':
if p.useOptionE() {
return ntECMABoundary
}
return ntBoundary
case 'B':
if p.useOptionE() {
return ntNonECMABoundary
}
return ntNonboundary
case 'A':
return ntBeginning
case 'G':
return ntStart
case 'Z':
return ntEndZ
case 'z':
return ntEnd
default:
return ntNothing
}
} | go | func (p *parser) typeFromCode(ch rune) nodeType {
switch ch {
case 'b':
if p.useOptionE() {
return ntECMABoundary
}
return ntBoundary
case 'B':
if p.useOptionE() {
return ntNonECMABoundary
}
return ntNonboundary
case 'A':
return ntBeginning
case 'G':
return ntStart
case 'Z':
return ntEndZ
case 'z':
return ntEnd
default:
return ntNothing
}
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"typeFromCode",
"(",
"ch",
"rune",
")",
"nodeType",
"{",
"switch",
"ch",
"{",
"case",
"'b'",
":",
"if",
"p",
".",
"useOptionE",
"(",
")",
"{",
"return",
"ntECMABoundary",
"\n",
"}",
"\n",
"return",
"ntBoundary",
... | // Returns ReNode type for zero-length assertions with a \ code. | [
"Returns",
"ReNode",
"type",
"for",
"zero",
"-",
"length",
"assertions",
"with",
"a",
"\\",
"code",
"."
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/parser.go#L1261-L1284 |
16,359 | dlclark/regexp2 | syntax/parser.go | scanBlank | func (p *parser) scanBlank() error {
if p.useOptionX() {
for {
for p.charsRight() > 0 && isSpace(p.rightChar(0)) {
p.moveRight(1)
}
if p.charsRight() == 0 {
break
}
if p.rightChar(0) == '#' {
for p.charsRight() > 0 && p.rightChar(0) != '\n' {
p.moveRight(1)
}
} else if p.charsRight() >= 3 && p.rightChar(2) == '#' &&
p.rightChar(1) == '?' && p.rightChar(0) == '(' {
for p.charsRight() > 0 && p.rightChar(0) != ')' {
p.moveRight(1)
}
if p.charsRight() == 0 {
return p.getErr(ErrUnterminatedComment)
}
p.moveRight(1)
} else {
break
}
}
} else {
for {
if p.charsRight() < 3 || p.rightChar(2) != '#' ||
p.rightChar(1) != '?' || p.rightChar(0) != '(' {
return nil
}
for p.charsRight() > 0 && p.rightChar(0) != ')' {
p.moveRight(1)
}
if p.charsRight() == 0 {
return p.getErr(ErrUnterminatedComment)
}
p.moveRight(1)
}
}
return nil
} | go | func (p *parser) scanBlank() error {
if p.useOptionX() {
for {
for p.charsRight() > 0 && isSpace(p.rightChar(0)) {
p.moveRight(1)
}
if p.charsRight() == 0 {
break
}
if p.rightChar(0) == '#' {
for p.charsRight() > 0 && p.rightChar(0) != '\n' {
p.moveRight(1)
}
} else if p.charsRight() >= 3 && p.rightChar(2) == '#' &&
p.rightChar(1) == '?' && p.rightChar(0) == '(' {
for p.charsRight() > 0 && p.rightChar(0) != ')' {
p.moveRight(1)
}
if p.charsRight() == 0 {
return p.getErr(ErrUnterminatedComment)
}
p.moveRight(1)
} else {
break
}
}
} else {
for {
if p.charsRight() < 3 || p.rightChar(2) != '#' ||
p.rightChar(1) != '?' || p.rightChar(0) != '(' {
return nil
}
for p.charsRight() > 0 && p.rightChar(0) != ')' {
p.moveRight(1)
}
if p.charsRight() == 0 {
return p.getErr(ErrUnterminatedComment)
}
p.moveRight(1)
}
}
return nil
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"scanBlank",
"(",
")",
"error",
"{",
"if",
"p",
".",
"useOptionX",
"(",
")",
"{",
"for",
"{",
"for",
"p",
".",
"charsRight",
"(",
")",
">",
"0",
"&&",
"isSpace",
"(",
"p",
".",
"rightChar",
"(",
"0",
")",
... | // Scans whitespace or x-mode comments. | [
"Scans",
"whitespace",
"or",
"x",
"-",
"mode",
"comments",
"."
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/parser.go#L1287-L1332 |
16,360 | dlclark/regexp2 | syntax/parser.go | scanOptions | func (p *parser) scanOptions() {
for off := false; p.charsRight() > 0; p.moveRight(1) {
ch := p.rightChar(0)
if ch == '-' {
off = true
} else if ch == '+' {
off = false
} else {
option := optionFromCode(ch)
if option == 0 || isOnlyTopOption(option) {
return
}
if off {
p.options &= ^option
} else {
p.options |= option
}
}
}
} | go | func (p *parser) scanOptions() {
for off := false; p.charsRight() > 0; p.moveRight(1) {
ch := p.rightChar(0)
if ch == '-' {
off = true
} else if ch == '+' {
off = false
} else {
option := optionFromCode(ch)
if option == 0 || isOnlyTopOption(option) {
return
}
if off {
p.options &= ^option
} else {
p.options |= option
}
}
}
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"scanOptions",
"(",
")",
"{",
"for",
"off",
":=",
"false",
";",
"p",
".",
"charsRight",
"(",
")",
">",
"0",
";",
"p",
".",
"moveRight",
"(",
"1",
")",
"{",
"ch",
":=",
"p",
".",
"rightChar",
"(",
"0",
")"... | // Scans cimsx-cimsx option string, stops at the first unrecognized char. | [
"Scans",
"cimsx",
"-",
"cimsx",
"option",
"string",
"stops",
"at",
"the",
"first",
"unrecognized",
"char",
"."
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/parser.go#L1554-L1576 |
16,361 | dlclark/regexp2 | syntax/parser.go | scanCharEscape | func (p *parser) scanCharEscape() (rune, error) {
ch := p.moveRightGetChar()
if ch >= '0' && ch <= '7' {
p.moveLeft()
return p.scanOctal(), nil
}
switch ch {
case 'x':
// support for \x{HEX} syntax from Perl and PCRE
if p.charsRight() > 0 && p.rightChar(0) == '{' {
p.moveRight(1)
return p.scanHexUntilBrace()
}
return p.scanHex(2)
case 'u':
return p.scanHex(4)
case 'a':
return '\u0007', nil
case 'b':
return '\b', nil
case 'e':
return '\u001B', nil
case 'f':
return '\f', nil
case 'n':
return '\n', nil
case 'r':
return '\r', nil
case 't':
return '\t', nil
case 'v':
return '\u000B', nil
case 'c':
return p.scanControl()
default:
if !p.useOptionE() && IsWordChar(ch) {
return 0, p.getErr(ErrUnrecognizedEscape, string(ch))
}
return ch, nil
}
} | go | func (p *parser) scanCharEscape() (rune, error) {
ch := p.moveRightGetChar()
if ch >= '0' && ch <= '7' {
p.moveLeft()
return p.scanOctal(), nil
}
switch ch {
case 'x':
// support for \x{HEX} syntax from Perl and PCRE
if p.charsRight() > 0 && p.rightChar(0) == '{' {
p.moveRight(1)
return p.scanHexUntilBrace()
}
return p.scanHex(2)
case 'u':
return p.scanHex(4)
case 'a':
return '\u0007', nil
case 'b':
return '\b', nil
case 'e':
return '\u001B', nil
case 'f':
return '\f', nil
case 'n':
return '\n', nil
case 'r':
return '\r', nil
case 't':
return '\t', nil
case 'v':
return '\u000B', nil
case 'c':
return p.scanControl()
default:
if !p.useOptionE() && IsWordChar(ch) {
return 0, p.getErr(ErrUnrecognizedEscape, string(ch))
}
return ch, nil
}
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"scanCharEscape",
"(",
")",
"(",
"rune",
",",
"error",
")",
"{",
"ch",
":=",
"p",
".",
"moveRightGetChar",
"(",
")",
"\n\n",
"if",
"ch",
">=",
"'0'",
"&&",
"ch",
"<=",
"'7'",
"{",
"p",
".",
"moveLeft",
"(",
... | // Scans \ code for escape codes that map to single unicode chars. | [
"Scans",
"\\",
"code",
"for",
"escape",
"codes",
"that",
"map",
"to",
"single",
"unicode",
"chars",
"."
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/parser.go#L1579-L1622 |
16,362 | dlclark/regexp2 | syntax/parser.go | scanControl | func (p *parser) scanControl() (rune, error) {
if p.charsRight() <= 0 {
return 0, p.getErr(ErrMissingControl)
}
ch := p.moveRightGetChar()
// \ca interpreted as \cA
if ch >= 'a' && ch <= 'z' {
ch = (ch - ('a' - 'A'))
}
ch = (ch - '@')
if ch >= 0 && ch < ' ' {
return ch, nil
}
return 0, p.getErr(ErrUnrecognizedControl)
} | go | func (p *parser) scanControl() (rune, error) {
if p.charsRight() <= 0 {
return 0, p.getErr(ErrMissingControl)
}
ch := p.moveRightGetChar()
// \ca interpreted as \cA
if ch >= 'a' && ch <= 'z' {
ch = (ch - ('a' - 'A'))
}
ch = (ch - '@')
if ch >= 0 && ch < ' ' {
return ch, nil
}
return 0, p.getErr(ErrUnrecognizedControl)
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"scanControl",
"(",
")",
"(",
"rune",
",",
"error",
")",
"{",
"if",
"p",
".",
"charsRight",
"(",
")",
"<=",
"0",
"{",
"return",
"0",
",",
"p",
".",
"getErr",
"(",
"ErrMissingControl",
")",
"\n",
"}",
"\n\n",
... | // Grabs and converts an ascii control character | [
"Grabs",
"and",
"converts",
"an",
"ascii",
"control",
"character"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/parser.go#L1625-L1644 |
16,363 | dlclark/regexp2 | syntax/parser.go | scanHexUntilBrace | func (p *parser) scanHexUntilBrace() (rune, error) {
// PCRE spec reads like unlimited hex digits are allowed, but unicode has a limit
// so we can enforce that
i := 0
hasContent := false
for p.charsRight() > 0 {
ch := p.moveRightGetChar()
if ch == '}' {
// hit our close brace, we're done here
// prevent \x{}
if !hasContent {
return 0, p.getErr(ErrTooFewHex)
}
return rune(i), nil
}
hasContent = true
// no brace needs to be hex digit
d := hexDigit(ch)
if d < 0 {
return 0, p.getErr(ErrMissingBrace)
}
i *= 0x10
i += d
if i > unicode.MaxRune {
return 0, p.getErr(ErrInvalidHex)
}
}
// we only make it here if we run out of digits without finding the brace
return 0, p.getErr(ErrMissingBrace)
} | go | func (p *parser) scanHexUntilBrace() (rune, error) {
// PCRE spec reads like unlimited hex digits are allowed, but unicode has a limit
// so we can enforce that
i := 0
hasContent := false
for p.charsRight() > 0 {
ch := p.moveRightGetChar()
if ch == '}' {
// hit our close brace, we're done here
// prevent \x{}
if !hasContent {
return 0, p.getErr(ErrTooFewHex)
}
return rune(i), nil
}
hasContent = true
// no brace needs to be hex digit
d := hexDigit(ch)
if d < 0 {
return 0, p.getErr(ErrMissingBrace)
}
i *= 0x10
i += d
if i > unicode.MaxRune {
return 0, p.getErr(ErrInvalidHex)
}
}
// we only make it here if we run out of digits without finding the brace
return 0, p.getErr(ErrMissingBrace)
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"scanHexUntilBrace",
"(",
")",
"(",
"rune",
",",
"error",
")",
"{",
"// PCRE spec reads like unlimited hex digits are allowed, but unicode has a limit",
"// so we can enforce that",
"i",
":=",
"0",
"\n",
"hasContent",
":=",
"false",... | // Scan hex digits until we hit a closing brace.
// Non-hex digits, hex value too large for UTF-8, or running out of chars are errors | [
"Scan",
"hex",
"digits",
"until",
"we",
"hit",
"a",
"closing",
"brace",
".",
"Non",
"-",
"hex",
"digits",
"hex",
"value",
"too",
"large",
"for",
"UTF",
"-",
"8",
"or",
"running",
"out",
"of",
"chars",
"are",
"errors"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/parser.go#L1648-L1681 |
16,364 | dlclark/regexp2 | syntax/parser.go | hexDigit | func hexDigit(ch rune) int {
if d := uint(ch - '0'); d <= 9 {
return int(d)
}
if d := uint(ch - 'a'); d <= 5 {
return int(d + 0xa)
}
if d := uint(ch - 'A'); d <= 5 {
return int(d + 0xa)
}
return -1
} | go | func hexDigit(ch rune) int {
if d := uint(ch - '0'); d <= 9 {
return int(d)
}
if d := uint(ch - 'a'); d <= 5 {
return int(d + 0xa)
}
if d := uint(ch - 'A'); d <= 5 {
return int(d + 0xa)
}
return -1
} | [
"func",
"hexDigit",
"(",
"ch",
"rune",
")",
"int",
"{",
"if",
"d",
":=",
"uint",
"(",
"ch",
"-",
"'0'",
")",
";",
"d",
"<=",
"9",
"{",
"return",
"int",
"(",
"d",
")",
"\n",
"}",
"\n\n",
"if",
"d",
":=",
"uint",
"(",
"ch",
"-",
"'a'",
")",
... | // Returns n <= 0xF for a hex digit. | [
"Returns",
"n",
"<",
"=",
"0xF",
"for",
"a",
"hex",
"digit",
"."
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/parser.go#L1708-L1723 |
16,365 | dlclark/regexp2 | syntax/parser.go | moveRightGetChar | func (p *parser) moveRightGetChar() rune {
ch := p.pattern[p.currentPos]
p.currentPos++
return ch
} | go | func (p *parser) moveRightGetChar() rune {
ch := p.pattern[p.currentPos]
p.currentPos++
return ch
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"moveRightGetChar",
"(",
")",
"rune",
"{",
"ch",
":=",
"p",
".",
"pattern",
"[",
"p",
".",
"currentPos",
"]",
"\n",
"p",
".",
"currentPos",
"++",
"\n",
"return",
"ch",
"\n",
"}"
] | // Returns the char at the right of the current parsing position and advances to the right. | [
"Returns",
"the",
"char",
"at",
"the",
"right",
"of",
"the",
"current",
"parsing",
"position",
"and",
"advances",
"to",
"the",
"right",
"."
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/parser.go#L1770-L1774 |
16,366 | dlclark/regexp2 | syntax/parser.go | rightChar | func (p *parser) rightChar(i int) rune {
// default would be 0
return p.pattern[p.currentPos+i]
} | go | func (p *parser) rightChar(i int) rune {
// default would be 0
return p.pattern[p.currentPos+i]
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"rightChar",
"(",
"i",
"int",
")",
"rune",
"{",
"// default would be 0",
"return",
"p",
".",
"pattern",
"[",
"p",
".",
"currentPos",
"+",
"i",
"]",
"\n",
"}"
] | // Returns the char i chars right of the current parsing position. | [
"Returns",
"the",
"char",
"i",
"chars",
"right",
"of",
"the",
"current",
"parsing",
"position",
"."
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/parser.go#L1793-L1796 |
16,367 | dlclark/regexp2 | syntax/parser.go | isCaptureSlot | func (p *parser) isCaptureSlot(i int) bool {
if p.caps != nil {
_, ok := p.caps[i]
return ok
}
return (i >= 0 && i < p.capsize)
} | go | func (p *parser) isCaptureSlot(i int) bool {
if p.caps != nil {
_, ok := p.caps[i]
return ok
}
return (i >= 0 && i < p.capsize)
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"isCaptureSlot",
"(",
"i",
"int",
")",
"bool",
"{",
"if",
"p",
".",
"caps",
"!=",
"nil",
"{",
"_",
",",
"ok",
":=",
"p",
".",
"caps",
"[",
"i",
"]",
"\n",
"return",
"ok",
"\n",
"}",
"\n\n",
"return",
"(",... | // True if the capture slot was noted | [
"True",
"if",
"the",
"capture",
"slot",
"was",
"noted"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/parser.go#L1813-L1820 |
16,368 | dlclark/regexp2 | syntax/parser.go | isCaptureName | func (p *parser) isCaptureName(capname string) bool {
if p.capnames == nil {
return false
}
_, ok := p.capnames[capname]
return ok
} | go | func (p *parser) isCaptureName(capname string) bool {
if p.capnames == nil {
return false
}
_, ok := p.capnames[capname]
return ok
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"isCaptureName",
"(",
"capname",
"string",
")",
"bool",
"{",
"if",
"p",
".",
"capnames",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"_",
",",
"ok",
":=",
"p",
".",
"capnames",
"[",
"capname",
"]",
... | // Looks up the slot number for a given name | [
"Looks",
"up",
"the",
"slot",
"number",
"for",
"a",
"given",
"name"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/parser.go#L1823-L1830 |
16,369 | dlclark/regexp2 | syntax/parser.go | addUnitOne | func (p *parser) addUnitOne(ch rune) {
if p.useOptionI() {
ch = unicode.ToLower(ch)
}
p.unit = newRegexNodeCh(ntOne, p.options, ch)
} | go | func (p *parser) addUnitOne(ch rune) {
if p.useOptionI() {
ch = unicode.ToLower(ch)
}
p.unit = newRegexNodeCh(ntOne, p.options, ch)
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"addUnitOne",
"(",
"ch",
"rune",
")",
"{",
"if",
"p",
".",
"useOptionI",
"(",
")",
"{",
"ch",
"=",
"unicode",
".",
"ToLower",
"(",
"ch",
")",
"\n",
"}",
"\n\n",
"p",
".",
"unit",
"=",
"newRegexNodeCh",
"(",
... | // Sets the current unit to a single char node | [
"Sets",
"the",
"current",
"unit",
"to",
"a",
"single",
"char",
"node"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/parser.go#L1883-L1889 |
16,370 | dlclark/regexp2 | syntax/parser.go | addUnitNotone | func (p *parser) addUnitNotone(ch rune) {
if p.useOptionI() {
ch = unicode.ToLower(ch)
}
p.unit = newRegexNodeCh(ntNotone, p.options, ch)
} | go | func (p *parser) addUnitNotone(ch rune) {
if p.useOptionI() {
ch = unicode.ToLower(ch)
}
p.unit = newRegexNodeCh(ntNotone, p.options, ch)
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"addUnitNotone",
"(",
"ch",
"rune",
")",
"{",
"if",
"p",
".",
"useOptionI",
"(",
")",
"{",
"ch",
"=",
"unicode",
".",
"ToLower",
"(",
"ch",
")",
"\n",
"}",
"\n\n",
"p",
".",
"unit",
"=",
"newRegexNodeCh",
"("... | // Sets the current unit to a single inverse-char node | [
"Sets",
"the",
"current",
"unit",
"to",
"a",
"single",
"inverse",
"-",
"char",
"node"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/parser.go#L1892-L1898 |
16,371 | dlclark/regexp2 | syntax/parser.go | addUnitSet | func (p *parser) addUnitSet(set *CharSet) {
p.unit = newRegexNodeSet(ntSet, p.options, set)
} | go | func (p *parser) addUnitSet(set *CharSet) {
p.unit = newRegexNodeSet(ntSet, p.options, set)
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"addUnitSet",
"(",
"set",
"*",
"CharSet",
")",
"{",
"p",
".",
"unit",
"=",
"newRegexNodeSet",
"(",
"ntSet",
",",
"p",
".",
"options",
",",
"set",
")",
"\n",
"}"
] | // Sets the current unit to a single set node | [
"Sets",
"the",
"current",
"unit",
"to",
"a",
"single",
"set",
"node"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/parser.go#L1901-L1903 |
16,372 | dlclark/regexp2 | syntax/parser.go | addUnitType | func (p *parser) addUnitType(t nodeType) {
p.unit = newRegexNode(t, p.options)
} | go | func (p *parser) addUnitType(t nodeType) {
p.unit = newRegexNode(t, p.options)
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"addUnitType",
"(",
"t",
"nodeType",
")",
"{",
"p",
".",
"unit",
"=",
"newRegexNode",
"(",
"t",
",",
"p",
".",
"options",
")",
"\n",
"}"
] | // Sets the current unit to an assertion of the specified type | [
"Sets",
"the",
"current",
"unit",
"to",
"an",
"assertion",
"of",
"the",
"specified",
"type"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/parser.go#L1911-L1913 |
16,373 | dlclark/regexp2 | syntax/parser.go | popKeepOptions | func (p *parser) popKeepOptions() {
lastIdx := len(p.optionsStack) - 1
p.optionsStack = p.optionsStack[:lastIdx]
} | go | func (p *parser) popKeepOptions() {
lastIdx := len(p.optionsStack) - 1
p.optionsStack = p.optionsStack[:lastIdx]
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"popKeepOptions",
"(",
")",
"{",
"lastIdx",
":=",
"len",
"(",
"p",
".",
"optionsStack",
")",
"-",
"1",
"\n",
"p",
".",
"optionsStack",
"=",
"p",
".",
"optionsStack",
"[",
":",
"lastIdx",
"]",
"\n",
"}"
] | // Pops the option stack, but keeps the current options unchanged. | [
"Pops",
"the",
"option",
"stack",
"but",
"keeps",
"the",
"current",
"options",
"unchanged",
"."
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/parser.go#L1932-L1935 |
16,374 | dlclark/regexp2 | syntax/parser.go | popOptions | func (p *parser) popOptions() {
lastIdx := len(p.optionsStack) - 1
// get the last item on the stack and then remove it by reslicing
p.options = p.optionsStack[lastIdx]
p.optionsStack = p.optionsStack[:lastIdx]
} | go | func (p *parser) popOptions() {
lastIdx := len(p.optionsStack) - 1
// get the last item on the stack and then remove it by reslicing
p.options = p.optionsStack[lastIdx]
p.optionsStack = p.optionsStack[:lastIdx]
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"popOptions",
"(",
")",
"{",
"lastIdx",
":=",
"len",
"(",
"p",
".",
"optionsStack",
")",
"-",
"1",
"\n",
"// get the last item on the stack and then remove it by reslicing",
"p",
".",
"options",
"=",
"p",
".",
"optionsStac... | // Recalls options from the stack. | [
"Recalls",
"options",
"from",
"the",
"stack",
"."
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/parser.go#L1938-L1943 |
16,375 | dlclark/regexp2 | syntax/parser.go | pushOptions | func (p *parser) pushOptions() {
p.optionsStack = append(p.optionsStack, p.options)
} | go | func (p *parser) pushOptions() {
p.optionsStack = append(p.optionsStack, p.options)
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"pushOptions",
"(",
")",
"{",
"p",
".",
"optionsStack",
"=",
"append",
"(",
"p",
".",
"optionsStack",
",",
"p",
".",
"options",
")",
"\n",
"}"
] | // Saves options on a stack. | [
"Saves",
"options",
"on",
"a",
"stack",
"."
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/parser.go#L1946-L1948 |
16,376 | dlclark/regexp2 | syntax/parser.go | addToConcatenate | func (p *parser) addToConcatenate(pos, cch int, isReplacement bool) {
var node *regexNode
if cch == 0 {
return
}
if cch > 1 {
str := p.pattern[pos : pos+cch]
if p.useOptionI() && !isReplacement {
// We do the ToLower character by character for consistency. With surrogate chars, doing
// a ToLower on the entire string could actually change the surrogate pair. This is more correct
// linguistically, but since Regex doesn't support surrogates, it's more important to be
// consistent.
for i := 0; i < len(str); i++ {
str[i] = unicode.ToLower(str[i])
}
}
node = newRegexNodeStr(ntMulti, p.options, str)
} else {
ch := p.charAt(pos)
if p.useOptionI() && !isReplacement {
ch = unicode.ToLower(ch)
}
node = newRegexNodeCh(ntOne, p.options, ch)
}
p.concatenation.addChild(node)
} | go | func (p *parser) addToConcatenate(pos, cch int, isReplacement bool) {
var node *regexNode
if cch == 0 {
return
}
if cch > 1 {
str := p.pattern[pos : pos+cch]
if p.useOptionI() && !isReplacement {
// We do the ToLower character by character for consistency. With surrogate chars, doing
// a ToLower on the entire string could actually change the surrogate pair. This is more correct
// linguistically, but since Regex doesn't support surrogates, it's more important to be
// consistent.
for i := 0; i < len(str); i++ {
str[i] = unicode.ToLower(str[i])
}
}
node = newRegexNodeStr(ntMulti, p.options, str)
} else {
ch := p.charAt(pos)
if p.useOptionI() && !isReplacement {
ch = unicode.ToLower(ch)
}
node = newRegexNodeCh(ntOne, p.options, ch)
}
p.concatenation.addChild(node)
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"addToConcatenate",
"(",
"pos",
",",
"cch",
"int",
",",
"isReplacement",
"bool",
")",
"{",
"var",
"node",
"*",
"regexNode",
"\n\n",
"if",
"cch",
"==",
"0",
"{",
"return",
"\n",
"}",
"\n\n",
"if",
"cch",
">",
"1... | // Add a string to the last concatenate. | [
"Add",
"a",
"string",
"to",
"the",
"last",
"concatenate",
"."
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/parser.go#L1951-L1983 |
16,377 | dlclark/regexp2 | syntax/tree.go | removeChildren | func (n *regexNode) removeChildren(startIndex, endIndex int) {
n.children = append(n.children[:startIndex], n.children[endIndex:]...)
} | go | func (n *regexNode) removeChildren(startIndex, endIndex int) {
n.children = append(n.children[:startIndex], n.children[endIndex:]...)
} | [
"func",
"(",
"n",
"*",
"regexNode",
")",
"removeChildren",
"(",
"startIndex",
",",
"endIndex",
"int",
")",
"{",
"n",
".",
"children",
"=",
"append",
"(",
"n",
".",
"children",
"[",
":",
"startIndex",
"]",
",",
"n",
".",
"children",
"[",
"endIndex",
"... | // removes children including the start but not the end index | [
"removes",
"children",
"including",
"the",
"start",
"but",
"not",
"the",
"end",
"index"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/tree.go#L183-L185 |
16,378 | dlclark/regexp2 | syntax/tree.go | makeRep | func (n *regexNode) makeRep(t nodeType, min, max int) {
n.t += (t - ntOne)
n.m = min
n.n = max
} | go | func (n *regexNode) makeRep(t nodeType, min, max int) {
n.t += (t - ntOne)
n.m = min
n.n = max
} | [
"func",
"(",
"n",
"*",
"regexNode",
")",
"makeRep",
"(",
"t",
"nodeType",
",",
"min",
",",
"max",
"int",
")",
"{",
"n",
".",
"t",
"+=",
"(",
"t",
"-",
"ntOne",
")",
"\n",
"n",
".",
"m",
"=",
"min",
"\n",
"n",
".",
"n",
"=",
"max",
"\n",
"... | // Pass type as OneLazy or OneLoop | [
"Pass",
"type",
"as",
"OneLazy",
"or",
"OneLoop"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/tree.go#L188-L192 |
16,379 | dlclark/regexp2 | syntax/tree.go | reduceRep | func (n *regexNode) reduceRep() *regexNode {
u := n
t := n.t
min := n.m
max := n.n
for {
if len(u.children) == 0 {
break
}
child := u.children[0]
// multiply reps of the same type only
if child.t != t {
childType := child.t
if !(childType >= ntOneloop && childType <= ntSetloop && t == ntLoop ||
childType >= ntOnelazy && childType <= ntSetlazy && t == ntLazyloop) {
break
}
}
// child can be too lumpy to blur, e.g., (a {100,105}) {3} or (a {2,})?
// [but things like (a {2,})+ are not too lumpy...]
if u.m == 0 && child.m > 1 || child.n < child.m*2 {
break
}
u = child
if u.m > 0 {
if (math.MaxInt32-1)/u.m < min {
u.m = math.MaxInt32
} else {
u.m = u.m * min
}
}
if u.n > 0 {
if (math.MaxInt32-1)/u.n < max {
u.n = math.MaxInt32
} else {
u.n = u.n * max
}
}
}
if math.MaxInt32 == min {
return newRegexNode(ntNothing, n.options)
}
return u
} | go | func (n *regexNode) reduceRep() *regexNode {
u := n
t := n.t
min := n.m
max := n.n
for {
if len(u.children) == 0 {
break
}
child := u.children[0]
// multiply reps of the same type only
if child.t != t {
childType := child.t
if !(childType >= ntOneloop && childType <= ntSetloop && t == ntLoop ||
childType >= ntOnelazy && childType <= ntSetlazy && t == ntLazyloop) {
break
}
}
// child can be too lumpy to blur, e.g., (a {100,105}) {3} or (a {2,})?
// [but things like (a {2,})+ are not too lumpy...]
if u.m == 0 && child.m > 1 || child.n < child.m*2 {
break
}
u = child
if u.m > 0 {
if (math.MaxInt32-1)/u.m < min {
u.m = math.MaxInt32
} else {
u.m = u.m * min
}
}
if u.n > 0 {
if (math.MaxInt32-1)/u.n < max {
u.n = math.MaxInt32
} else {
u.n = u.n * max
}
}
}
if math.MaxInt32 == min {
return newRegexNode(ntNothing, n.options)
}
return u
} | [
"func",
"(",
"n",
"*",
"regexNode",
")",
"reduceRep",
"(",
")",
"*",
"regexNode",
"{",
"u",
":=",
"n",
"\n",
"t",
":=",
"n",
".",
"t",
"\n",
"min",
":=",
"n",
".",
"m",
"\n",
"max",
":=",
"n",
".",
"n",
"\n\n",
"for",
"{",
"if",
"len",
"(",... | // Nested repeaters just get multiplied with each other if they're not
// too lumpy | [
"Nested",
"repeaters",
"just",
"get",
"multiplied",
"with",
"each",
"other",
"if",
"they",
"re",
"not",
"too",
"lumpy"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/tree.go#L393-L445 |
16,380 | dlclark/regexp2 | syntax/tree.go | stripEnation | func (n *regexNode) stripEnation(emptyType nodeType) *regexNode {
switch len(n.children) {
case 0:
return newRegexNode(emptyType, n.options)
case 1:
return n.children[0]
default:
return n
}
} | go | func (n *regexNode) stripEnation(emptyType nodeType) *regexNode {
switch len(n.children) {
case 0:
return newRegexNode(emptyType, n.options)
case 1:
return n.children[0]
default:
return n
}
} | [
"func",
"(",
"n",
"*",
"regexNode",
")",
"stripEnation",
"(",
"emptyType",
"nodeType",
")",
"*",
"regexNode",
"{",
"switch",
"len",
"(",
"n",
".",
"children",
")",
"{",
"case",
"0",
":",
"return",
"newRegexNode",
"(",
"emptyType",
",",
"n",
".",
"optio... | // Simple optimization. If a concatenation or alternation has only
// one child strip out the intermediate node. If it has zero children,
// turn it into an empty. | [
"Simple",
"optimization",
".",
"If",
"a",
"concatenation",
"or",
"alternation",
"has",
"only",
"one",
"child",
"strip",
"out",
"the",
"intermediate",
"node",
".",
"If",
"it",
"has",
"zero",
"children",
"turn",
"it",
"into",
"an",
"empty",
"."
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/tree.go#L450-L459 |
16,381 | dlclark/regexp2 | syntax/tree.go | reduceSet | func (n *regexNode) reduceSet() *regexNode {
// Extract empty-set, one and not-one case as special
if n.set == nil {
n.t = ntNothing
} else if n.set.IsSingleton() {
n.ch = n.set.SingletonChar()
n.set = nil
n.t += (ntOne - ntSet)
} else if n.set.IsSingletonInverse() {
n.ch = n.set.SingletonChar()
n.set = nil
n.t += (ntNotone - ntSet)
}
return n
} | go | func (n *regexNode) reduceSet() *regexNode {
// Extract empty-set, one and not-one case as special
if n.set == nil {
n.t = ntNothing
} else if n.set.IsSingleton() {
n.ch = n.set.SingletonChar()
n.set = nil
n.t += (ntOne - ntSet)
} else if n.set.IsSingletonInverse() {
n.ch = n.set.SingletonChar()
n.set = nil
n.t += (ntNotone - ntSet)
}
return n
} | [
"func",
"(",
"n",
"*",
"regexNode",
")",
"reduceSet",
"(",
")",
"*",
"regexNode",
"{",
"// Extract empty-set, one and not-one case as special",
"if",
"n",
".",
"set",
"==",
"nil",
"{",
"n",
".",
"t",
"=",
"ntNothing",
"\n",
"}",
"else",
"if",
"n",
".",
"... | // Simple optimization. If a set is a singleton, an inverse singleton,
// or empty, it's transformed accordingly. | [
"Simple",
"optimization",
".",
"If",
"a",
"set",
"is",
"a",
"singleton",
"an",
"inverse",
"singleton",
"or",
"empty",
"it",
"s",
"transformed",
"accordingly",
"."
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/tree.go#L473-L489 |
16,382 | dlclark/regexp2 | syntax/prefix.go | getFirstCharsPrefix | func getFirstCharsPrefix(tree *RegexTree) *Prefix {
s := regexFcd{
fcStack: make([]regexFc, 32),
intStack: make([]int, 32),
}
fc := s.regexFCFromRegexTree(tree)
if fc == nil || fc.nullable || fc.cc.IsEmpty() {
return nil
}
fcSet := fc.getFirstChars()
return &Prefix{PrefixSet: fcSet, CaseInsensitive: fc.caseInsensitive}
} | go | func getFirstCharsPrefix(tree *RegexTree) *Prefix {
s := regexFcd{
fcStack: make([]regexFc, 32),
intStack: make([]int, 32),
}
fc := s.regexFCFromRegexTree(tree)
if fc == nil || fc.nullable || fc.cc.IsEmpty() {
return nil
}
fcSet := fc.getFirstChars()
return &Prefix{PrefixSet: fcSet, CaseInsensitive: fc.caseInsensitive}
} | [
"func",
"getFirstCharsPrefix",
"(",
"tree",
"*",
"RegexTree",
")",
"*",
"Prefix",
"{",
"s",
":=",
"regexFcd",
"{",
"fcStack",
":",
"make",
"(",
"[",
"]",
"regexFc",
",",
"32",
")",
",",
"intStack",
":",
"make",
"(",
"[",
"]",
"int",
",",
"32",
")",... | // It takes a RegexTree and computes the set of chars that can start it. | [
"It",
"takes",
"a",
"RegexTree",
"and",
"computes",
"the",
"set",
"of",
"chars",
"that",
"can",
"start",
"it",
"."
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/prefix.go#L18-L30 |
16,383 | dlclark/regexp2 | syntax/prefix.go | pushFC | func (s *regexFcd) pushFC(fc regexFc) {
if s.fcDepth >= len(s.fcStack) {
expanded := make([]regexFc, s.fcDepth*2)
copy(expanded, s.fcStack)
s.fcStack = expanded
}
s.fcStack[s.fcDepth] = fc
s.fcDepth++
} | go | func (s *regexFcd) pushFC(fc regexFc) {
if s.fcDepth >= len(s.fcStack) {
expanded := make([]regexFc, s.fcDepth*2)
copy(expanded, s.fcStack)
s.fcStack = expanded
}
s.fcStack[s.fcDepth] = fc
s.fcDepth++
} | [
"func",
"(",
"s",
"*",
"regexFcd",
")",
"pushFC",
"(",
"fc",
"regexFc",
")",
"{",
"if",
"s",
".",
"fcDepth",
">=",
"len",
"(",
"s",
".",
"fcStack",
")",
"{",
"expanded",
":=",
"make",
"(",
"[",
"]",
"regexFc",
",",
"s",
".",
"fcDepth",
"*",
"2"... | // We also use a stack of RegexFC objects.
// This is the push. | [
"We",
"also",
"use",
"a",
"stack",
"of",
"RegexFC",
"objects",
".",
"This",
"is",
"the",
"push",
"."
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/prefix.go#L123-L132 |
16,384 | dlclark/regexp2 | syntax/prefix.go | repeat | func repeat(r rune, c int) []rune {
if c > MaxPrefixSize {
c = MaxPrefixSize
}
ret := make([]rune, c)
// binary growth using copy for speed
ret[0] = r
bp := 1
for bp < len(ret) {
copy(ret[bp:], ret[:bp])
bp *= 2
}
return ret
} | go | func repeat(r rune, c int) []rune {
if c > MaxPrefixSize {
c = MaxPrefixSize
}
ret := make([]rune, c)
// binary growth using copy for speed
ret[0] = r
bp := 1
for bp < len(ret) {
copy(ret[bp:], ret[:bp])
bp *= 2
}
return ret
} | [
"func",
"repeat",
"(",
"r",
"rune",
",",
"c",
"int",
")",
"[",
"]",
"rune",
"{",
"if",
"c",
">",
"MaxPrefixSize",
"{",
"c",
"=",
"MaxPrefixSize",
"\n",
"}",
"\n\n",
"ret",
":=",
"make",
"(",
"[",
"]",
"rune",
",",
"c",
")",
"\n\n",
"// binary gro... | // repeat the rune r, c times... up to the max of MaxPrefixSize | [
"repeat",
"the",
"rune",
"r",
"c",
"times",
"...",
"up",
"to",
"the",
"max",
"of",
"MaxPrefixSize"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/prefix.go#L393-L409 |
16,385 | dlclark/regexp2 | syntax/prefix.go | Dump | func (b *BmPrefix) Dump(indent string) string {
buf := &bytes.Buffer{}
fmt.Fprintf(buf, "%sBM Pattern: %s\n%sPositive: ", indent, string(b.pattern), indent)
for i := 0; i < len(b.positive); i++ {
buf.WriteString(strconv.Itoa(b.positive[i]))
buf.WriteRune(' ')
}
buf.WriteRune('\n')
if b.negativeASCII != nil {
buf.WriteString(indent)
buf.WriteString("Negative table\n")
for i := 0; i < len(b.negativeASCII); i++ {
if b.negativeASCII[i] != len(b.pattern) {
fmt.Fprintf(buf, "%s %s %s\n", indent, Escape(string(rune(i))), strconv.Itoa(b.negativeASCII[i]))
}
}
}
return buf.String()
} | go | func (b *BmPrefix) Dump(indent string) string {
buf := &bytes.Buffer{}
fmt.Fprintf(buf, "%sBM Pattern: %s\n%sPositive: ", indent, string(b.pattern), indent)
for i := 0; i < len(b.positive); i++ {
buf.WriteString(strconv.Itoa(b.positive[i]))
buf.WriteRune(' ')
}
buf.WriteRune('\n')
if b.negativeASCII != nil {
buf.WriteString(indent)
buf.WriteString("Negative table\n")
for i := 0; i < len(b.negativeASCII); i++ {
if b.negativeASCII[i] != len(b.pattern) {
fmt.Fprintf(buf, "%s %s %s\n", indent, Escape(string(rune(i))), strconv.Itoa(b.negativeASCII[i]))
}
}
}
return buf.String()
} | [
"func",
"(",
"b",
"*",
"BmPrefix",
")",
"Dump",
"(",
"indent",
"string",
")",
"string",
"{",
"buf",
":=",
"&",
"bytes",
".",
"Buffer",
"{",
"}",
"\n\n",
"fmt",
".",
"Fprintf",
"(",
"buf",
",",
"\"",
"\\n",
"\"",
",",
"indent",
",",
"string",
"(",... | // Dump returns the contents of the filter as a human readable string | [
"Dump",
"returns",
"the",
"contents",
"of",
"the",
"filter",
"as",
"a",
"human",
"readable",
"string"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/prefix.go#L611-L632 |
16,386 | dlclark/regexp2 | syntax/prefix.go | Scan | func (b *BmPrefix) Scan(text []rune, index, beglimit, endlimit int) int {
var (
defadv, test, test2 int
match, startmatch, endmatch int
bump, advance int
chTest rune
unicodeLookup []int
)
if !b.rightToLeft {
defadv = len(b.pattern)
startmatch = len(b.pattern) - 1
endmatch = 0
test = index + defadv - 1
bump = 1
} else {
defadv = -len(b.pattern)
startmatch = 0
endmatch = -defadv - 1
test = index + defadv
bump = -1
}
chMatch := b.pattern[startmatch]
for {
if test >= endlimit || test < beglimit {
return -1
}
chTest = text[test]
if b.caseInsensitive {
chTest = unicode.ToLower(chTest)
}
if chTest != chMatch {
if chTest < 128 {
advance = b.negativeASCII[chTest]
} else if chTest < 0xffff && len(b.negativeUnicode) > 0 {
unicodeLookup = b.negativeUnicode[chTest>>8]
if len(unicodeLookup) > 0 {
advance = unicodeLookup[chTest&0xFF]
} else {
advance = defadv
}
} else {
advance = defadv
}
test += advance
} else { // if (chTest == chMatch)
test2 = test
match = startmatch
for {
if match == endmatch {
if b.rightToLeft {
return test2 + 1
} else {
return test2
}
}
match -= bump
test2 -= bump
chTest = text[test2]
if b.caseInsensitive {
chTest = unicode.ToLower(chTest)
}
if chTest != b.pattern[match] {
advance = b.positive[match]
if (chTest & 0xFF80) == 0 {
test2 = (match - startmatch) + b.negativeASCII[chTest]
} else if chTest < 0xffff && len(b.negativeUnicode) > 0 {
unicodeLookup = b.negativeUnicode[chTest>>8]
if len(unicodeLookup) > 0 {
test2 = (match - startmatch) + unicodeLookup[chTest&0xFF]
} else {
test += advance
break
}
} else {
test += advance
break
}
if b.rightToLeft {
if test2 < advance {
advance = test2
}
} else if test2 > advance {
advance = test2
}
test += advance
break
}
}
}
}
} | go | func (b *BmPrefix) Scan(text []rune, index, beglimit, endlimit int) int {
var (
defadv, test, test2 int
match, startmatch, endmatch int
bump, advance int
chTest rune
unicodeLookup []int
)
if !b.rightToLeft {
defadv = len(b.pattern)
startmatch = len(b.pattern) - 1
endmatch = 0
test = index + defadv - 1
bump = 1
} else {
defadv = -len(b.pattern)
startmatch = 0
endmatch = -defadv - 1
test = index + defadv
bump = -1
}
chMatch := b.pattern[startmatch]
for {
if test >= endlimit || test < beglimit {
return -1
}
chTest = text[test]
if b.caseInsensitive {
chTest = unicode.ToLower(chTest)
}
if chTest != chMatch {
if chTest < 128 {
advance = b.negativeASCII[chTest]
} else if chTest < 0xffff && len(b.negativeUnicode) > 0 {
unicodeLookup = b.negativeUnicode[chTest>>8]
if len(unicodeLookup) > 0 {
advance = unicodeLookup[chTest&0xFF]
} else {
advance = defadv
}
} else {
advance = defadv
}
test += advance
} else { // if (chTest == chMatch)
test2 = test
match = startmatch
for {
if match == endmatch {
if b.rightToLeft {
return test2 + 1
} else {
return test2
}
}
match -= bump
test2 -= bump
chTest = text[test2]
if b.caseInsensitive {
chTest = unicode.ToLower(chTest)
}
if chTest != b.pattern[match] {
advance = b.positive[match]
if (chTest & 0xFF80) == 0 {
test2 = (match - startmatch) + b.negativeASCII[chTest]
} else if chTest < 0xffff && len(b.negativeUnicode) > 0 {
unicodeLookup = b.negativeUnicode[chTest>>8]
if len(unicodeLookup) > 0 {
test2 = (match - startmatch) + unicodeLookup[chTest&0xFF]
} else {
test += advance
break
}
} else {
test += advance
break
}
if b.rightToLeft {
if test2 < advance {
advance = test2
}
} else if test2 > advance {
advance = test2
}
test += advance
break
}
}
}
}
} | [
"func",
"(",
"b",
"*",
"BmPrefix",
")",
"Scan",
"(",
"text",
"[",
"]",
"rune",
",",
"index",
",",
"beglimit",
",",
"endlimit",
"int",
")",
"int",
"{",
"var",
"(",
"defadv",
",",
"test",
",",
"test2",
"int",
"\n",
"match",
",",
"startmatch",
",",
... | // Scan uses the Boyer-Moore algorithm to find the first occurrence
// of the specified string within text, beginning at index, and
// constrained within beglimit and endlimit.
//
// The direction and case-sensitivity of the match is determined
// by the arguments to the RegexBoyerMoore constructor. | [
"Scan",
"uses",
"the",
"Boyer",
"-",
"Moore",
"algorithm",
"to",
"find",
"the",
"first",
"occurrence",
"of",
"the",
"specified",
"string",
"within",
"text",
"beginning",
"at",
"index",
"and",
"constrained",
"within",
"beglimit",
"and",
"endlimit",
".",
"The",
... | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/prefix.go#L640-L744 |
16,387 | dlclark/regexp2 | syntax/prefix.go | IsMatch | func (b *BmPrefix) IsMatch(text []rune, index, beglimit, endlimit int) bool {
if !b.rightToLeft {
if index < beglimit || endlimit-index < len(b.pattern) {
return false
}
return b.matchPattern(text, index)
} else {
if index > endlimit || index-beglimit < len(b.pattern) {
return false
}
return b.matchPattern(text, index-len(b.pattern))
}
} | go | func (b *BmPrefix) IsMatch(text []rune, index, beglimit, endlimit int) bool {
if !b.rightToLeft {
if index < beglimit || endlimit-index < len(b.pattern) {
return false
}
return b.matchPattern(text, index)
} else {
if index > endlimit || index-beglimit < len(b.pattern) {
return false
}
return b.matchPattern(text, index-len(b.pattern))
}
} | [
"func",
"(",
"b",
"*",
"BmPrefix",
")",
"IsMatch",
"(",
"text",
"[",
"]",
"rune",
",",
"index",
",",
"beglimit",
",",
"endlimit",
"int",
")",
"bool",
"{",
"if",
"!",
"b",
".",
"rightToLeft",
"{",
"if",
"index",
"<",
"beglimit",
"||",
"endlimit",
"-... | // When a regex is anchored, we can do a quick IsMatch test instead of a Scan | [
"When",
"a",
"regex",
"is",
"anchored",
"we",
"can",
"do",
"a",
"quick",
"IsMatch",
"test",
"instead",
"of",
"a",
"Scan"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/prefix.go#L747-L761 |
16,388 | dlclark/regexp2 | syntax/prefix.go | String | func (anchors AnchorLoc) String() string {
buf := &bytes.Buffer{}
if 0 != (anchors & AnchorBeginning) {
buf.WriteString(", Beginning")
}
if 0 != (anchors & AnchorStart) {
buf.WriteString(", Start")
}
if 0 != (anchors & AnchorBol) {
buf.WriteString(", Bol")
}
if 0 != (anchors & AnchorBoundary) {
buf.WriteString(", Boundary")
}
if 0 != (anchors & AnchorECMABoundary) {
buf.WriteString(", ECMABoundary")
}
if 0 != (anchors & AnchorEol) {
buf.WriteString(", Eol")
}
if 0 != (anchors & AnchorEnd) {
buf.WriteString(", End")
}
if 0 != (anchors & AnchorEndZ) {
buf.WriteString(", EndZ")
}
// trim off comma
if buf.Len() >= 2 {
return buf.String()[2:]
}
return "None"
} | go | func (anchors AnchorLoc) String() string {
buf := &bytes.Buffer{}
if 0 != (anchors & AnchorBeginning) {
buf.WriteString(", Beginning")
}
if 0 != (anchors & AnchorStart) {
buf.WriteString(", Start")
}
if 0 != (anchors & AnchorBol) {
buf.WriteString(", Bol")
}
if 0 != (anchors & AnchorBoundary) {
buf.WriteString(", Boundary")
}
if 0 != (anchors & AnchorECMABoundary) {
buf.WriteString(", ECMABoundary")
}
if 0 != (anchors & AnchorEol) {
buf.WriteString(", Eol")
}
if 0 != (anchors & AnchorEnd) {
buf.WriteString(", End")
}
if 0 != (anchors & AnchorEndZ) {
buf.WriteString(", EndZ")
}
// trim off comma
if buf.Len() >= 2 {
return buf.String()[2:]
}
return "None"
} | [
"func",
"(",
"anchors",
"AnchorLoc",
")",
"String",
"(",
")",
"string",
"{",
"buf",
":=",
"&",
"bytes",
".",
"Buffer",
"{",
"}",
"\n\n",
"if",
"0",
"!=",
"(",
"anchors",
"&",
"AnchorBeginning",
")",
"{",
"buf",
".",
"WriteString",
"(",
"\"",
"\"",
... | // anchorDescription returns a human-readable description of the anchors | [
"anchorDescription",
"returns",
"a",
"human",
"-",
"readable",
"description",
"of",
"the",
"anchors"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/prefix.go#L863-L896 |
16,389 | dlclark/regexp2 | syntax/replacerdata.go | NewReplacerData | func NewReplacerData(rep string, caps map[int]int, capsize int, capnames map[string]int, op RegexOptions) (*ReplacerData, error) {
p := parser{
options: op,
caps: caps,
capsize: capsize,
capnames: capnames,
}
p.setPattern(rep)
concat, err := p.scanReplacement()
if err != nil {
return nil, err
}
if concat.t != ntConcatenate {
panic(ErrReplacementError)
}
sb := &bytes.Buffer{}
var (
strings []string
rules []int
)
for _, child := range concat.children {
switch child.t {
case ntMulti:
child.writeStrToBuf(sb)
case ntOne:
sb.WriteRune(child.ch)
case ntRef:
if sb.Len() > 0 {
rules = append(rules, len(strings))
strings = append(strings, sb.String())
sb.Reset()
}
slot := child.m
if len(caps) > 0 && slot >= 0 {
slot = caps[slot]
}
rules = append(rules, -replaceSpecials-1-slot)
default:
panic(ErrReplacementError)
}
}
if sb.Len() > 0 {
rules = append(rules, len(strings))
strings = append(strings, sb.String())
}
return &ReplacerData{
Rep: rep,
Strings: strings,
Rules: rules,
}, nil
} | go | func NewReplacerData(rep string, caps map[int]int, capsize int, capnames map[string]int, op RegexOptions) (*ReplacerData, error) {
p := parser{
options: op,
caps: caps,
capsize: capsize,
capnames: capnames,
}
p.setPattern(rep)
concat, err := p.scanReplacement()
if err != nil {
return nil, err
}
if concat.t != ntConcatenate {
panic(ErrReplacementError)
}
sb := &bytes.Buffer{}
var (
strings []string
rules []int
)
for _, child := range concat.children {
switch child.t {
case ntMulti:
child.writeStrToBuf(sb)
case ntOne:
sb.WriteRune(child.ch)
case ntRef:
if sb.Len() > 0 {
rules = append(rules, len(strings))
strings = append(strings, sb.String())
sb.Reset()
}
slot := child.m
if len(caps) > 0 && slot >= 0 {
slot = caps[slot]
}
rules = append(rules, -replaceSpecials-1-slot)
default:
panic(ErrReplacementError)
}
}
if sb.Len() > 0 {
rules = append(rules, len(strings))
strings = append(strings, sb.String())
}
return &ReplacerData{
Rep: rep,
Strings: strings,
Rules: rules,
}, nil
} | [
"func",
"NewReplacerData",
"(",
"rep",
"string",
",",
"caps",
"map",
"[",
"int",
"]",
"int",
",",
"capsize",
"int",
",",
"capnames",
"map",
"[",
"string",
"]",
"int",
",",
"op",
"RegexOptions",
")",
"(",
"*",
"ReplacerData",
",",
"error",
")",
"{",
"... | // NewReplacerData will populate a reusable replacer data struct based on the given replacement string
// and the capture group data from a regexp | [
"NewReplacerData",
"will",
"populate",
"a",
"reusable",
"replacer",
"data",
"struct",
"based",
"on",
"the",
"given",
"replacement",
"string",
"and",
"the",
"capture",
"group",
"data",
"from",
"a",
"regexp"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/replacerdata.go#L27-L87 |
16,390 | dlclark/regexp2 | replace.go | replacementImpl | func replacementImpl(data *syntax.ReplacerData, buf *bytes.Buffer, m *Match) {
for _, r := range data.Rules {
if r >= 0 { // string lookup
buf.WriteString(data.Strings[r])
} else if r < -replaceSpecials { // group lookup
m.groupValueAppendToBuf(-replaceSpecials-1-r, buf)
} else {
switch -replaceSpecials - 1 - r { // special insertion patterns
case replaceLeftPortion:
for i := 0; i < m.Index; i++ {
buf.WriteRune(m.text[i])
}
case replaceRightPortion:
for i := m.Index + m.Length; i < len(m.text); i++ {
buf.WriteRune(m.text[i])
}
case replaceLastGroup:
m.groupValueAppendToBuf(m.GroupCount()-1, buf)
case replaceWholeString:
for i := 0; i < len(m.text); i++ {
buf.WriteRune(m.text[i])
}
}
}
}
} | go | func replacementImpl(data *syntax.ReplacerData, buf *bytes.Buffer, m *Match) {
for _, r := range data.Rules {
if r >= 0 { // string lookup
buf.WriteString(data.Strings[r])
} else if r < -replaceSpecials { // group lookup
m.groupValueAppendToBuf(-replaceSpecials-1-r, buf)
} else {
switch -replaceSpecials - 1 - r { // special insertion patterns
case replaceLeftPortion:
for i := 0; i < m.Index; i++ {
buf.WriteRune(m.text[i])
}
case replaceRightPortion:
for i := m.Index + m.Length; i < len(m.text); i++ {
buf.WriteRune(m.text[i])
}
case replaceLastGroup:
m.groupValueAppendToBuf(m.GroupCount()-1, buf)
case replaceWholeString:
for i := 0; i < len(m.text); i++ {
buf.WriteRune(m.text[i])
}
}
}
}
} | [
"func",
"replacementImpl",
"(",
"data",
"*",
"syntax",
".",
"ReplacerData",
",",
"buf",
"*",
"bytes",
".",
"Buffer",
",",
"m",
"*",
"Match",
")",
"{",
"for",
"_",
",",
"r",
":=",
"range",
"data",
".",
"Rules",
"{",
"if",
"r",
">=",
"0",
"{",
"// ... | // Given a Match, emits into the StringBuilder the evaluated
// substitution pattern. | [
"Given",
"a",
"Match",
"emits",
"into",
"the",
"StringBuilder",
"the",
"evaluated",
"substitution",
"pattern",
"."
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/replace.go#L116-L142 |
16,391 | dlclark/regexp2 | syntax/fuzz.go | Fuzz | func Fuzz(data []byte) int {
sdata := string(data)
tree, err := Parse(sdata, RegexOptions(0))
if err != nil {
return 0
}
// translate it to code
_, err = Write(tree)
if err != nil {
panic(err)
}
return 1
} | go | func Fuzz(data []byte) int {
sdata := string(data)
tree, err := Parse(sdata, RegexOptions(0))
if err != nil {
return 0
}
// translate it to code
_, err = Write(tree)
if err != nil {
panic(err)
}
return 1
} | [
"func",
"Fuzz",
"(",
"data",
"[",
"]",
"byte",
")",
"int",
"{",
"sdata",
":=",
"string",
"(",
"data",
")",
"\n",
"tree",
",",
"err",
":=",
"Parse",
"(",
"sdata",
",",
"RegexOptions",
"(",
"0",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"ret... | // Fuzz is the input point for go-fuzz | [
"Fuzz",
"is",
"the",
"input",
"point",
"for",
"go",
"-",
"fuzz"
] | 7632a260cbaf5e7594fc1544a503456ecd0827f1 | https://github.com/dlclark/regexp2/blob/7632a260cbaf5e7594fc1544a503456ecd0827f1/syntax/fuzz.go#L6-L20 |
16,392 | fhs/gompd | mpd/internal/server/server.go | Listen | func Listen(network, addr string, listening chan bool) {
ln, err := net.Listen(network, addr)
if err != nil {
log.Fatalf("Listen failed: %v\n", err)
os.Exit(1)
}
s := newServer()
go s.broadcastIdleEvents()
listening <- true
for {
conn, err := ln.Accept()
if err != nil {
log.Printf("Accept failed: %v\n", err)
continue
}
go s.handleConnection(textproto.NewConn(conn))
}
} | go | func Listen(network, addr string, listening chan bool) {
ln, err := net.Listen(network, addr)
if err != nil {
log.Fatalf("Listen failed: %v\n", err)
os.Exit(1)
}
s := newServer()
go s.broadcastIdleEvents()
listening <- true
for {
conn, err := ln.Accept()
if err != nil {
log.Printf("Accept failed: %v\n", err)
continue
}
go s.handleConnection(textproto.NewConn(conn))
}
} | [
"func",
"Listen",
"(",
"network",
",",
"addr",
"string",
",",
"listening",
"chan",
"bool",
")",
"{",
"ln",
",",
"err",
":=",
"net",
".",
"Listen",
"(",
"network",
",",
"addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"... | // Listen starts the server on the network network and address addr.
// Once the server has started, a value is sent to listening channel. | [
"Listen",
"starts",
"the",
"server",
"on",
"the",
"network",
"network",
"and",
"address",
"addr",
".",
"Once",
"the",
"server",
"has",
"started",
"a",
"value",
"is",
"sent",
"to",
"listening",
"channel",
"."
] | e9f7b69903c5ed916cfc447488363d709ecd5492 | https://github.com/fhs/gompd/blob/e9f7b69903c5ed916cfc447488363d709ecd5492/mpd/internal/server/server.go#L889-L906 |
16,393 | fhs/gompd | mpd/watcher.go | Subsystems | func (w *Watcher) Subsystems(names ...string) {
w.names <- names
w.consume()
w.conn.noIdle()
} | go | func (w *Watcher) Subsystems(names ...string) {
w.names <- names
w.consume()
w.conn.noIdle()
} | [
"func",
"(",
"w",
"*",
"Watcher",
")",
"Subsystems",
"(",
"names",
"...",
"string",
")",
"{",
"w",
".",
"names",
"<-",
"names",
"\n",
"w",
".",
"consume",
"(",
")",
"\n",
"w",
".",
"conn",
".",
"noIdle",
"(",
")",
"\n",
"}"
] | // Subsystems interrupts watching current subsystems, consumes all
// outstanding values from Event and Error channels, and then
// changes the subsystems to watch for to names. | [
"Subsystems",
"interrupts",
"watching",
"current",
"subsystems",
"consumes",
"all",
"outstanding",
"values",
"from",
"Event",
"and",
"Error",
"channels",
"and",
"then",
"changes",
"the",
"subsystems",
"to",
"watch",
"for",
"to",
"names",
"."
] | e9f7b69903c5ed916cfc447488363d709ecd5492 | https://github.com/fhs/gompd/blob/e9f7b69903c5ed916cfc447488363d709ecd5492/mpd/watcher.go#L103-L107 |
16,394 | fhs/gompd | mpd/watcher.go | Close | func (w *Watcher) Close() error {
w.exit <- true
w.consume()
w.conn.noIdle()
<-w.done // wait for idle to finish and channels to close
// At this point, watch goroutine has ended,
// so it's safe to close connection.
return w.conn.Close()
} | go | func (w *Watcher) Close() error {
w.exit <- true
w.consume()
w.conn.noIdle()
<-w.done // wait for idle to finish and channels to close
// At this point, watch goroutine has ended,
// so it's safe to close connection.
return w.conn.Close()
} | [
"func",
"(",
"w",
"*",
"Watcher",
")",
"Close",
"(",
")",
"error",
"{",
"w",
".",
"exit",
"<-",
"true",
"\n",
"w",
".",
"consume",
"(",
")",
"\n",
"w",
".",
"conn",
".",
"noIdle",
"(",
")",
"\n\n",
"<-",
"w",
".",
"done",
"// wait for idle to fin... | // Close closes Event and Error channels, and the connection to MPD server. | [
"Close",
"closes",
"Event",
"and",
"Error",
"channels",
"and",
"the",
"connection",
"to",
"MPD",
"server",
"."
] | e9f7b69903c5ed916cfc447488363d709ecd5492 | https://github.com/fhs/gompd/blob/e9f7b69903c5ed916cfc447488363d709ecd5492/mpd/watcher.go#L110-L119 |
16,395 | fhs/gompd | mpd/client.go | Close | func (c *Client) Close() (err error) {
if c.text != nil {
c.printfLine("close")
err = c.text.Close()
c.text = nil
}
return
} | go | func (c *Client) Close() (err error) {
if c.text != nil {
c.printfLine("close")
err = c.text.Close()
c.text = nil
}
return
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Close",
"(",
")",
"(",
"err",
"error",
")",
"{",
"if",
"c",
".",
"text",
"!=",
"nil",
"{",
"c",
".",
"printfLine",
"(",
"\"",
"\"",
")",
"\n",
"err",
"=",
"c",
".",
"text",
".",
"Close",
"(",
")",
"\n"... | // Close terminates the connection with MPD. | [
"Close",
"terminates",
"the",
"connection",
"with",
"MPD",
"."
] | e9f7b69903c5ed916cfc447488363d709ecd5492 | https://github.com/fhs/gompd/blob/e9f7b69903c5ed916cfc447488363d709ecd5492/mpd/client.go#L145-L152 |
16,396 | fhs/gompd | mpd/client.go | PlayID | func (c *Client) PlayID(id int) error {
if id < 0 {
return c.Command("playid").OK()
}
return c.Command("playid %d", id).OK()
} | go | func (c *Client) PlayID(id int) error {
if id < 0 {
return c.Command("playid").OK()
}
return c.Command("playid %d", id).OK()
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"PlayID",
"(",
"id",
"int",
")",
"error",
"{",
"if",
"id",
"<",
"0",
"{",
"return",
"c",
".",
"Command",
"(",
"\"",
"\"",
")",
".",
"OK",
"(",
")",
"\n",
"}",
"\n",
"return",
"c",
".",
"Command",
"(",
"... | // PlayID plays the song identified by id. If id is negative, start playing
// at the current position in playlist. | [
"PlayID",
"plays",
"the",
"song",
"identified",
"by",
"id",
".",
"If",
"id",
"is",
"negative",
"start",
"playing",
"at",
"the",
"current",
"position",
"in",
"playlist",
"."
] | e9f7b69903c5ed916cfc447488363d709ecd5492 | https://github.com/fhs/gompd/blob/e9f7b69903c5ed916cfc447488363d709ecd5492/mpd/client.go#L324-L329 |
16,397 | fhs/gompd | mpd/client.go | SeekPos | func (c *Client) SeekPos(pos int, d time.Duration) error {
return c.Command("seek %d %f", pos, d.Seconds()).OK()
} | go | func (c *Client) SeekPos(pos int, d time.Duration) error {
return c.Command("seek %d %f", pos, d.Seconds()).OK()
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"SeekPos",
"(",
"pos",
"int",
",",
"d",
"time",
".",
"Duration",
")",
"error",
"{",
"return",
"c",
".",
"Command",
"(",
"\"",
"\"",
",",
"pos",
",",
"d",
".",
"Seconds",
"(",
")",
")",
".",
"OK",
"(",
")"... | // SeekPos seeks to the position d of the song at playlist position pos. | [
"SeekPos",
"seeks",
"to",
"the",
"position",
"d",
"of",
"the",
"song",
"at",
"playlist",
"position",
"pos",
"."
] | e9f7b69903c5ed916cfc447488363d709ecd5492 | https://github.com/fhs/gompd/blob/e9f7b69903c5ed916cfc447488363d709ecd5492/mpd/client.go#L350-L352 |
16,398 | fhs/gompd | mpd/client.go | SeekSongID | func (c *Client) SeekSongID(id int, d time.Duration) error {
return c.Command("seekid %d %f", id, d.Seconds()).OK()
} | go | func (c *Client) SeekSongID(id int, d time.Duration) error {
return c.Command("seekid %d %f", id, d.Seconds()).OK()
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"SeekSongID",
"(",
"id",
"int",
",",
"d",
"time",
".",
"Duration",
")",
"error",
"{",
"return",
"c",
".",
"Command",
"(",
"\"",
"\"",
",",
"id",
",",
"d",
".",
"Seconds",
"(",
")",
")",
".",
"OK",
"(",
")... | // SeekSongID seeks to the position d of the song identified by id. | [
"SeekSongID",
"seeks",
"to",
"the",
"position",
"d",
"of",
"the",
"song",
"identified",
"by",
"id",
"."
] | e9f7b69903c5ed916cfc447488363d709ecd5492 | https://github.com/fhs/gompd/blob/e9f7b69903c5ed916cfc447488363d709ecd5492/mpd/client.go#L355-L357 |
16,399 | fhs/gompd | mpd/client.go | SeekCur | func (c *Client) SeekCur(d time.Duration, relative bool) error {
if relative {
return c.Command("seekcur %+f", d.Seconds()).OK()
}
return c.Command("seekcur %f", d.Seconds()).OK()
} | go | func (c *Client) SeekCur(d time.Duration, relative bool) error {
if relative {
return c.Command("seekcur %+f", d.Seconds()).OK()
}
return c.Command("seekcur %f", d.Seconds()).OK()
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"SeekCur",
"(",
"d",
"time",
".",
"Duration",
",",
"relative",
"bool",
")",
"error",
"{",
"if",
"relative",
"{",
"return",
"c",
".",
"Command",
"(",
"\"",
"\"",
",",
"d",
".",
"Seconds",
"(",
")",
")",
".",
... | // SeekCur seeks to the position d within the current song.
// If relative is true, then the time is relative to the current playing position. | [
"SeekCur",
"seeks",
"to",
"the",
"position",
"d",
"within",
"the",
"current",
"song",
".",
"If",
"relative",
"is",
"true",
"then",
"the",
"time",
"is",
"relative",
"to",
"the",
"current",
"playing",
"position",
"."
] | e9f7b69903c5ed916cfc447488363d709ecd5492 | https://github.com/fhs/gompd/blob/e9f7b69903c5ed916cfc447488363d709ecd5492/mpd/client.go#L361-L366 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.