Golang bytes.IndexFunc类(方法)实例源码

下面列出了Golang bytes.IndexFunc 类(方法)源码代码实例,从而了解它的用法。

作者:achand    项目:g   
func ExampleIndexFunc() {
	f := func(c rune) bool {
		return unicode.Is(unicode.Han, c)
	}
	fmt.Println(bytes.IndexFunc([]byte("Hello, 世界"), f))
	fmt.Println(bytes.IndexFunc([]byte("Hello, world"), f))
	// Output:
	// 7
	// -1
}

作者:vro    项目:se   
// TODO:
func (f *File) OffsetLine(ln, start int) (offset int, e error) {
	if start < 0 || start > len(f.b) {
		return 0, memfile.OutOfBounds
	}
	if ln == 0 {
		i := bytes.LastIndex(f.b[:start], []byte("\n"))
		return i + 1, nil
	}
	if ln < 0 {
		i := 0
		return bytes.LastIndexFunc(f.b[:start], func(r rune) bool {
			if r == '\n' {
				if i == ln {
					return true
				}
				i--
			}
			return false
		}) + 1, nil
	}
	i := 0
	va := bytes.IndexFunc(f.b[start:], func(r rune) bool {
		if r == '\n' {
			i++
			if i == ln {
				return true
			}
		}
		return false
	})
	if va != -1 {
		return va + start + 1, nil
	}
	return len(f.b), nil
}

作者:johan-bolmsj    项目:po   
// Trim space from the left.
func (buf *parserBuf) trimSpaceLeft() {
	n := bytes.IndexFunc(buf.bytes, func(r rune) bool { return !unicode.IsSpace(r) })
	if n == -1 {
		n = len(buf.bytes)
	}
	buf.trimBytesLeft(n)
}

作者:npadman    项目:npg   
func (l *LogFile) Add(b []byte) error {
	// Extract the first word --- which will be the command; the rest will be args
	if (l.linenum % l.Size) == l.Rank {
		ndx := bytes.IndexFunc(b, unicode.IsSpace)
		var comm, args string
		if ndx == -1 {
			comm = string(b)
			args = ""
		} else {
			comm = string(b[0:ndx])
			args = string(b[ndx:])
		}
		fmt.Fprintln(l.F, "-->", string(b))
		out, err := exec.Command(comm, args).CombinedOutput()
		if err != nil {
			fmt.Fprintln(l.F, "-->ERROR : ", err)
			fmt.Fprintln(l.F, "-->Output follows :")
		}
		fmt.Fprintln(l.F, string(out))
		fmt.Fprintln(l.F, "-->")
	}
	l.linenum += 1

	return nil
}

作者:qban    项目:dow   
func writeBytesKey(w io.Writer, key []byte) error {
	if len(key) == 0 || bytes.IndexFunc(key, invalidKeyRune) != -1 {
		return ErrInvalidKey
	}
	_, err := w.Write(key)
	return err
}

作者:johnvilsac    项目:golang-stuf   
func indexFunc(s []byte, f func(rune) bool) {
	if i := bytes.IndexFunc(s, f); i == -1 {
		log.Printf("Something controlled by %#v does NOT appear in %s", f, s)
	} else {
		log.Printf("Something controlled by %#v appears at index %d in %s", f, i, s)
	}
}

作者:kisiel    项目:vig   
func IterWords(data []byte, cb func(word []byte)) {
	for {
		i := bytes.IndexFunc(data, IsWord)
		if i == -1 {
			return
		}
		data = data[i:]
		i = bytes.IndexFunc(data, func(r rune) bool {
			return !IsWord(r)
		})
		if i == -1 {
			return
		}
		cb(data[:i])
		data = data[i:]
	}
}

作者:pombredann    项目:syntaxhighligh   
func lastContiguousIndexFunc(s []byte, f func(r rune) bool) int {
	i := bytes.IndexFunc(s, func(r rune) bool {
		return !f(r)
	})
	if i == -1 {
		i = len(s)
	}
	return i - 1
}

作者:qban    项目:dow   
func writeBytesValue(w io.Writer, value []byte) error {
	var err error
	if bytes.IndexFunc(value, needsQuotedValueRune) >= 0 {
		_, err = writeQuotedBytes(w, value)
	} else {
		_, err = w.Write(value)
	}
	return err
}

作者:gitter-badge    项目:alkasi   
func consumeToken(v []byte) (token, rest []byte) {
	notPos := bytes.IndexFunc(v, isNotTokenChar)
	if notPos == -1 {
		return v, nil
	}
	if notPos == 0 {
		return nil, v
	}
	return v[0:notPos], v[notPos:]
}

作者:cwen-code    项目:study-gopk   
/*IndexFunc interprets s as a sequence of UTF-8-encoded Unicode code points.
It returns the byte index in s of the first Unicode code point satisfying f(c), or -1 if none do.*/
func main() {
	s := []byte("123456677")
	f := func(a rune) bool {
		if a > '6' {
			return true
		}
		return false
	}
	fmt.Println(bytes.IndexFunc(s, f))
}

