Example #1
0
func New(str string) JID {
	// TODO(skriptble): Implement RFC7622
	var local, domain, resource string

	domain = str
	slash := strings.IndexByte(domain, '/')
	if slash != -1 {
		resource = domain[slash+1:]
		domain = domain[:slash]
	}

	at := strings.IndexByte(domain, '@')
	if at != -1 {
		local = domain[:at]
		domain = domain[at+1:]
	}

	local = parseLocal(local)
	domain = parseDomain(domain)
	resource = parseResource(resource)

	if len([]byte(local)) > 1024 || len([]byte(domain)) > 1024 || len([]byte(resource)) > 1024 {
		return Empty
	}

	return JID{
		local:    local,
		domain:   domain,
		resource: resource,
	}
}
Example #2
0
File: enc.go Project: llir/llvm
// escape replaces any characters which are not valid in identifiers with
// corresponding hexadecimal escape sequence (\XX).
func escape(s string) string {
	// Check if a replacement is required.
	extra := 0
	for i := 0; i < len(s); i++ {
		if strings.IndexByte(tail, s[i]) == -1 {
			// Two extra bytes are required for each invalid byte; e.g.
			//    "#" -> `\23`
			//    "世" -> `\E4\B8\96`
			extra += 2
		}
	}
	if extra == 0 {
		return s
	}

	// Replace invalid characters.
	const hextable = "0123456789ABCDEF"
	buf := make([]byte, len(s)+extra)
	j := 0
	for i := 0; i < len(s); i++ {
		b := s[i]
		if strings.IndexByte(tail, b) != -1 {
			buf[j] = b
			j++
			continue
		}
		buf[j] = '\\'
		buf[j+1] = hextable[b>>4]
		buf[j+2] = hextable[b&0x0F]
		j += 3
	}
	return string(buf)
}
Example #3
0
// Unquote interprets s as a single-quoted, double-quoted,
// or backquoted Go string literal, returning the string value
// that s quotes. For example: test=`"\"\n"` (hex: 22 5c 22 5c 6e 22)
// should be converted to `"\n` (hex: 22 0a).
func Unquote(s string) (t string, err error) {
	n := len(s)
	if n < 2 {
		return "", errors.Trace(ErrSyntax)
	}
	quote := s[0]
	if quote != s[n-1] {
		return "", errors.Trace(ErrSyntax)
	}
	s = s[1 : n-1]
	if quote != '"' && quote != '\'' {
		return "", errors.Trace(ErrSyntax)
	}
	// Avoid allocation. No need to convert if there is no '\'
	if strings.IndexByte(s, '\\') == -1 && strings.IndexByte(s, quote) == -1 {
		return s, nil
	}
	buf := make([]byte, 0, 3*len(s)/2) // Try to avoid more allocations.
	for len(s) > 0 {
		mb, ss, err := UnquoteChar(s, quote)
		if err != nil {
			return "", errors.Trace(err)
		}
		s = ss
		buf = append(buf, mb...)
	}
	return string(buf), nil
}
Example #4
0
func main() {
	fmt.Println(strings.Index("Hello, world!", "He"))  // 0: He가 맨 처음에 있으므로 0
	fmt.Println(strings.Index("Hello, world!", "wor")) // 7: wor가 8번째에 있으므로 7
	fmt.Println(strings.Index("Hello, world!", "ow"))  // -1: ow는 없으므로 -1

	fmt.Println(strings.IndexAny("Hello, world!", "eo")) // 1: e가 2번째에 있으므로 1
	fmt.Println(strings.IndexAny("Hello, world!", "f"))  // -1: f는 없으므로 -1

	var c byte
	c = 'd'
	fmt.Println(strings.IndexByte("Hello, world!", c)) // 11: d가 12번째에 있으므로 11
	c = 'f'
	fmt.Println(strings.IndexByte("Hello, world!", c)) // -1: f는 없으므로 -1

	var r rune
	r = '언'
	fmt.Println(strings.IndexRune("고 언어", r)) // 4: "언"이 시작되는 인덱스가 4

	f := func(r rune) bool {
		return unicode.Is(unicode.Hangul, r) // r이 한글 유니코드이면 true를 리턴
	}
	fmt.Println(strings.IndexFunc("Go 언어", f))       // 3: 한글이 4번째부터 시작하므로 3
	fmt.Println(strings.IndexFunc("Go Language", f)) // -1: 한글이 없으므로 -1

	fmt.Println(strings.LastIndex("Hello Hello Hello, world!", "Hello"))
	// 12: 마지막 Hello가 13번째에 있으므로 12

	fmt.Println(strings.LastIndexAny("Hello, world", "ol")) // 10: 마지막 l이 11번째에 있으므로 10

	fmt.Println(strings.LastIndexFunc("Go 언어 안녕", f)) // 13: 마지막 한글인 '녕'이 시작되는 인덱스가 13
}
Example #5
0
// Parse user information from string
// format: nick!user@hostname
// Taken from: https://github.com/sorcix/irc
// All credit for this function goes to github user sorcix
func ParsePrefix(prefix string) *Prefix {
	p := new(Prefix)

	user := strings.IndexByte(prefix, '!')
	host := strings.IndexByte(prefix, '@')

	switch {
	case user > 0 && host > user:
		p.Name = prefix[:user]
		p.User = prefix[user+1 : host]
		p.Host = prefix[host+1:]

	case user > 0:
		p.Name = prefix[:user]
		p.User = prefix[user+1:]

	case host > 0:
		p.Name = prefix[:host]
		p.Host = prefix[host+1:]

	default:
		p.Name = prefix
	}

	return p
}
Example #6
0
// unpackKey extracts key, index and remainder of the key.
// It returns "", "", "" for error.
func unpackKey(s string) (interface{}, string) {
	if s == "" {
		return nil, ""
	}
	if s[0] == '.' {
		s = s[1:]
	}
	dot := strings.IndexByte(s, '.')
	open := strings.IndexByte(s, '[')
	switch {
	case dot == -1 && open == -1:
		return s, ""
	case dot != -1 && (open == -1 || dot < open):
		return s[:dot], s[dot:]
	case open != -1 && (dot == -1 || open < dot):
		if open > 0 {
			return s[:open], s[open:]
		}
		close := strings.IndexByte(s, ']')
		if close == -1 {
			return nil, ""
		}
		n, err := strconv.Atoi(s[1:close])
		if err != nil {
			return nil, ""
		}
		return n, s[close+1:]
	default: // Cannot happen
		return nil, ""
	}
}
Example #7
0
/*
 * parse a query string to symlist_t struct , string format should be:
 * nmq=testmq&mac=xxxx&bootid=xxxx...
 */
