本文整理汇总了Golang中bytes.IndexRune函数的典型用法代码### 示例。如果您正苦于以下问题:Golang IndexRune函数的具体用法?Golang IndexRune怎么用?Golang IndexRune使用的例子?那么恭喜您, 这里精选的函数代码### 示例或许可以为您提供帮助。

在下文中一共展示了IndexRune函数的20个代码### 示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码### 示例。

示例1: getLoad

func getLoad() string {

    switch runtime.GOOS {
    case "windows": // ...
        return "Windows"
    case "linux": // ...
        cmd := exec.Command("cat", "/proc/loadavg")
        bs, err := cmd.Output()
        if err != nil {
            return "top error"
        }
        offset := bytes.IndexRune(bs, '\n')
        if offset < 1 {
            offset = len(bs)
        }
        return string(bs[:offset])
    case "freebsd": // ...
        return "freebsd"
    case "darwin": // ...
        cmd := exec.Command("sysctl", "-n", "vm.loadavg")
        bs, err := cmd.Output()
        if err != nil {
            return "top error"
        }
        offset := bytes.IndexRune(bs, '\n')
        if offset < 1 {
            offset = len(bs)
        }
        return string(bs[:offset])
    }
    return "dunno!"

}

开发者ID:rputbl,项目名称:rputn-srv,代码行数:33,代码来源:rputn-srv.go

示例2: statLeds

func statLeds(oC *tCommand) {
    const kLeds = "/sys/class/leds/"
    aList, _ := ioutil.ReadDir(kLeds)
    const kFields = "%-15s%-11s%-10s%-10s%s\n"

lRestart:
    oC.buf = []byte(fmt.Sprintf(kFields, "Device", "Brightness", "Delay_on", "Delay_off", "Trigger"))

    for _, a := range aList {
        aBright, _ := ioutil.ReadFile(kLeds + a.Name() + "/brightness")
        aTriggr, _ := ioutil.ReadFile(kLeds + a.Name() + "/trigger")
        aBright = aBright[:len(aBright)-1]
        aTriggr = aTriggr[bytes.IndexRune(aTriggr, '[')+1 : bytes.IndexRune(aTriggr, ']')]
        var aDelayOn, aDelayOff []byte
        if bytes.Equal(aTriggr, []byte("timer")) {
            aDelayOn, _ = ioutil.ReadFile(kLeds + a.Name() + "/delay_on")
            aDelayOff, _ = ioutil.ReadFile(kLeds + a.Name() + "/delay_off")
            if len(aDelayOn) == 0 || len(aDelayOff) == 0 {
                goto lRestart
            }
            aDelayOn = aDelayOn[:len(aDelayOn)-1]
            aDelayOff = aDelayOff[:len(aDelayOff)-1]
        } else {
            aDelayOn = []byte("--")
            aDelayOff = aDelayOn
        }
        oC.buf = append(oC.buf, fmt.Sprintf(kFields, a.Name(), aBright, aDelayOn, aDelayOff, aTriggr)...)
    }
    if sDebug {
        fmt.Println(oC.name)
    }
}

开发者ID:networkimprov,项目名称:info-anvl,代码行数:32,代码来源:info.go

示例3: ExampleIndexRune

func ExampleIndexRune() {
    fmt.Println(bytes.IndexRune([]byte("chicken"), 'k'))
    fmt.Println(bytes.IndexRune([]byte("chicken"), 'd'))
    // Output:
    // 4
    // -1
}

开发者ID:achanda,项目名称:go,代码行数:7,代码来源:example_test.go

示例4: NonMatchOneOrMore

/**
 * Lexer::NonMatchOneOrMore
 */
func (l *lexer) NonMatchOneOrMore(match []byte) bool {
    var r rune
    if r = l.PeekRune(0); r != RuneEOF && bytes.IndexRune(match, r) == -1 {
        l.NextRune()
        for r = l.PeekRune(0); r != RuneEOF && bytes.IndexRune(match, r) == -1; r = l.PeekRune(0) {
            l.NextRune()
        }
        return true
    }
    return false
}