作者:johscheue    项目:kubernete   
// glogBody logs a body output that could be either JSON or protobuf. It explicitly guards against
// allocating a new string for the body output unless necessary. Uses a simple heuristic to determine
// whether the body is printable.
func glogBody(prefix string, body []byte) {
	if glog.V(8) {
		if bytes.IndexFunc(body, func(r rune) bool {
			return r < 0x0a
		}) != -1 {
			glog.Infof("%s:\n%s", prefix, hex.Dump(body))
		} else {
			glog.Infof("%s: %s", prefix, string(body))
		}
	}
}

作者:AntiM    项目:Simple-CSS-Shrinke   
func parseRule(sel []byte, in *bufio.Reader) Item {
	// Clean up the selector.
	sel = bytes.TrimSpace(sel)
	sel = bytes.Replace(sel, []byte{'\t'}, []byte{' '}, -1)
	sel = bytes.Replace(sel, []byte{'\n'}, []byte{' '}, -1)
	for si := bytes.IndexByte(sel, ' '); si != -1; si = bytes.IndexByte(sel[si+2:], ' ') + si + 2 {
		lsi := bytes.IndexFunc(sel[si+1:], func(c rune) bool { return c != ' ' })
		if lsi == -1 {
			// No non-space was found.
			break
		} else if lsi == 0 {
			// The very next character was a non-space.
			continue
		}
		copy(sel[si+1:], sel[si+lsi+1:])
		sel = sel[:len(sel)-lsi]
	}
	sel = bytes.Replace(sel, []byte{',', ' '}, []byte{','}, -1)
	sel = bytes.Replace(sel, []byte{' ', ','}, []byte{','}, -1)
	sel = bytes.Replace(sel, []byte{'>', ' '}, []byte{'>'}, -1)
	sel = bytes.Replace(sel, []byte{' ', '>'}, []byte{'>'}, -1)

	// Read the body portion.
	body, _ := in.ReadBytes('}')
	// Clean up the body.
	body = bytes.TrimSpace(body[:len(body)-1])

	if len(body) == 0 {
		// This rule doesn't do anything.  It's useless.  No need to
		// include it in the output.
		return nil
	}

	// Create the slice of pairs to store in the rule.  (This slice will be
	// extended as necessary.)
	pairs := make([]pair, 0)

	// Iterate over the directives in the body.
	for _, p := range bytes.Split(body, []byte{';'}) {
		// Clean up the pair.
		p = bytes.TrimSpace(p)
		i := bytes.Index(p, []byte{':'})
		if i == -1 {
			// Hmm.  There's no colon in this pair.  Something's wrong.
			// We'll just silently omit it.
			continue
		}

		// Extend our slice of pairs with the new directive.
		pairs = append(pairs, pair{bytes.TrimSpace(p[:i]), bytes.TrimSpace(p[i+1:])})
	}

	return &rule{sel, pairs}
}

作者:ryochac    项目:gore   
// Charactor code 0x00 - 0x08 is control code (ASCII)
func verifyBinary(buf []byte) bool {
	var b []byte
	if len(buf) > 256 {
		b = buf[:256]
	} else {
		b = buf
	}
	if bytes.IndexFunc(b, func(r rune) bool { return r < 0x09 }) != -1 {
		return true
	}
	return false
}

作者:danuxgui    项目:dxne   
func StringCutRune(str string, n int) string {

	b := []byte(str)
	i := 0
	index := bytes.IndexFunc(b, func(r rune) bool {
		i++

		if i > n {
			return true
		}

		return false
	})

	if index < 0 {
		return str
	}
	return string(b[:index])
}

作者:speedat    项目:publishe   
func tokenizeXML(data []byte, atEOF bool) (advance int, token []byte, err error) {
	var tcomment = []byte{'<', '!', '-', '-'}
	if bytes.HasPrefix(data, tcomment) {
		return len(tcomment), tcomment, nil
	}
	r, size := utf8.DecodeRune(data)
	if unicode.IsSpace(r) {
		return size, data[:size], nil
	}
	if data[0] == '<' || data[0] == '>' {
		return 1, data[:1], nil
	}
	if data[0] == '/' && data[1] == '>' {
		return 2, data[:2], nil
	}
	num := bytes.IndexFunc(data, nameboundary)
	if num > 0 {
		return num, data[:num], nil
	}
	return 1, data[:1], nil
}

