func escape(w writer, s string) error {
	i := strings.IndexAny(s, escapedChars)
	for i != -1 {
		if _, err := w.WriteString(s[:i]); err != nil {
			return err
		}
		var esc string
		switch s[i] {
		case '&':
			esc = "&"
		case '\'':
			// "'" is shorter than "'" and apos was not in HTML until HTML5.
			esc = "'"
		case '<':
			esc = "&lt;"
		case '>':
			esc = "&gt;"
		case '"':
			// "&#34;" is shorter than "&quot;".
			esc = "&#34;"
		case '\r':
			esc = "&#13;"
		default:
			panic("unrecognized escape character")
		}
		s = s[i+1:]
		if _, err := w.WriteString(esc); err != nil {
			return err
		}
		i = strings.IndexAny(s, escapedChars)
	}
	_, err := w.WriteString(s)
	return err
}
Exemplo n.º 2
0
// returns nil for empty or invalid messages
func NewIncomingMessage(line string) *IRCMessage {
	var m IRCMessage
	m.cmds = makeCmdMap()
	m.ncmds = makeNCmdMap()
	line = strings.TrimSpace(line)
	if len(line) == 0 { // empty message
		return nil
	}
	m.prefix = ""
	if line[0] == ':' { // we have optional prefix
		fs := strings.IndexAny(line, " ")
		m.prefix = line[1:fs]
		line = line[fs+1:]
	}
	//m.command = strings.Fields(line)[0]
	fc := strings.IndexAny(line, ":")
	if fc != -1 {
		m.command = strings.TrimSpace(line[0:fc])
		m.argument = line[fc+1:]
	} else {
		m.command = line
	}
	if !m.cmds[pureCmd(m.command)] { // not in literal cmds
		if !m.ncmds[pureCmd(m.command)] { // not in numerical cmds
			return nil
		}
	}
	return &m
}
Exemplo n.º 3
0
// validateProjectTaskIdsAndTags ensures that task tags and ids only contain valid characters
func validateProjectTaskIdsAndTags(project *model.Project) []ValidationError {
	errs := []ValidationError{}
	// create a map to hold the task names
	for _, task := range project.Tasks {
		// check task name
		if i := strings.IndexAny(task.Name, model.InvalidCriterionRunes); i == 0 {
			errs = append(errs, ValidationError{
				Message: fmt.Sprintf("task '%v' has invalid name: starts with invalid character %v",
					task.Name, strconv.QuoteRune(rune(task.Name[0])))})
		}
		// check tag names
		for _, tag := range task.Tags {
			if i := strings.IndexAny(tag, model.InvalidCriterionRunes); i == 0 {
				errs = append(errs, ValidationError{
					Message: fmt.Sprintf("task '%v' has invalid tag '%v': starts with invalid character %v",
						task.Name, tag, strconv.QuoteRune(rune(tag[0])))})
			}
			if i := util.IndexWhiteSpace(tag); i != -1 {
				errs = append(errs, ValidationError{
					Message: fmt.Sprintf("task '%v' has invalid tag '%v': tag contains white space",
						task.Name, tag)})
			}
		}
	}
	return errs
}
Exemplo n.º 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
}
Exemplo n.º 5
0
func getDepfileImpl(ss string) (string, error) {
	tss := ss + " "
	if (!strings.Contains(tss, " -MD ") && !strings.Contains(tss, " -MMD ")) || !strings.Contains(tss, " -c ") {
		return "", nil
	}

	mfIndex := strings.Index(ss, " -MF ")
	if mfIndex >= 0 {
		mf := trimLeftSpace(ss[mfIndex+4:])
		if strings.Index(mf, " -MF ") >= 0 {
			return "", fmt.Errorf("Multiple output file candidates in %s", ss)
		}
		mfEndIndex := strings.IndexAny(mf, " \t\n")
		if mfEndIndex >= 0 {
			mf = mf[:mfEndIndex]
		}

		return mf, nil
	}

	outIndex := strings.Index(ss, " -o ")
	if outIndex < 0 {
		return "", fmt.Errorf("Cannot find the depfile in %s", ss)
	}
	out := trimLeftSpace(ss[outIndex+4:])
	if strings.Index(out, " -o ") >= 0 {
		return "", fmt.Errorf("Multiple output file candidates in %s", ss)
	}
	outEndIndex := strings.IndexAny(out, " \t\n")
	if outEndIndex >= 0 {
		out = out[:outEndIndex]
	}
	return stripExt(out) + ".d", nil
}
Exemplo n.º 6
0
// begin prepare the current path to walk through it
func (d *decoder) begin() (err error) {
	d.curr = d.main
	fields := strings.Split(d.field, ".")
	for i, field := range fields {
		b := strings.IndexAny(field, "[")
		if b != -1 {
			// is a array
			e := strings.IndexAny(field, "]")
			if e == -1 {
				return errors.New("formam: bad syntax array")
			}
			d.field = field[:b]
			if d.index, err = strconv.Atoi(field[b+1 : e]); err != nil {
				return errors.New("formam: the index of array not is a number")
			}
			if len(fields) == i+1 {
				return d.end()
			}
			if err = d.walk(); err != nil {
				return
			}
		} else {
			// not is a array
			d.field = field
			d.index = -1
			if len(fields) == i+1 {
				return d.end()
			}
			if err = d.walk(); err != nil {
				return
			}
		}
	}
	return
}
Exemplo n.º 7
0
func BenchmarkStringsIndexAny(b *testing.B) {
	for i := 0; i < b.N; i++ {
		strings.IndexAny(printable, "abcdefghijklmnopqrstuvwxyz")
		strings.IndexAny(printable, " abcdefghijklmnopqrstuvwxyz")
		strings.IndexAny(printable, " ")
	}
}
Exemplo n.º 8
0
func CompareVer(ver1, ver2 string) int {
	ver1 += "."
	ver2 += "."
	res := 0
	s1 := ""
	s2 := ""
	for res == 0 {

		n1 := strings.IndexAny(ver1, ".-")
		n2 := strings.IndexAny(ver2, ".-")

		if n1 > -1 {
			s1 = fmt.Sprintf("%010s", ver1[:n1])
			ver1 = ver1[n1+1:]
		} else {
			s1 = "0000000000"
		}

		if n2 > -1 {
			s2 = fmt.Sprintf("%010s", ver2[:n2])
			ver2 = ver2[n2+1:]
		} else {

			s2 = "0000000000"
		}

		res = strings.Compare(s1, s2)
		if n1 < 0 && n2 < 0 {
			break
		}
	}

	return res
}
Exemplo n.º 9
0
func escape(buf *bytes.Buffer, s string) {
	i := strings.IndexAny(s, escapedChars)
	for i != -1 {
		buf.WriteString(s[0:i])
		var esc string
		switch s[i] {
		case '&':
			esc = "&amp;"
		case '\'':
			esc = "&apos;"
		case '<':
			esc = "&lt;"
		case '>':
			esc = "&gt;"
		case '"':
			esc = "&quot;"
		default:
			panic("unrecognized escape character")
		}
		s = s[i+1:]
		buf.WriteString(esc)
		i = strings.IndexAny(s, escapedChars)
	}
	buf.WriteString(s)
}
Exemplo n.º 10
0
func ExampleIndexAny() {
	fmt.Println(strings.IndexAny("chicken", "aeiouy"))
	fmt.Println(strings.IndexAny("crwth", "aeiouy"))
	// Output:
	// 2
	// -1
}
Exemplo n.º 11
0
// Divide splits a word into its vowels
func Divide(word string, vowels string) (syllables []string) {
	word = strings.ToLower(word)
	var lv, rv, dist int

	for len(word) > 0 {
		lv = strings.IndexAny(word, vowels)
		if lv == -1 {
			syllables = append(syllables, word)
			break
		}

		rv = strings.IndexAny(word[lv+1:], vowels)
		for rv == 0 {
			lv++
			rv = strings.IndexAny(word[lv+1:], vowels)
		}

		if rv == -1 {
			syllables = append(syllables, word)
			break
		}

		dist = ((rv + lv) - lv) / 2
		if dist > -1 {
			syllables = append(syllables, word[:lv+1+dist])
			word = word[lv+1+dist:]
		}
	}

	return
}
Exemplo n.º 12
0
// IndexAny returns the index of the first instance of any Unicode code point from chars in s
// or -1 if no Unicode code point from chars is present in s
func IndexAny(s, chars string) int {
	fmt.Println(strings.IndexAny("chicken", "aeiouy"))    // 2
	fmt.Println(strings.IndexAny("crwth", "aeiouy"))      // -1
	fmt.Println(strings.IndexAny("crwth", "axrrrrrrrr"))  // 1
	fmt.Println(strings.IndexAny("crwth", "acsxxxrrrrr")) // 0
	return strings.IndexAny(s, chars)
}
Exemplo n.º 13
0
func Test_OCRADataInputQuestion(t *testing.T) {
	ocraSuiteFmt := []string{"OCRA-1:HOTP-SHA1-6:Q%v%02d", "OCRA-1:HOTP-SHA1-6:C-Q%v%02d", "OCRA-1:HOTP-SHA1-6:C-Q%v%02d-T1M"}
	key := "12345678"
	questionN := "1234112233445566778899001122334455667788990011223344556677889900"
	questionB := make([]byte, maxOcraSuiteDataInputQuestionLength)
	var question string

	for _, s := range ocraSuiteFmt {
		for i := ' '; i <= '}'; i++ {
			format := string(i)
			for j := 0; j < 200; j++ {
				if format == ocraSuiteDataInputQuestionAlfabetToken {
					io.ReadFull(rand.Reader, questionB)
					question = string(questionB)
				} else {
					question = questionN
				}
				str := strings.ToLower(fmt.Sprintf(s, format, j))
				_, err := GenerateOCRAAdvance(str, key, "", question, "", "", "")
				if err == nil && (strings.IndexAny(strings.ToLower(format), ocraSuiteDataInputQuestionTypeOptions) == -1 ||
					j < minOcraSuiteDataInputQuestionLength || j > maxOcraSuiteDataInputQuestionLength) {
					t.Error("Test fail: Accept illegal OCRA dataInput question format:", str)
				}
				if err != nil && (strings.IndexAny(format, ocraSuiteDataInputQuestionTypeOptions) != -1 &&
					(j >= minOcraSuiteDataInputQuestionLength && j <= maxOcraSuiteDataInputQuestionLength)) {
					t.Error("Test fail: legal OCRA dataInput question format:", str, "wasn't accpeted, error:", err)
				}
			}
		}
	}
}
Exemplo n.º 14
0
func escape(w writer, s string) os.Error {
	i := strings.IndexAny(s, escapedChars)
	for i != -1 {
		if _, err := w.WriteString(s[:i]); err != nil {
			return err
		}
		var esc string
		switch s[i] {
		case '&':
			esc = "&amp;"
		case '\'':
			esc = "&apos;"
		case '<':
			esc = "&lt;"
		case '>':
			esc = "&gt;"
		case '"':
			esc = "&quot;"
		default:
			panic("unrecognized escape character")
		}
		s = s[i+1:]
		if _, err := w.WriteString(esc); err != nil {
			return err
		}
		i = strings.IndexAny(s, escapedChars)
	}
	_, err := w.WriteString(s)
	return err
}
Exemplo n.º 15
0
func (c *Config) read(buf *bufio.Reader) (err error) {
	var section, option string

	for {
		l, err := buf.ReadString('\n') // parse line-by-line
		if len(strings.TrimSpace(l)) == 0 {
			if err == io.EOF {
				break
			} else if err != nil {
				return err
			}
		}

		l = strings.TrimSpace(l)

		// Switch written for readability (not performance)
		switch {
		// Empty line and comments
		case len(l) == 0, l[0] == '#', l[0] == ';':
			continue

		// New section
		case l[0] == '[' && l[len(l)-1] == ']':
			option = "" // reset multi-line value
			section = strings.TrimSpace(l[1 : len(l)-1])
			c.AddSection(section)

		// No new section and no section defined so
		//case section == "":
		//return os.NewError("no section defined")

		// Other alternatives
		default:
			i := strings.IndexAny(l, "=:")

			switch {
			// Option and value
			case i > 0:
				i := strings.IndexAny(l, "=:")
				option = strings.TrimSpace(l[0:i])
				value := strings.TrimSpace(stripComments(l[i+1:]))
				c.AddOption(section, option, value)
			// Continuation of multi-line value
			case section != "" && option != "":

				if MUTI_KEY_IDENTIFIER == string(option[0]) {
					return errors.New("muti key not support muti line")
				}
				prev, _ := c.RawString(section, option)
				value := strings.TrimSpace(stripComments(l))
				c.AddOption(section, option, prev+"\n"+value)

			default:
				return errors.New("could not parse line: " + l)
			}
		}
	}
	return nil
}
Exemplo n.º 16
0
// ParsePattern parses the given router pattern from the given path. A
// valid pattern always starts with a leading "/". Named portions of the
// path are dynamic path segments, of the form :param. They match a
// segment of the path, so they must be preceded by a "/" and followed
// by a "/" or appear at the end of the string.
//
// For example:
//
//	/:name/info
//
// would match /foo/info but not /foo/bar/info.
//
// A catch-all pattern of the form *param may appear at the end of the
// path and matches any number of path segments at the end of the
// pattern. It must be preceded by a "/". The value of a catch-all
// parameter will include a leading "/".
//
// For example:
//
//	/foo/*name
//
// would match /foo/info and /foo/bar/info.
func ParsePattern(p string) (*Pattern, error) {
	if CleanPath(p) != p {
		return nil, fmt.Errorf("pattern is not clean")
	}
	n := 0
	for i := 0; i < len(p); i++ {
		if p[i] == ':' || p[i] == '*' {
			n++
		}
	}
	pat := Pattern{
		static: make([]string, 0, n*2),
		vars:   make([]string, 0, n),
	}

	if !strings.HasPrefix(p, "/") {
		return nil, fmt.Errorf("path must start with /")
	}
	for len(p) > 0 {
		i := strings.IndexAny(p, ":*")
		if i == -1 {
			pat.static = append(pat.static, p)
			break
		}
		if i == 0 {
			panic("unexpected empty path segment")
		}
		pat.static = append(pat.static, p[0:i])
		if p[i-1] != '/' {
			return nil, fmt.Errorf("no / before wildcard segment")
		}
		p = p[i:]
		i = strings.Index(p, "/")
		if i == -1 {
			pat.static = append(pat.static, "")
			pat.vars = append(pat.vars, p[1:])
			pat.catchAll = p[0] == '*'
			break
		}
		if p[0] == '*' {
			return nil, fmt.Errorf("catch-all route not at end of path")
		}
		v := p[1:i]
		if strings.IndexAny(v, ":*") != -1 {
			return nil, fmt.Errorf("no / before wildcard segment")
		}
		pat.static = append(pat.static, "")
		pat.vars = append(pat.vars, v)
		p = p[i:]
	}
	size := 0
	for _, s := range pat.static {
		size += len(s)
	}
	pat.staticSize = size
	return &pat, nil
}
Exemplo n.º 17
0
Arquivo: pathutil.go Projeto: jq/kati
func wildcardGlob(pat string) ([]string, error) {
	// TODO(ukai): use find cache for glob if exists.
	pat = wildcardUnescape(pat)
	pattern := filepath.Clean(pat)
	if pattern != pat {
		// For some reason, go's Glob normalizes
		// foo/../bar to bar.
		i := strings.IndexAny(pattern, "*?[")
		if i < 0 {
			// no wildcard. if any files matched with pattern,
			// return pat.
			_, err := os.Stat(pat)
			if err != nil {
				return nil, nil
			}
			return []string{pat}, nil
		}
		if strings.Contains(pattern[i+1:], "..") {
			// We ask shell to expand a glob to avoid this.
			cmdline := []string{"/bin/sh", "-c", "/bin/ls -d " + pat}
			cmd := exec.Cmd{
				Path: cmdline[0],
				Args: cmdline,
			}
			// Ignore errors.
			out, _ := cmd.Output()
			ws := newWordScanner(out)
			var files []string
			for ws.Scan() {
				files = append(files, string(ws.Bytes()))
			}
			return files, nil
		}
		// prefix + meta + suffix, and suffix doesn't have '..'
		prefix := pattern[:i]
		i = strings.IndexAny(pat, "*?[")
		if i < 0 {
			return nil, fmt.Errorf("wildcard metachar mismatch? pattern=%q pat=%q", pattern, pat)
		}
		oprefix := pat[:i]
		matched, err := filepath.Glob(pattern)
		if err != nil {
			return nil, err
		}
		var files []string
		for _, m := range matched {
			file := oprefix + strings.TrimPrefix(m, prefix)
			_, err := os.Stat(file)
			if err != nil {
				continue
			}
			files = append(files, file)
		}
		return files, nil
	}
	return filepath.Glob(pat)
}
Exemplo n.º 18
0
func (self *Config) read(buf *bufio.Reader) (err os.Error) {
	var section, option string

	for {
		l, err := buf.ReadString('\n') // parse line-by-line
		if err == os.EOF {
			break
		} else if err != nil {
			return err
		}

		l = strings.TrimSpace(l)

		// Switch written for readability (not performance)
		switch {
		// Empty line and comments
		case len(l) == 0, l[0] == '#', l[0] == ';':
			continue

		// Comment (for windows users)
		case len(l) >= 3 && strings.ToLower(l[0:3]) == "rem":
			continue

		// New section
		case l[0] == '[' && l[len(l)-1] == ']':
			option = "" // reset multi-line value
			section = strings.TrimSpace(l[1 : len(l)-1])
			self.AddSection(section)

		// No new section and no section defined so
		//case section == "":
		//return os.NewError("no section defined")

		// Other alternatives
		default:
			i := strings.IndexAny(l, "=:")

			switch {
			// Option and value
			case i > 0:
				i := strings.IndexAny(l, "=:")
				option = strings.TrimSpace(l[0:i])
				value := strings.TrimSpace(stripComments(l[i+1:]))
				self.AddOption(section, option, value)
			// Continuation of multi-line value
			case section != "" && option != "":
				prev, _ := self.RawString(section, option)
				value := strings.TrimSpace(stripComments(l))
				self.AddOption(section, option, prev+"\n"+value)

			default:
				return os.NewError("could not parse line: " + l)
			}
		}
	}
	return nil
}
Exemplo n.º 19
0
func (ifs *IniFileSettings) Put(key, value string) os.Error {
	if strings.IndexAny(key, "=\r\n") > -1 || strings.IndexAny(value, "\r\n") > -1 {
		return newError("either key or value contains at least one of the invalid characters '=\\r\\n'")
	}

	ifs.data[key] = value

	return nil
}
Exemplo n.º 20
0
func tokenize(path string) (tokens []string, verb string) {
	if path == "" {
		return []string{eof}, ""
	}

	const (
		init = iota
		field
		nested
	)
	var (
		st = init
	)
	for path != "" {
		var idx int
		switch st {
		case init:
			idx = strings.IndexAny(path, "/{")
		case field:
			idx = strings.IndexAny(path, ".=}")
		case nested:
			idx = strings.IndexAny(path, "/}")
		}
		if idx < 0 {
			tokens = append(tokens, path)
			break
		}
		switch r := path[idx]; r {
		case '/', '.':
		case '{':
			st = field
		case '=':
			st = nested
		case '}':
			st = init
		}
		if idx == 0 {
			tokens = append(tokens, path[idx:idx+1])
		} else {
			tokens = append(tokens, path[:idx], path[idx:idx+1])
		}
		path = path[idx+1:]
	}

	l := len(tokens)
	t := tokens[l-1]
	if idx := strings.LastIndex(t, ":"); idx == 0 {
		tokens, verb = tokens[:l-1], t[1:]
	} else if idx > 0 {
		tokens[l-1], verb = t[:idx], t[idx+1:]
	}
	tokens = append(tokens, eof)
	return tokens, verb
}
Exemplo n.º 21
0
func ReadConfigFromString(v string) (*config.Config, error) {
	var buf *bufio.Reader = bufio.NewReader(strings.NewReader(v))
	c := config.NewDefault()
	var section, option string
	for {
		l, err := buf.ReadString('\n') // parse line-by-line
		if err == io.EOF {
			break
		} else if err != nil {
			return c, err
		}

		l = strings.TrimSpace(l)

		// Switch written for readability (not performance)
		switch {
		// Empty line and comments
		case len(l) == 0, l[0] == '#', l[0] == ';':
			continue

		// New section
		case l[0] == '[' && l[len(l)-1] == ']':
			option = "" // reset multi-line value
			section = strings.TrimSpace(l[1 : len(l)-1])
			c.AddSection(section)

		// No new section and no section defined so
		//case section == "":
		//return os.NewError("no section defined")

		// Other alternatives
		default:
			i := strings.IndexAny(l, "=:")

			switch {
			// Option and value
			case i > 0:
				i := strings.IndexAny(l, "=:")
				option = strings.TrimSpace(l[0:i])
				value := strings.TrimSpace(stripComments(l[i+1:]))
				c.AddOption(section, option, value)
			// Continuation of multi-line value
			case section != "" && option != "":
				prev, _ := c.RawString(section, option)
				value := strings.TrimSpace(stripComments(l))
				c.AddOption(section, option, prev+"\n"+value)

			default:
				return c, errors.New("could not parse line: " + l)
			}
		}
	}
	return c, nil
}
Exemplo n.º 22
0
Arquivo: ntriples.go Projeto: iand/go
func (ps *NTriplesIO) readTerm(line string, lineno int) (remainder string, term Term, err error) {
	line = strings.TrimLeft(line, Whitespace)

	// Resource
	if line[0] == '<' {
		end := strings.Index(line, ">")
		if end < 0 {
			return "", nil, &NTriplesParseError{"Unterminated resource URI (<...>); '>' character is required", lineno}
		}

		return line[end+1:], NewResource(line[1:end]), nil

		// Blank node
	} else if line[:2] == "_:" {
		end := strings.IndexAny(line, Whitespace)
		if end < 0 {
			return "", nil, &NTriplesParseError{"Unterminated blank node (_:...); delimiting whitespace is required", lineno}
		}

		return line[end+1:], NewNode(line[2:end]), nil

		// Literal
	} else if line[0] == '"' {
		end := strings.Index(line, "\"")
		if end < 0 {
			return "", nil, &NTriplesParseError{"Unterminated literal (\"...\"); '\"' character is required", lineno}
		}

		text := line[1:end]
		line = line[end+1:]

		if line[0] == '@' {
			end = strings.IndexAny(line, Whitespace)
			if end < 0 {
				return "", nil, &NTriplesParseError{"Unterminated language identifier (@...); delimiting whitespace is required", lineno}
			}

			return line[end+1:], NewLiteralWithLanguage(text, line[1:end]), nil

		} else if strings.HasPrefix(line, "^^") {
			remainder, datatype, err := ps.readTerm(line[2:], lineno)
			if err != nil {
				return "", nil, err
			}

			return remainder, NewLiteralWithDatatype(text, datatype), nil
		}

		return line, NewLiteral(text), nil
	}

	return "", nil, &NTriplesParseError{"Invalid term syntax", lineno}
}
Exemplo n.º 23
0
// atoc attempts to coerce the given text into a complex numeric value,
// returning an error if unsuccessful.
func atoc(text string) (complex128, LispError) {
	var zero complex128 = complex(0.0, 0.0)
	if split := strings.IndexRune(text, '@'); split > 0 {
		// <real R> @ <real R>
		reel, err := atof(text[:split])
		if err != nil {
			return zero, err
		}
		imaj, err := atof(text[split+1:])
		if err != nil {
			return zero, err
		}
		return complex(reel, imaj), nil
	} else {
		// <real R> + <ureal R> i | <real R> - <ureal R> i |
		// <real R> + i | <real R> - i |
		// + <ureal R> i | - <ureal R> i |
		// + i | - i
		split := strings.IndexAny(text, "+-")
		if split == -1 {
			// there must be a sign, otherwise lexer messed up
			return zero, NewLispErrorf(ESYNTAX, "invalid number syntax: %s", text)
		} else if split == 0 {
			// see if there is a second sign
			split = strings.IndexAny(text[1:], "+-") + 1
		}
		var err LispError
		var reel float64
		if split > 0 {
			reel, err = atof(text[:split])
			if err != nil {
				return zero, err
			}
		} else {
			reel = 0.0
		}
		var imaj float64
		ip := text[split : len(text)-1]
		if ip == "+" {
			imaj = 1.0
		} else if ip == "-" {
			imaj = -1.0
		} else {
			imaj, err = atof(ip)
			if err != nil {
				return zero, err
			}
		}
		return complex(reel, imaj), nil
	}
	panic("unreachable code")
}
Exemplo n.º 24
0
Arquivo: arch.go Projeto: eqv/usercorn
func (r regList) Less(i, j int) bool {
	inum := strings.IndexAny(r[i].Name, "0123456789")
	jnum := strings.IndexAny(r[j].Name, "0123456789")
	if inum != -1 && jnum != -1 {
		return sortorder.NaturalLess(r[i].Name, r[j].Name)
	} else if inum == -1 && jnum != -1 {
		return true
	} else if jnum == -1 && inum != -1 {
		return false
	} else {
		return strings.Compare(r[i].Name, r[j].Name) == -1
	}
}
Exemplo n.º 25
0
// splitLines splits a string into lines reliably on Windows and non-Windows platforms.
func splitLines(s string) []string {
	start := 0
	var lines []string
	for i := strings.IndexAny(s[start:], "\r\n"); start < len(s) && i != -1; i = strings.IndexAny(s[start:], "\r\n") {
		if !(start+i > 0 && s[start+i] == '\n' && s[start+i-1] == '\r') {
			// avoid creating an extra empty line for \r\n
			lines = append(lines, s[start:start+i])
		}
		start = start + i + 1
	}
	lines = append(lines, s[start:])
	return lines
}
Exemplo n.º 26
0
func (a *Address) parse(s string) error {

	// normalization

	s = strings.TrimSpace(s)

	if len(s) == 0 {
		return errors.New("Address is empty")
	}

	// parsing

	domainStart := 0
	domainEnd := len(s)

	if idx := strings.IndexAny(s, "@"); idx != -1 {
		a.LocalPart = s[0:idx]
		domainStart = idx + 1
	}

	if idx := strings.IndexAny(s, "/"); idx != -1 {
		a.ResourcePart = s[idx+1:]
		domainEnd = idx
	}

	if domainStart != domainEnd {
		a.DomainPart = s[domainStart:domainEnd]
	}

	// validation

	errs := a.validate()

	if a.LocalPart == "" && domainStart != 0 {
		errs = append(errs, errors.New("Localpart is empty"))
	}

	if a.ResourcePart == "" && domainEnd != len(s) {
		errs = append(errs, errors.New("Resourcepart is empty"))
	}

	if len(errs) == 1 {
		return errs[0]
	} else if len(errs) > 1 {
		return fmt.Errorf("Multiple errors: %v", errs)
	}

	return nil
}
Exemplo n.º 27
0
// 对一些堂量的基本检测。
func TestConsts(t *testing.T) {
	a := assert.New(t)

	a.True(version.SemVerValid(Version))
	a.True(len(Name) > 0)
	a.True(is.URL(RepoURL))
	a.True(is.URL(OfficialURL))
	a.True(len(ConfigFilename) > 0).True(strings.IndexAny(ConfigFilename, "/\\") < 0)
	a.True(len(DefaultTitle) > 0)
	a.True(len(DefaultGroupName) > 0).True(strings.IndexAny(DefaultGroupName, "/\\") < 0)
	a.True(len(Profile) > 0).True(strings.IndexAny(Profile, "/\\") < 0)

	tag, err := language.Parse(DefaultLocale)
	a.NotError(err).NotEqual(tag, language.Und)
}
Exemplo n.º 28
0
func parseQuery(m Values, query string) (err error) {
	for query != "" {
		key := query
		if i := strings.IndexAny(key, "&;"); i >= 0 {
			key, query = key[:i], key[i+1:]
		} else {
			query = ""
		}
		if key == "" {
			continue
		}
		value := ""
		if i := strings.Index(key, "="); i >= 0 {
			key, value = key[:i], key[i+1:]
		}
		key, err1 := QueryUnescape(key)
		if err1 != nil {
			if err == nil {
				err = err1
			}
			continue
		}
		value, err1 = QueryUnescape(value)
		if err1 != nil {
			if err == nil {
				err = err1
			}
			continue
		}
		m[key] = append(m[key], value)
	}
	return err
}
Exemplo n.º 29
0
func fromMetaElement(s string) string {
	for s != "" {
		csLoc := strings.Index(s, "charset")
		if csLoc == -1 {
			return ""
		}
		s = s[csLoc+len("charset"):]
		s = strings.TrimLeft(s, " \t\n\f\r")
		if !strings.HasPrefix(s, "=") {
			continue
		}
		s = s[1:]
		s = strings.TrimLeft(s, " \t\n\f\r")
		if s == "" {
			return ""
		}
		if q := s[0]; q == '"' || q == '\'' {
			s = s[1:]
			closeQuote := strings.IndexRune(s, rune(q))
			if closeQuote == -1 {
				return ""
			}
			return s[:closeQuote]
		}

		end := strings.IndexAny(s, "; \t\n\f\r")
		if end == -1 {
			end = len(s)
		}
		return s[:end]
	}
	return ""
}
Exemplo n.º 30
-1
func consumeLine(data []byte, atEOF bool) (advance int, token []byte, err error) {
	advance, token, err = bufio.ScanLines(data, atEOF)
	if advance == 0 && len(token) == 0 {
		return
	}
	tokenString := string(token)
	//Skip empty lines
	if advance == 2 {
		advance, token, err = consumeLine(data[advance:len(data)], atEOF)
		advance = advance + 2
	}
	//Drop lines with comments OR drop line ending with comments
	if strings.IndexAny(tokenString, "/") == 0 {
		storedAdvance := advance
		advance, token, err = consumeLine(data[storedAdvance:len(data)], atEOF)
		advance = advance + storedAdvance
	} else if commentIndex := strings.IndexAny(tokenString, "/"); commentIndex != -1 {
		token = token[0:commentIndex]
	}

	//Remove all spaces
	token = bytes.Map(func(r rune) (newR rune) {
		if unicode.IsSpace(r) {
			newR = -1
		} else {
			newR = r
		}
		return
	}, token)
	return
}