开发者ID:scottfranklin,项目名称:go_lexer,代码行数:14,代码来源:impl.go

示例5: MatchOneOrMoreBytes

// Lexer::MatchOneOrMoreBytes
func (l *lex) MatchOneOrMoreBytes(match []byte) bool {
    var r rune
    if r = l.PeekRune(0); r != RuneEOF && bytes.IndexRune(match, r) >= 0 {
        l.NextRune()
        for r = l.PeekRune(0); r != RuneEOF && bytes.IndexRune(match, r) >= 0; r = l.PeekRune(0) {
            l.NextRune()
        }
        return true
    }
    return false
}

开发者ID:jbowles,项目名称:lexer,代码行数:12,代码来源:impl.go

示例6: ReadConfig

func ReadConfig() (accesskey string, secret string, err error) {
    homedir := os.Getenv("HOME")
    if homedir == "" {
        u, err := user.Current()
        if err != nil {
            return "", "", err
        }
        homedir = u.HomeDir
    }
    cfg, err := ioutil.ReadFile(homedir + "/.s3cfg")
    if err != nil {
        return
    }

    for off := 0; off != -1; off = bytes.IndexRune(cfg, '\n') {
        line := cfg[:off]
        cfg = cfg[off+1:]
        tokens := bytes.SplitN(line, []byte(" = "), 2)
        if len(tokens) != 2 {
            continue
        }
        switch string(tokens[0]) {
        case "access_key":
            accesskey = string(tokens[1])
        case "secret_key":
            secret = string(tokens[1])
        }
    }
    return
}

开发者ID:bsiegert,项目名称:s3upload,代码行数:30,代码来源:s3upload.go

示例7: Fire

// Fire implements logrus.Hook interface
func (h *Hook) Fire(entry *logrus.Entry) error {
    p := bytes.TrimSpace([]byte(entry.Message))
    short := bytes.NewBuffer(p)
    full := ""
    if i := bytes.IndexRune(p, '\n'); i > 0 {
        full = short.String()
        short.Truncate(i)
    }
    extra := map[string]interface{}{}
    // merge entry.Data & extra & facility
    for k, v := range entry.Data {
        extra["_"+k] = v // prefix with _ will be treated as an additional field
    }
    for k, v := range h.extra {
        extra["_"+k] = v // prefix with _ will be treated as an additional field
    }
    extra["_facility"] = h.facility

    m := &gelf.Message{
        Version:  "1.1",
        Host:     h.hostname,
        Short:    short.String(),
        Full:     full,
        TimeUnix: float64(now().UnixNano()) / 1e9,
        Level:    int32(entry.Level),
        Extra:    extra,
    }
    return h.w.WriteMessage(m)
}

开发者ID:solefaucet,项目名称:sole-server,代码行数:30,代码来源:graylog_hook.go

示例8: assertionFilter

func assertionFilter(r rune) rune {
    // wish that base64.go exported this publicly:
    if bytes.IndexRune([]byte("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_~.="), r) < 0 {
        return rune(-1)
    }
    return r
}

开发者ID:michielbdejong,项目名称:FindMyDevice,代码行数:7,代码来源:utils.go

示例9: translateWithoutSametypesequence

func (d Dictionary) translateWithoutSametypesequence(data []byte) (items []*TranslationItem) {
    var dataPos int
    dataSize := len(data)

    for {
        t := data[dataPos]

        dataPos++

        switch t {
        case 'm', 'l', 'g', 't', 'x', 'y', 'k', 'w', 'h', 'r':
            end := bytes.IndexRune(data[dataPos:], '\000')

            if end < 0 { // last item
                items = append(items, &TranslationItem{Type: rune(t), Data: data[dataPos:dataSize]})
                dataPos = dataSize
            } else {
                items = append(items, &TranslationItem{Type: rune(t), Data: data[dataPos : dataPos+end+1]})
                dataPos += end + 1
            }
        case 'W', 'P':
            size := binary.BigEndian.Uint32(data[dataPos : dataPos+4])
            items = append(items, &TranslationItem{Type: rune(t), Data: data[dataPos+4 : dataPos+int(size)+5]})
            dataPos += int(size) + 5
        }

        if dataPos >= dataSize {
            break
        }
    }

    return
}