作者:sneha29shukl    项目:mi   
// Import parses the contents of a libotr private key file.
func (priv *PrivateKey) Import(in []byte) bool {
	mpiStart := []byte(" #")

	mpis := make([]*big.Int, 5)

	for i := 0; i < len(mpis); i++ {
		start := bytes.Index(in, mpiStart)
		if start == -1 {
			return false
		}
		in = in[start+len(mpiStart):]
		end := bytes.IndexFunc(in, notHex)
		if end == -1 {
			return false
		}
		hexBytes := in[:end]
		in = in[end:]

		if len(hexBytes)&1 != 0 {
			return false
		}

		mpiBytes := make([]byte, len(hexBytes)/2)
		if _, err := hex.Decode(mpiBytes, hexBytes); err != nil {
			return false
		}

		mpis[i] = new(big.Int).SetBytes(mpiBytes)
	}

	priv.PrivateKey.P = mpis[0]
	priv.PrivateKey.Q = mpis[1]
	priv.PrivateKey.G = mpis[2]
	priv.PrivateKey.Y = mpis[3]
	priv.PrivateKey.X = mpis[4]
	priv.PublicKey.PublicKey = priv.PrivateKey.PublicKey

	a := new(big.Int).Exp(priv.PrivateKey.G, priv.PrivateKey.X, priv.PrivateKey.P)
	return a.Cmp(priv.PrivateKey.Y) == 0
}

作者:thotanagaraj    项目:hu   
func getWord(b []byte, pos *filePos) (string, []byte) {
	// Skip over leading whitespace
	i := 0
	for i < len(b) {
		r, size := utf8.DecodeRune(b[i:])
		if r == '\n' {
			pos.line++
		}
		if !unicode.IsSpace(r) {
			break
		}
		i += size
	}
	b = b[i:]

	// Find end of word
	i = bytes.IndexFunc(b, unicode.IsSpace)
	if i < 0 {
		i = len(b)
	}
	return string(b[0:i]), b[i:]
}

作者:iol    项目:golangdo   
func (p *PackageInfo) comment_format(comment, indent, preIndent string) string {
	containsOnlySpace := func(buf []byte) bool {
		isNotSpace := func(r rune) bool { return !unicode.IsSpace(r) }
		return bytes.IndexFunc(buf, isNotSpace) == -1
	}
	var buf bytes.Buffer
	const punchCardWidth = 80
	ToText(&buf, comment, indent, preIndent, punchCardWidth-2*len(indent))
	if containsOnlySpace(buf.Bytes()) {
		return ""
	}
	lines := strings.Split(buf.String(), "\n")
	if len(lines) > 0 && lines[len(lines)-1] == "" {
		lines = lines[:len(lines)-1]
	}
	for i := 0; i < len(lines); i++ {
		if lines[i] == "" || lines[i][0] != '\t' {
			lines[i] = "// " + lines[i]
		} else {
			lines[i] = "//" + lines[i]
		}
	}
	return strings.Join(lines, "\n")
}

作者:matt    项目:w   
func whitespace(src []byte) []byte {
	// remove needless comments
	for {
		pos := bytes.IndexFunc(src, func(r rune) bool {
			return r != ' ' && r != '\t' && r != '\n'
		})
		if pos < 0 {
			break
		}
		if pos == 0 {
			src = src[1:]
		} else {
			src = append(src[:pos], src[pos+1:]...)
		}
	}

	// parse whitespace into tokens
	tokens := opcodes{}
	for len(src) > 0 {
		op := ""
		code := Nop
		for k, v := range optable {
			if bytes.HasPrefix(src, []byte(k)) {
				op = k
				code = v
				break
			}
		}
		if op == "" {
			src = src[1:]
			continue
		}
		src = src[len(op):]
		var arg int
		switch code {
		case Push:
			// handle argument
		handle_signed_arg:
			for i := 1; i < len(src); i++ {
				switch src[i] {
				case ' ':
					arg = (arg << 1) | 0
				case '\t':
					arg = (arg << 1) | 1
				case '\n':
					// Push take singed argument
					if src[0] == '\t' {
						arg = -arg
					}
					src = src[i+1:]
					break handle_signed_arg
				}
			}
		case Mark, Call, Jump, Jz, Jn:
			// handle argument
		handle_unsigned_arg:
			for i := 0; i < len(src); i++ {
				switch src[i] {
				case ' ':
					arg = (arg << 1) | 0
				case '\t':
					arg = (arg << 1) | 1
				case '\n':
					src = src[i+1:]
					break handle_unsigned_arg
				}
			}
		}
		tokens = append(tokens, opcode{code, arg})
	}

	pc := 0
	ps := stack{}
	cs := stack{}
	heap := map[int]int{}
	for {
		token := tokens[pc]

		code, arg := token.code, token.arg
		//fmt.Println(pc, code, arg)
		pc++
		switch code {
		case Push:
			ps.push(arg)
		case Mark:
		case Dup:
			ps.dup()
		case OutN:
			fmt.Print(ps.pop())
		case OutC:
			fmt.Print(string(rune(ps.pop())))
		case Add:
			rhs := ps.pop()
			lhs := ps.pop()
			ps.push(lhs + rhs)
		case Sub:
			rhs := ps.pop()
			lhs := ps.pop()
			ps.push(lhs - rhs)
		case Mul:
//.........这里部分代码省略.........


问题


面经


文章

微信
公众号

扫码关注公众号