func QueryToSymlist(query string) (symlist *SymList, err error) {
	var middle int = 0
	var end int = 0
	data := query
	for {
		middle = strings.IndexByte(data, '=')
		if middle == -1 {
			break
		}

		end = strings.IndexByte(data[middle:], '&')
		if end == -1 {
			if symlist == nil {
				symlist, _ = NewSymlist(data[:middle], data[middle+1:], STRING)
			} else {
				symlist, _ = AppendSymlistString(symlist, data[:middle], data[middle+1:])
			}
			break
		} else {
			if symlist == nil {
				symlist, _ = NewSymlist(data[:middle], data[middle+1:middle+end], STRING)
			} else {
				symlist, _ = AppendSymlistString(symlist, data[:middle], data[middle+1:middle+end])
			}
			data = data[middle+end+1:]
		}
	}
	return symlist, err
}
Example #8
0
func parsePart(part string) (k, v, rest string, err error) {
	// `key=value;otherKey=otherValue`
	// `key="value";otherKey=otherValue`
	idx := strings.IndexByte(part, '=')
	if idx < 0 {
		err = strconv.ErrSyntax
		return
	}

	k, v = part[0:idx], part[idx+1:]
	// k=`key`, v=`value;otherKey=otherValue`
	// k=`key`, v=`"value";otherKey=otherValue`
	if len(v) > 0 && v[0] == '"' {
		v, rest, err = unquote(v)
		if err != nil {
			return
		}
	} else {
		idx = strings.IndexByte(v, ';')
		if idx >= 0 {
			v, rest = v[0:idx], v[idx+1:]
		}
	}

	if len(rest) > 0 && rest[0] == ';' {
		rest = rest[1:]
	}

	return
}
Example #9
0
// parsePAXRecord parses the input PAX record string into a key-value pair.
// If parsing is successful, it will slice off the currently read record and
// return the remainder as r.
//
// A PAX record is of the following form:
//	"%d %s=%s\n" % (size, key, value)
func parsePAXRecord(s string) (k, v, r string, err error) {
	// The size field ends at the first space.
	sp := strings.IndexByte(s, ' ')
	if sp == -1 {
		return "", "", s, ErrHeader
	}

	// Parse the first token as a decimal integer.
	n, perr := strconv.ParseInt(s[:sp], 10, 0) // Intentionally parse as native int
	if perr != nil || n < 5 || int64(len(s)) < n {
		return "", "", s, ErrHeader
	}

	// Extract everything between the space and the final newline.
	rec, nl, rem := s[sp+1:n-1], s[n-1:n], s[n:]
	if nl != "\n" {
		return "", "", s, ErrHeader
	}

	// The first equals separates the key from the value.
	eq := strings.IndexByte(rec, '=')
	if eq == -1 {
		return "", "", s, ErrHeader
	}
	return rec[:eq], rec[eq+1:], rem, nil
}
Example #10
0
func (n *treenode) addParamNode(pattern string) (*treenode, *stringList, bool) {
	i := strings.IndexByte(pattern, byte('{'))
	if i >= 0 {
		node, paramNames := n.addNode(pattern[:i])
		pattern = pattern[i+1:]
		i := strings.IndexByte(pattern, byte('}'))
		if i < 0 {
			panic("invalid route syntax: {" + pattern)
		}

		nc := strings.Split(pattern[:i], ":") // split {name:constraint}
		name := strings.TrimSpace(nc[0])
		constraint := ""
		if len(nc) > 1 {
			constraint = strings.TrimSpace(strings.Join(nc[1:], ""))
		}
		pn := node.addParamChild(constraint)
		paramNames = addItem(paramNames, name)
		pattern = pattern[i+1:]
		if len(pattern) == 0 {
			return pn, paramNames, true
		}

		node, paramNames = pn.addNode(pattern)
		paramNames = addItem(paramNames, name)
		return node, paramNames, true
	}
	return nil, nil, false
}
Example #11
0
File: strutil.go Project: jq/kati
func substRef(pat, repl, str string) string {
	if strings.IndexByte(pat, '%') >= 0 && strings.IndexByte(repl, '%') >= 0 {
		return substPattern(pat, repl, str)
	}
	str = strings.TrimSuffix(str, pat)
	return str + repl
}
Example #12
0
// ServerParseAddr parses the listening addr and returns this
func ServerParseAddr(listeningAddr string) string {
	// check if addr has :port, if not do it +:80 ,we need the hostname for many cases
	a := listeningAddr
	if a == "" {
		// check for os environments
		if oshost := os.Getenv("HOST"); oshost != "" {
			a = oshost
		} else if oshost := os.Getenv("ADDR"); oshost != "" {
			a = oshost
		} else if osport := os.Getenv("PORT"); osport != "" {
			a = ":" + osport
		}

		if a == "" {
			a = DefaultServerAddr
		}

	}
	if portIdx := strings.IndexByte(a, ':'); portIdx == 0 {
		// if contains only :port	,then the : is the first letter, so we dont have setted a hostname, lets set it
		a = DefaultServerHostname + a
	}
	if portIdx := strings.IndexByte(a, ':'); portIdx < 0 {
		// missing port part, add it
		a = a + ":80"
	}

	return a
}
Example #13
0
// Parses the second call's parameters in a stack trace of the form:
//
// goroutine 1 [running]:
// main.printInputs(0x4c4c60, 0x539038)
//	/.../go/src/debug/main.go:16 +0xe0
// main.Test1(0x2)                       <---- parsed
//	/.../go/src/debug/main.go:23
//
//	Returns the function name and the parameter values, e.g.:
//
//		("main.Test1", [0x2])
//
func parseParams(st string) (string, []uintptr) {

	line := 1
	start, stop := 0, 0
	for i, c := range st {
		if c == '\n' {
			line++
		}
		if line == 4 && c == '\n' {
			start = i + 1
		}
		if line == 5 && c == '\n' {
			stop = i
		}
	}

	call := st[start:stop]
	fname := call[0:strings.IndexByte(call, '(')]
	param := call[strings.IndexByte(call, '(')+1 : strings.IndexByte(call, ')')]
	params := strings.Split(param, ", ")
	parsedParams := make([]uintptr, len(params))

	for i := range params {
		iv, err := strconv.ParseInt(params[i], 0, 64)

		if err != nil {
			panic(err.Error())
		}

		parsedParams[i] = uintptr(iv)
	}

	return fname, parsedParams
}
Example #14
0
// compare compares two version strings. compare returns -1 if v1 < v2, 1 if v1
// > v2, 0 otherwise.
//
// Non-numeric segments in either argument are considered equal, so
// compare("1.a", "1.b") == 0, but compare("2.a", "1.b") == 1.
func compare(v1, v2 string) int {
	if n := strings.IndexByte(v1, '-'); n != -1 {
		v1 = v1[:n]
	}
	if n := strings.IndexByte(v2, '-'); n != -1 {
		v2 = v2[:n]
	}
	var (
		currTab  = strings.Split(v1, ".")
		otherTab = strings.Split(v2, ".")
	)

	max := len(currTab)
	if len(otherTab) > max {
		max = len(otherTab)
	}
	for i := 0; i < max; i++ {
		var currInt, otherInt int

		if len(currTab) > i {
			currInt, _ = strconv.Atoi(currTab[i])
		}
		if len(otherTab) > i {
			otherInt, _ = strconv.Atoi(otherTab[i])
		}
		if currInt > otherInt {
			return 1
		}
		if otherInt > currInt {
			return -1
		}
	}
	return 0
}
Example #15
0
// ParsePrefix takes a string and attempts to create a Prefix struct.
func ParsePrefix(raw string) (p *Prefix) {

	p = new(Prefix)

	user := strings.IndexByte(raw, prefixUser)
	host := strings.IndexByte(raw, prefixHost)

	switch {

	case user > 0 && host > user:
		p.Name = raw[:user]
		p.User = raw[user+1 : host]
		p.Host = raw[host+1:]

	case user > 0:
		p.Name = raw[:user]
		p.User = raw[user+1:]

	case host > 0:
		p.Name = raw[:host]
		p.Host = raw[host+1:]

	default:
		p.Name = raw

	}

	return p
}
Example #16
0
func parseToKVPair(s string) (key string, value string, err error) {

	re := regexp.MustCompile(`^[0-9a-zA-Z@:/_-]`)
	if !re.MatchString(s) {
		err = fmt.Errorf("Invalid key-value identity: %s", s)
		return
	}

	colon := strings.IndexByte(s, byte(':'))
	atsign := strings.IndexByte(s, byte('@'))
	if colon >= 0 {
		key = s[0:colon]
		value = s[(colon + 1):]
		if len(value) >= 2 && value[0:2] == "//" {
			value = value[2:]
		}
	} else if atsign >= 0 {
		value = s[0:atsign]
		key = s[(atsign + 1):]
	} else {
		value = s
	}
	key = strings.ToLower(key)
	value = strings.ToLower(value)
	return
}
Example #17
0
// UnescapeString unescapes entities like "&lt;" to become "<". It unescapes a
// larger range of entities than EscapeString escapes. For example, "&aacute;"
// unescapes to "á", as does "&#225;" and "&xE1;".
// UnescapeString(EscapeString(s)) == s always holds, but the converse isn't
// always true.
func UnescapeString(s string) string {
	i := strings.IndexByte(s, '&')

	if i < 0 {
		return s
	}

	b := []byte(s)
	dst, src := unescapeEntity(b, i, i)
	for len(s[src:]) > 0 {
		if s[src] == '&' {
			i = 0
		} else {
			i = strings.IndexByte(s[src:], '&')
		}
		if i < 0 {
			dst += copy(b[dst:], s[src:])
			break
		}

		if i > 0 {
			copy(b[dst:], s[src:src+i])
		}
		dst, src = unescapeEntity(b, dst+i, src+i)
	}
	return string(b[:dst])
}
Example #18
0
// html_to_txt extracts text that browser displays from html source.
func html_to_txt(s string) string {
	for {
		scriptopen := strings.Index(s, "<script")
		scriptclose := strings.Index(s, "</script>")
		if scriptopen == -1 || scriptclose == -1 {
			break
		}
		s = s[:scriptopen] + s[scriptclose+len("</script>"):]
	}
	for {
		tagopen := strings.IndexByte(s, '<')
		tagclose := strings.IndexByte(s, '>')
		if tagopen == -1 || tagclose == -1 || tagopen > len(s) ||
			tagclose > len(s) {
			break
		}
		if tagopen > tagclose {
			fmt.Printf("something wrong: %d %d %s\n",
				tagopen, tagclose, s[tagclose:tagclose+200])
			os.Exit(1)
			break
		}

		s = s[:tagopen] + s[tagclose+1:]
	}
	return s
}
Example #19
0
func parsePortSpec(addr string) (string, int, int, error) {
	i := strings.IndexByte(addr, ':')
	portPart := ""
	fdPart := ""

	if i < 0 {
		portPart = addr
		addr = ""
	} else {
		portPart = addr[i+1:]
		addr = addr[:i]
	}

	j := strings.IndexByte(portPart, '=')
	if j > 0 {
		fdPart = portPart[j+1:]
		portPart = portPart[:j]
	}

	port, err := strconv.ParseInt(portPart, 10, 64)
	if err != nil {
		return "", -1, -1, err
	}

	if fdPart == "" {
		return addr, int(port), -1, nil
	} else {
		fd, err := strconv.ParseInt(fdPart, 10, 64)
		if err != nil {
			return addr, int(port), -1, err
		}
		return addr, int(port), int(fd), nil
	}
}
Example #20
0
func parseHtpasswd(pm map[string]PasswordMatcher, r io.Reader) error {
	scanner := bufio.NewScanner(r)
	for scanner.Scan() {
		line := strings.TrimSpace(scanner.Text())
		if line == "" || strings.IndexByte(line, '#') == 0 {
			continue
		}
		i := strings.IndexByte(line, ':')
		if i <= 0 {
			return fmt.Errorf("malformed line, no color: %q", line)
		}
		user, encoded := line[:i], line[i+1:]
		for _, p := range basic.DefaultSystems {
			matcher, err := p(encoded)
			if err != nil {
				return err
			}
			if matcher != nil {
				pm[user] = matcher.MatchesPassword
				break
			}
		}
	}
	return scanner.Err()
}
Example #21
0
func goType(cType string) (name string, bitSize int, arrayLength int) {
	name = dry.StringReplaceMulti(cType,
		"_t", "",
		"_mavlink_version", "",
		"char", "byte",
		"float", "float32",
		"double", "float64")
	if index := strings.IndexByte(name, '['); index != -1 {
		arrayLength, _ = strconv.Atoi(name[index+1 : len(name)-1])
		name = name[index:] + name[:index]
	}
	if strings.HasSuffix(name, "byte") {
		bitSize = 8
		if arrayLength > 0 {
			name = fmt.Sprintf("Char%d", arrayLength)
		}
	} else {
		t := name[strings.IndexByte(name, ']')+1:]
		if sizeStart := strings.IndexAny(t, "8136"); sizeStart != -1 {
			bitSize, _ = strconv.Atoi(t[sizeStart:])
		}
		if bitSize == 0 {
			panic("Unknown message field size")
		}
	}
	return name, bitSize, arrayLength
}
Example #22
0
// Set implements flag.Value.
func (t *Target) Set(val string) error {
	index := strings.IndexByte(val, '@')
	if index > -1 {
		t.version = val[index+1:]
		val = val[:index]
	}
	index = strings.IndexByte(val, '=')
	tag := ""
	if index > -1 {
		tag = val[0:index]
		val = val[index+1:]
	} else {
		if strings.IndexByte(val, '-') < 0 {
			t.tag = val
			t.arch = ""
			t.opsys = ""
			t.isSet = true
			return nil
		}
	}
	parts := strings.Split(val, "-")
	if len(parts) != 2 || (len(parts[0]) == 0 || len(parts[1]) == 0) {
		return fmt.Errorf("%q doesn't look like [tag=]<arch>-<os>", val)
	}
	t.tag = tag
	t.arch = parts[0]
	t.opsys = parts[1]
	t.isSet = true
	return nil
}
Example #23
0
func hashKey(key string) string {
	if s := strings.IndexByte(key, '{'); s > -1 {
		if e := strings.IndexByte(key[s+1:], '}'); e > 0 {
			return key[s+1 : s+e+1]
		}
	}
	return key
}
Example #24
0
// CanonicalURL constructs a URL from the given scheme, host, and port,
// excluding default port numbers.
func CanonicalURL(scheme, host string, port int) string {
	if strings.IndexByte(host, ':') >= 0 || strings.IndexByte(host, '%') >= 0 {
		host = "[" + host + "]"
	}
	if defaultPorts[scheme] == port {
		return fmt.Sprintf("%s://%s", scheme, host)
	}
	return fmt.Sprintf("%s://%s:%d", scheme, host, port)
}
Example #25
0
// splitParamPattern splits the given pattern string just before the first occurence of a
// variable or catch-all indicator, if any, and returns the two resulting strings.
func splitParamPattern(pattern string) (string, string) {
	if i := strings.IndexByte(pattern, '{'); i != -1 {
		return pattern[:i], pattern[i:]
	}
	if i := strings.IndexByte(pattern, '*'); i != -1 {
		return pattern[:i], pattern[i:]
	}
	return pattern, ""
}
Example #26
0
// Analyze an address for its malfunctions
// TODO: do this better in a more structured way.
func getAddrOpts(a string, c *Context) (o Option) {
	if a == "" {
		return
	}
	idx := strings.IndexByte(a, '@')
	if idx == -1 {
		o |= oNoat
	} else {
		// We don't necessarily do everything right in the presence
		// of route addresses.
		if idx == 0 {
			idx2 := strings.IndexByte(a[1:], '@')
			// This is '@something' as an address, which is a
			// big fat FAIL.
			if idx2 == -1 {
				o |= oGarbage
			} else {
				o |= oRoute
			}
		}
		idx2 := strings.IndexByte(a[idx+1:], '.')
		if idx2 == -1 {
			o |= oUnqualified
		}
	}
	// Look for trailing craziness
	lp := len(a) - 1
	if a[0] == '<' || a[lp] == '>' || a[lp] == '"' || a[lp] == ']' || a[lp] == '.' || idx == lp {
		o |= oGarbage
	}
	// general crazy things
	if strings.Contains(a, "..") || strings.Contains(a, "@@") {
		o |= oGarbage
	}

	idx3 := strings.IndexByte(a, '"')
	if idx3 != -1 && idx3 != lp {
		o |= oQuoted
	}

	if o&(oNoat|oUnqualified|oGarbage|oRoute) == 0 {
		dom := a[idx+1:]
		valid := c.validDomain(dom)
		switch valid.d {
		case dnsGood:
			o |= oDomainValid
		case dnsBad:
			o |= oDomainInvalid
			c.domerr = fmt.Errorf("domain %s: %s", dom, valid.e)
		case dnsTempfail:
			o |= oDomainTempfail
			c.domerr = fmt.Errorf("domain %s: %s", dom, valid.e)
		}
	}
	return
}
Example #27
0
func stripPort(hostport string) string {
	colon := strings.IndexByte(hostport, ':')
	if colon == -1 {
		return hostport
	}
	if i := strings.IndexByte(hostport, ']'); i != -1 {
		return strings.TrimPrefix(hostport[:i], "[")
	}
	return hostport[:colon]
}
Example #28
0
func hexDigit(c byte) int {
	if i := strings.IndexByte(hex, c); i >= 0 {
		return i
	}

	if i := strings.IndexByte(Hex, c); i >= 0 {
		return i
	}

	return -1
}
Example #29
0
func has_illegal_letter(password string) bool {
	if strings.IndexByte(password, 'i') != -1 {
		return true
	}
	if strings.IndexByte(password, 'o') != -1 {
		return true
	}
	if strings.IndexByte(password, 'l') != -1 {
		return true
	}
	return false
}
Example #30
0
func initLocal() {
	d := js.Global.Get("Date").New()
	s := d.Str()
	i := strings.IndexByte(s, '(')
	j := strings.IndexByte(s, ')')
	if i == -1 || j == -1 {
		localLoc.name = "UTC"
		return
	}
	localLoc.name = s[i+1 : j]
	localLoc.zone = []zone{{localLoc.name, d.Call("getTimezoneOffset").Int() * -60, false}}
}