开发者ID:dyatlov,项目名称:gostardict,代码行数:33,代码来源:dictionary.go

示例10: MatchOneBytes

// Lexer::MatchOneBytes
func (l *lex) MatchOneBytes(match []byte) bool {
    if r := l.PeekRune(0); r != RuneEOF && bytes.IndexRune(match, r) >= 0 {
        l.NextRune()
        return true
    }
    return false
}

开发者ID:jbowles,项目名称:lexer,代码行数:8,代码来源:impl.go

示例11: ScrambleBytes

// Modifies `s` in-place.
func ScrambleBytes(s []byte) []byte {
    isArray := len(s) >= 2 && s[0] == '{' && s[len(s)-1] == '}'

    hash := sha256.New()
    // Hard-coding this constant wins less than 3% in BenchmarkScrambleBytes
    const sumLength = 32 // SHA256/8
    hash.Write(Salt)
    hash.Write(s)
    sumBytes := hash.Sum(nil)

    reader := bytes.NewReader(s)
    var r rune
    var err error
    for i := 0; ; i++ {
        r, _, err = reader.ReadRune()
        if err != nil {
            s = s[:i]
            break
        }
        if !isArray || bytes.IndexRune(bytesKeep, r) == -1 {
            // Do not insert, so should not obstruct reader.
            s[i] = bytesOutputAlphabet[(sumBytes[i%sumLength]+byte(r))%bytesOutputAlphabetLength]
        } else {
            // Possibly shift bytes to beginning of s.
            s[i] = byte(r)
        }
    }
    return s
}

开发者ID:ostrovok-team,项目名称:pgdump-obfuscator,代码行数:30,代码来源:obfuscators.go

示例12: lex

/**
 * lex is the starting StateFn for lexing the input into tokens
 */
func lex(l lexer.Lexer) lexer.StateFn {
    // EOF
    if l.MatchEOF() {
        l.EmitEOF()
        return nil // We're done here
    }

    // Skip whitespace
    if l.MatchOneOrMoreBytes(bytesWhitespace) {
        l.IgnoreToken()
    }

    // Single-char token?
    if i := bytes.IndexRune(singleChars, l.PeekRune(0)); i >= 0 {
        l.NextRune()
        l.EmitToken(singleTokens[i])
        return lex
    }

    // Quote
    if l.MatchOneRune('"') {
        l.EmitToken(T_OPEN_QUOTE)
        return lexQuotedString

        // Unquoted String
    } else if l.MatchOneBytes(bytesAlpha) && l.MatchZeroOrMoreBytes(bytesAlphaNum) {
        l.EmitTokenWithBytes(T_UNQUOTED_STRING)

        // Number:  /-?(0|([1-9][0-9]*))(\.[0-9]+)?([eE][-+]?[0-9]+)?/
    } else if m := matcher.New(l); m.
        MatchZeroOrOneRune('-').                     // -?      // Leading '-' (optional)
        And().Begin().                               // (       // Begin Integer (required)
        MatchOneRune('0').                           // 0       //   0 is stand alone, unsigned
        Or().Begin().                                // |(      //   Begin non-zero
        MatchOneBytes(bytes1to9).                    // [1-9]   //     First digit - No leading 0's (required)
        And().MatchZeroOrMoreBytes(bytesDigits).     // [0-9]*  //     Extra digits (optional)
        End().MatchOne().                            // )       //   End non-zero
        End().MatchOne().                            // )       // End Integer
        And().Begin().                               // (       // Begin Fraction (optional)
        MatchOneRune('.').                           // \.      //   Decimal '.' (required)
        And().MatchOneOrMoreBytes(bytesDigits).      // [0-9]+  //   Digits (required)
        End().MatchZeroOrOne().                      // )?      // End Fraction
        And().Begin().                               // (       // Begin Exponent (optional)
        MatchOneBytes([]byte{'e', 'E'}).             // [eE]    //   'e' | 'E' (required)
        And().MatchZeroOrOneBytes([]byte{'-', '+'}). // [-+]?   //   Sign (optional)
        And().MatchOneOrMoreBytes(bytesDigits).      // [0-9]+  //   Digits (required)
        End().MatchZeroOrOne().                      //  )?     // End Exponent
        Result() {
        l.EmitTokenWithBytes(T_NUMBER)
        return lex

        // Unknown
    } else {
        l.NextRune() // Consume unknown rune
        l.EmitTokenWithBytes(T_UNKNOWN)
    }

    // See you again soon!
    return lex
}

开发者ID:iNamik,项目名称:go_lexer_matcher,代码行数:63,代码来源:json_decoder.go

示例13: translateWithSametypesequence

func (d Dictionary) translateWithSametypesequence(data []byte) (items []*TranslationItem) {
    seq := d.info.Options["sametypesequence"]

    seqLen := len(seq)

    var dataPos int
    dataSize := len(data)

    for i, t := range seq {
        switch t {
        case 'm', 'l', 'g', 't', 'x', 'y', 'k', 'w', 'h', 'r':
            // if last seq item
            if i == seqLen-1 {
                items = append(items, &TranslationItem{Type: t, Data: data[dataPos:dataSize]})
            } else {
                end := bytes.IndexRune(data[dataPos:], '\000')
                items = append(items, &TranslationItem{Type: t, Data: data[dataPos : dataPos+end+1]})
                dataPos += end + 1
            }
        case 'W', 'P':
            if i == seqLen-1 {
                items = append(items, &TranslationItem{Type: t, Data: data[dataPos:dataSize]})
            } else {
                size := binary.BigEndian.Uint32(data[dataPos : dataPos+4])
                items = append(items, &TranslationItem{Type: t, Data: data[dataPos+4 : dataPos+int(size)+5]})
                dataPos += int(size) + 5
            }
        }
    }

    return
}

开发者ID:dyatlov,项目名称:gostardict,代码行数:32,代码来源:dictionary.go

示例14: indexRune

func indexRune(s []byte, r rune) {
    if i := bytes.IndexRune(s, r); i == -1 {
        log.Printf("Rune %d does NOT appear in %s", r, s)
    } else {
        log.Printf("Rune %d appears at index %d in %s", r, i, s)
    }
}

开发者ID:johnvilsack,项目名称:golang-stuff,代码行数:7,代码来源:searching.go

示例15: ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    w.Header().Add(wwwAuthenticate, fmt.Sprintf("Basic realm=\"%s\"", *realm))

    _, data, err := splitAuth(r.Header.Get(authorization))
    if err != nil {
        w.WriteHeader(401)
        return
    }

    t := time.Now()
    k := string(data)
    e, ex := cache[k]
    if ex && e.valid && t.Before(e.until) {
        w.WriteHeader(200)
        return
    }

    i := bytes.IndexRune(data, ':')
    if i < 0 {
        w.WriteHeader(401)
        return
    }
    username, password := string(data[:i]), string(data[i+1:])
    valid, err := s.authenticate(username, password)
    if valid {
        cache[k] = &entry{valid: true, until: t.Add(*ttl)}
        w.WriteHeader(200)
    } else {
        w.WriteHeader(401)
    }
}

开发者ID:presbrey,项目名称:nginx-auth-request-ldap,代码行数:31,代码来源:main.go

示例16: copyBinary

func copyBinary(sourceName, targetName, sourceDir, targetDir string) error {
    source := filepath.Join(sourceDir, sourceName)
    dest := filepath.Join(targetDir, targetName)
    if _, err := os.Stat(source); err != nil {
        if os.IsNotExist(err) {
            return fmt.Errorf("missing file %s", source)
        }
        return err
    }
    if err := CopyFile(source, dest, 0755); err != nil {
        return err
    }
    if b, err := ioutil.ReadFile(source + ".sha256"); err == nil {
        if i := bytes.IndexRune(b, ' '); i > 0 {
            b = b[:i]
        }
        expectedHash := make([]byte, hex.DecodedLen(len(b)))
        if _, err := hex.Decode(expectedHash, b); err != nil {
            return err
        }
        if err := hashCheck(dest, expectedHash, sha256.New()); err != nil {
            return err
        }
    }

    return nil
}

开发者ID:dmcgowan,项目名称:dockerdevtools,代码行数:27,代码来源:copy.go

示例17: Decode

func (dec *Decoder) Decode(msg *Message) error {
    r, rsize, err := dec.ReadRune()
    if err != nil {
        return err
    }

    if r == 0xFFFD && rsize == 3 {
        // the payload has multiple messages,
        // let's consume the first.
        // read frame length
        data := dec.Bytes()
        index := bytes.IndexRune(data, 0xFFFD)
        if index <= 0 {
            return errors.New("frame length is empty or missing")
        }
        length := positiveInt(data[:index])
        if length < 0 {
            return errors.New("frame length is not a positive integer")
        }
        data = data[index+rsize:]
        if len(data) < length {
            return errors.New("frame length is overflowing")
        }
        dec.Next(index + rsize + length)
        return decodePacket(data[:length], msg)
    }

    // rollback and read single entirely
    dec.UnreadRune()

    data := dec.Bytes()
    dec.Reset()
    return decodePacket(data, msg)
    return err
}

开发者ID:jacobxk,项目名称:go-socket.io,代码行数:35,代码来源:codec.go

示例18: NonMatchOne

/**
 * Lexer::NonMatchOne
 */
func (l *lexer) NonMatchOne(match []byte) bool {
    if r := l.PeekRune(0); r != RuneEOF && bytes.IndexRune(match, r) == -1 {
        l.NextRune()
        return true
    }
    return false
}

开发者ID:scottfranklin,项目名称:go_lexer,代码行数:10,代码来源:impl.go

示例19: Parse

// Parse parses the given array of bytes and returns key-value map.
func (p *LineParser) Parse(b []byte) (map[string][]byte, error) {
    m := make(map[string][]byte)
    for i := 0; i < len(b); {
        nextDelim := bytes.IndexRune(b[i:], p.Delimiter)
        if nextDelim < 0 {
            return nil, errors.New("failed to parse, the delimiter is not found")
        }
        key := b[i : i+nextDelim]
        i += nextDelim + 1

        nextLn := bytes.IndexByte(b[i:], '\n')
        if nextLn < 0 {
            return nil, errors.New("failed to parse, the end of line is not found")
        }
        val := b[i : i+nextLn]
        if p.TrimSpaces {
            val = bytes.TrimSpace(val)
        }
        if p.TrimQuotes {
            val = bytes.TrimFunc(val, isQuotationMark)
        }
        m[string(key)] = val
        i += nextLn + 1
    }
    return m, nil
}

开发者ID:harukasan,项目名称:orchestra-pit,代码行数:27,代码来源:lineParser.go

示例20: acceptRunMin

// acceptRunMin consumes a run of runes from the valid set, returning
// true if a minimum number of runes where consumed.
func (l *lexer) acceptRunMin(valid []byte, num int) bool {
    c := 0
    for bytes.IndexRune(valid, l.next()) >= 0 {
        c++
    }
    l.backup()
    return c >= num
}

开发者ID:postfix,项目名称:rdf,代码行数:10,代码来源:lex.go

最后编辑: kuteng  文档更新时间: 2021-08-23 19:14   作者:kuteng