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

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

示例1: TestAttachmentOnly

func TestAttachmentOnly(t *testing.T) {
    var aTests = []struct {
        filename       string
        attachmentsLen int
        inlinesLen     int
    }{
        {filename: "attachment-only.raw", attachmentsLen: 1, inlinesLen: 0},
        {filename: "attachment-only-inline.raw", attachmentsLen: 0, inlinesLen: 1},
    }

    for _, a := range aTests {
        // Mail with disposition attachment
        msg := readMessage(a.filename)
        m, err := ParseMIMEBody(msg)
        if err != nil {
            t.Fatal("Failed to parse MIME:", err)
        }
        if len(m.Attachments) != a.attachmentsLen {
            t.Fatal("len(Attachments) got:", len(m.Attachments), "want:", a.attachmentsLen)
        }
        if a.attachmentsLen > 0 &&
            !bytes.HasPrefix(m.Attachments[0].Content(), []byte{0x89, 'P', 'N', 'G'}) {
            t.Error("Content should be PNG image")
        }
        if len(m.Inlines) != a.inlinesLen {
            t.Fatal("len(Inlines) got:", len(m.Inlines), "want:", a.inlinesLen)
        }
        if a.inlinesLen > 0 &&
            !bytes.HasPrefix(m.Inlines[0].Content(), []byte{0x89, 'P', 'N', 'G'}) {
            t.Error("Content should be PNG image")
        }
    }
}

开发者ID:jhillyerd,项目名称:go.enmime,代码行数:33,代码来源:mail_test.go

示例2: parseFunctionKey

func (t *tScreen) parseFunctionKey(buf *bytes.Buffer) (bool, bool) {
    b := buf.Bytes()
    partial := false
    for e, k := range t.keycodes {
        esc := []byte(e)
        if (len(esc) == 1) && (esc[0] == '\x1b') {
            continue
        }
        if bytes.HasPrefix(b, esc) {
            // matched
            var r rune
            if len(esc) == 1 {
                r = rune(b[0])
            }
            mod := k.mod
            if t.escaped {
                mod |= ModAlt
                t.escaped = false
            }
            ev := NewEventKey(k.key, r, mod)
            t.PostEvent(ev)
            for i := 0; i < len(esc); i++ {
                buf.ReadByte()
            }
            return true, true
        }
        if bytes.HasPrefix(esc, b) {
            partial = true
        }
    }
    return partial, false
}

开发者ID:gdamore,项目名称:tcell,代码行数:32,代码来源:tscreen.go

示例3: rangeAddressing

// rangeAddressing updates or deletes the range addressing metadata
// for the range specified by desc. The action to take is specified by
// the supplied metaAction function.
//
// The rules for meta1 and meta2 records are as follows:
//
//  1. If desc.StartKey or desc.EndKey is meta1:
//     - ERROR
//  2. If desc.EndKey is meta2:
//     - meta1(desc.EndKey)
//  3. If desc.EndKey is normal user key:
//     - meta2(desc.EndKey)
//     3a. If desc.StartKey is KeyMin or meta2:
//         - meta1(KeyMax)
func rangeAddressing(b *client.Batch, desc *roachpb.RangeDescriptor, action metaAction) error {
    // 1. handle illegal case of start or end key being meta1.
    if bytes.HasPrefix(desc.EndKey, keys.Meta1Prefix) ||
        bytes.HasPrefix(desc.StartKey, keys.Meta1Prefix) {
        return errors.Errorf("meta1 addressing records cannot be split: %+v", desc)
    }

    // Note that both cases 2 and 3 are handled by keys.RangeMetaKey.
    //
    // 2. the case of the range ending with a meta2 prefix. This means
    // the range is full of meta2. We must update the relevant meta1
    // entry pointing to the end of this range.
    //
    // 3. the range ends with a normal user key, so we must update the
    // relevant meta2 entry pointing to the end of this range.
    action(b, keys.RangeMetaKey(desc.EndKey), desc)

    if !bytes.HasPrefix(desc.EndKey, keys.Meta2Prefix) {
        // 3a. the range starts with KeyMin or a meta2 addressing record,
        // update the meta1 entry for KeyMax.
        if bytes.Equal(desc.StartKey, roachpb.RKeyMin) ||
            bytes.HasPrefix(desc.StartKey, keys.Meta2Prefix) {
            action(b, keys.Meta1KeyMax, desc)
        }
    }
    return nil
}

开发者ID:CubeLite,项目名称:cockroach,代码行数:41,代码来源:addressing.go

示例4: TestAttachmentOnly

func TestAttachmentOnly(t *testing.T) {
    var aTests = []struct {
        filename       string
        attachmentsLen int
        inlinesLen     int
    }{
        {filename: "attachment-only.raw", attachmentsLen: 1, inlinesLen: 0},
        {filename: "attachment-only-inline.raw", attachmentsLen: 0, inlinesLen: 1},
    }

    for _, a := range aTests {
        // Mail with disposition attachment
        msg := readMessage(a.filename)
        m, err := ParseMIMEBody(msg)
        assert.Equal(t, err, nil)
        assert.Equal(t, a.attachmentsLen, len(m.Attachments))
        assert.Equal(t, a.inlinesLen, len(m.Inlines))
        if a.attachmentsLen > 0 {
            assert.True(t, bytes.HasPrefix(m.Attachments[0].Content(), []byte{0x89, 'P', 'N', 'G'}),
                "Content should be PNG image")
        }
        if a.inlinesLen > 0 {
            assert.True(t, bytes.HasPrefix(m.Inlines[0].Content(), []byte{0x89, 'P', 'N', 'G'}),
                "Content should be PNG image")
        }
    }
}

开发者ID:davrux,项目名称:go.enmime,代码行数:27,代码来源:mail_test.go

示例5: WalkPrefix

// WalkPrefix is used to walk the tree under a prefix
func (n *Node) WalkPrefix(prefix []byte, fn WalkFn) {
    search := prefix
    for {
        // Check for key exhaution
        if len(search) == 0 {
            recursiveWalk(n, fn)
            return
        }

        // Look for an edge
        _, n = n.getEdge(search[0])
        if n == nil {
            break
        }

        // Consume the search prefix
        if bytes.HasPrefix(search, n.prefix) {
            search = search[len(n.prefix):]

        } else if bytes.HasPrefix(n.prefix, search) {
            // Child may be under our search prefix
            recursiveWalk(n, fn)
            return
        } else {
            break
        }
    }
}

开发者ID:vektra,项目名称:gdata,代码行数:29,代码来源:node.go

示例6: decodeResponseCacheKey

func (rc *ResponseCache) decodeResponseCacheKey(encKey engine.MVCCKey) ([]byte, error) {
    key, _, isValue, err := engine.MVCCDecodeKey(encKey)
    if err != nil {
        return nil, err
    }
    if isValue {
        return nil, util.Errorf("key %s is not a raw MVCC value", encKey)
    }
    if !bytes.HasPrefix(key, keys.LocalRangeIDPrefix) {
        return nil, util.Errorf("key %s does not have %s prefix", key, keys.LocalRangeIDPrefix)
    }
    // Cut the prefix and the Range ID.
    b := key[len(keys.LocalRangeIDPrefix):]
    b, _, err = encoding.DecodeUvarint(b)
    if err != nil {
        return nil, err
    }
    if !bytes.HasPrefix(b, keys.LocalResponseCacheSuffix) {
        return nil, util.Errorf("key %s does not contain the response cache suffix %s",
            key, keys.LocalResponseCacheSuffix)
    }
    // Cut the response cache suffix.
    b = b[len(keys.LocalResponseCacheSuffix):]
    // Decode the family.
    b, fm, err := encoding.DecodeBytes(b, nil)
    if err != nil {
        return nil, err
    }
    if len(b) > 0 {
        return nil, util.Errorf("key %s has leftover bytes after decode: %s; indicates corrupt key",
            encKey, b)
    }
    return fm, nil
}

开发者ID:xujun10110,项目名称:cockroach,代码行数:34,代码来源:response_cache.go

示例7: IgnoredStatement

func IgnoredStatement(line []byte) bool {
    if bytes.HasPrefix(line, COMMENT) || bytes.HasPrefix(line, SET_SESSION_VAR) ||
        bytes.HasPrefix(line, DELIMITER) || bytes.HasPrefix(line, BINLOG) || bytes.HasPrefix(line, BINLOG_DB_CHANGE) {
        return true
    }
    return false
}

开发者ID:shrutip,项目名称:vitess,代码行数:7,代码来源:binlog_parser.go

示例8: UnmarshalFile

// UnmarshalFile loads a file and parses a Plist from the loaded data.
// If the file is a binary plist, the plutil system command is used to convert
// it to XML text.
func UnmarshalFile(filename string) (*Plist, error) {
    xmlFile, err := os.Open(filename)
    if err != nil {
        return nil, fmt.Errorf("plist: error opening plist: %s", err)
    }
    defer xmlFile.Close()

    xmlData, err := ioutil.ReadAll(xmlFile)
    if err != nil {
        return nil, fmt.Errorf("plist: error reading plist file: %s", err)
    }

    if !bytes.HasPrefix(xmlData, []byte("<?xml ")) {
        debug("non-text XML -- assuming binary")
        xmlData, err = exec.Command("plutil", "-convert", "xml1", "-o", "-",
            filename).Output()
        if err != nil || !bytes.HasPrefix(xmlData, []byte("<?xml ")) {
            return nil, fmt.Errorf("plist: invalid plist file " + filename)
        }
    }

    var plist Plist
    err = Unmarshal(xmlData, &plist)
    if err != nil {
        return nil, err
    }

    return &plist, err
}

开发者ID:jason0x43,项目名称:go-plist,代码行数:32,代码来源:main.go

示例9: toRunes

func toRunes(text []byte) ([]rune, error) {
    var runes []rune
    if bytes.HasPrefix(text, []byte{0, 0, 0xFE, 0xFF}) {
        return nil, fmt.Errorf("mof: unsupported encoding: UTF-32, big-endian")
    } else if bytes.HasPrefix(text, []byte{0xFF, 0xFE, 0, 0}) {
        return nil, fmt.Errorf("mof: unsupported encoding: UTF-32, little-endian")
    } else if bytes.HasPrefix(text, []byte{0xFE, 0xFF}) {
        return nil, fmt.Errorf("mof: unsupported encoding: UTF-16, big-endian")
    } else if bytes.HasPrefix(text, []byte{0xFF, 0xFE}) {
        // UTF-16, little-endian
        for len(text) > 0 {
            u := binary.LittleEndian.Uint16(text)
            runes = append(runes, rune(u))
            text = text[2:]
        }
        return runes, nil
    }
    // Assume UTF-8.
    for len(text) > 0 {
        r, s := utf8.DecodeRune(text)
        if r == utf8.RuneError {
            return nil, fmt.Errorf("mof: unrecognized encoding")
        }
        runes = append(runes, r)
        text = text[s:]
    }
    return runes, nil
}

开发者ID:eswdd,项目名称:bosun,代码行数:28,代码来源:parse.go

示例10: Read

func (r *Reader) Read() ([]byte, error) {
    buf := []byte{}
    var isErr bool
    for {
        line, err := r.ReadBytes('\n')
        if err != nil {
            return nil, err
        }
        if bytes.HasPrefix(line, []byte("event: error")) {
            isErr = true
        }
        if bytes.HasPrefix(line, []byte("data: ")) {
            data := bytes.TrimSuffix(bytes.TrimPrefix(line, []byte("data: ")), []byte("\n"))
            buf = append(buf, data...)
        }
        // peek ahead one byte to see if we have a double newline (terminator)
        if peek, err := r.Peek(1); err == nil && string(peek) == "\n" {
            break
        }
    }
    if isErr {
        return nil, Error(string(buf))
    }
    return buf, nil
}

开发者ID:ahi,项目名称:go-flynn-example,代码行数:25,代码来源:sse.go

示例11: UnmarshalPublic

// UnmarshalPublic decodes a byte slice containing an OpenSSH public key
// into an public key. It supports RSA and ECDSA keys.
func UnmarshalPublic(raw []byte) (key *SSHPublicKey, err error) {
    kb64 := pubkeyRegexp.ReplaceAll(raw, []byte("$1"))
    kb := make([]byte, base64.StdEncoding.DecodedLen(len(raw)))
    i, err := base64.StdEncoding.Decode(kb, kb64)
    if err != nil {
        return
    }
    kb = kb[:i]

    key = new(SSHPublicKey)
    if commentRegexp.Match(raw) {
        key.Comment = string(commentRegexp.ReplaceAll(raw, []byte("$3")))
        key.Comment = strings.TrimSpace(key.Comment)
    }

    switch {
    case bytes.HasPrefix(raw, []byte("ssh-rsa")):
        key.Type = KEY_RSA
        key.Key, err = parseRSAPublicKey(kb)
    case bytes.HasPrefix(raw, []byte("ecdsa")):
        key.Type = KEY_ECDSA
        key.Key, err = parseECDSAPublicKey(kb)
    case bytes.HasPrefix(raw, []byte("ssh-dss")):
        key.Type = KEY_DSA
        key.Key, err = parseDSAPublicKey(kb)
    default:
        key.Type = KEY_UNSUPPORTED
        err = ErrUnsupportedPublicKey
    }
    return
}

开发者ID:postfix,项目名称:sshkey,代码行数:33,代码来源:sshkey.go

示例12: extractKeywords

// Given a source file, extract keywords and values into the given map.
// The map must be filled with keywords to look for.
// The keywords in the data must be on the form "keyword: value",
// and can be within single-line HTML comments (<-- ... -->).
// Returns the data for the lines that does not contain any of the keywords.
func extractKeywords(data []byte, special map[string]string) []byte {
    bnl := []byte("\n")
    // Find and separate the lines starting with one of the keywords in the special map
    _, regular := filterIntoGroups(bytes.Split(data, bnl), func(byteline []byte) bool {
        // Check if the current line has one of the special keywords
        for keyword := range special {
            // Check for lines starting with the keyword and a ":"
            if bytes.HasPrefix(byteline, []byte(keyword+":")) {
                // Set (possibly overwrite) the value in the map, if the keyword is found.
                // Trim the surrounding whitespace and skip the letters of the keyword itself.
                special[keyword] = strings.TrimSpace(string(byteline)[len(keyword)+1:])
                return true
            }
            // Check for lines that starts with "<!--", ends with "-->" and contains the keyword and a ":"
            if bytes.HasPrefix(byteline, []byte("<!--")) && bytes.HasSuffix(byteline, []byte("-->")) {
                // Strip away the comment markers
                stripped := strings.TrimSpace(string(byteline[5 : len(byteline)-3]))
                // Check if one of the relevant keywords are present
                if strings.HasPrefix(stripped, keyword+":") {
                    // Set (possibly overwrite) the value in the map, if the keyword is found.
                    // Trim the surrounding whitespace and skip the letters of the keyword itself.
                    special[keyword] = strings.TrimSpace(stripped[len(keyword)+1:])
                    return true
                }
            }

        }
        // Not special
        return false
    })
    // Use the regular lines as the new data (remove the special lines)
    return bytes.Join(regular, bnl)
}

开发者ID:jeraldrich,项目名称:algernon,代码行数:38,代码来源:utils.go

示例13: TestKeyEncoding

func TestKeyEncoding(t *testing.T) {
    tests := []*spb.Entry{
        entry(vname("sig", "corpus", "root", "path", "language"), "", nil, "fact", "value"),
        entry(vname("sig", "corpus", "root", "path", "language"),
            "someEdge", vname("anotherVName", "", "", "", ""),
            "/", ""),
        entry(vname(entryKeyPrefix, "[email protected]#$%^&*()_+`-={}|:;\"'?/>.<,", "", "", ""), "", nil, "/", ""),
    }

    for _, test := range tests {
        key, err := EncodeKey(test.Source, test.FactName, test.EdgeKind, test.Target)
        fatalOnErr(t, "Error encoding key: %v", err)

        if !bytes.HasPrefix(key, entryKeyPrefixBytes) {
            t.Fatalf("Key missing entry prefix: %q", string(key))
        }

        prefix, err := KeyPrefix(test.Source, test.EdgeKind)
        fatalOnErr(t, "Error creating key prefix: %v", err)

        if !bytes.HasPrefix(key, prefix) {
            t.Fatalf("Key missing KeyPrefix: %q %q", string(key), string(prefix))
        }

        entry, err := Entry(key, test.FactValue)
        fatalOnErr(t, "Error creating Entry from key: %v", err)

        if !proto.Equal(entry, test) {
            t.Errorf("Expected Entry: {%+v}; Got: {%+v}", test, entry)
        }
    }
}

开发者ID:jwatt,项目名称:kythe,代码行数:32,代码来源:keyvalue_test.go

示例14: getRulesInfo

func getRulesInfo(host string, timeout int) ([]byte, error) {
    conn, err := net.DialTimeout("udp", host, time.Duration(timeout)*time.Second)
    if err != nil {
        logger.LogSteamError(ErrHostConnection(err.Error()))
        return nil, ErrHostConnection(err.Error())
    }

    conn.SetDeadline(time.Now().Add(time.Duration(timeout-1) * time.Second))
    defer conn.Close()

    _, err = conn.Write(rulesChallengeReq)
    if err != nil {
        logger.LogSteamError(ErrDataTransmit(err.Error()))
        return nil, ErrDataTransmit(err.Error())
    }

    challengeNumResp := make([]byte, maxPacketSize)
    _, err = conn.Read(challengeNumResp)
    if err != nil {
        logger.LogSteamError(ErrDataTransmit(err.Error()))
        return nil, ErrDataTransmit(err.Error())
    }
    if !bytes.HasPrefix(challengeNumResp, expectedRulesRespHeader) {
        logger.LogSteamError(ErrChallengeResponse)
        return nil, ErrChallengeResponse
    }

    challengeNum := bytes.TrimLeft(challengeNumResp, headerStr)
    challengeNum = challengeNum[1:5]
    request := []byte{0xFF, 0xFF, 0xFF, 0xFF, 0x56}
    request = append(request, challengeNum...)

    _, err = conn.Write(request)
    if err != nil {
        logger.LogSteamError(ErrDataTransmit(err.Error()))
        return nil, ErrDataTransmit(err.Error())
    }

    var buf [maxPacketSize]byte
    numread, err := conn.Read(buf[:maxPacketSize])
    if err != nil {
        logger.LogSteamError(ErrDataTransmit(err.Error()))
        return nil, ErrDataTransmit(err.Error())
    }
    var rulesInfo []byte
    if bytes.HasPrefix(buf[:maxPacketSize], multiPacketRespHeader) {
        // handle multi-packet response
        first := buf[:maxPacketSize]
        first = first[:numread]
        rulesInfo, err = handleMultiPacketResponse(conn, first)
        if err != nil {
            logger.LogSteamError(ErrDataTransmit(err.Error()))
            return nil, ErrDataTransmit(err.Error())
        }
    } else {
        rulesInfo = make([]byte, numread)
        copy(rulesInfo, buf[:numread])
    }
    return rulesInfo, nil
}

开发者ID:syncore,项目名称:a2sapi,代码行数:60,代码来源:steamrules.go

示例15: parseTag

func parseTag(source []byte) (tag interface{}) {
    defer func() {
        if e := recover(); e != nil {
            v := e.(*err.OpenErr)
            v.Text += "err parse tpl: " + string(source)
            err.Panic(v)
        }
    }()

    list := parser.SplitWord(source, 32)
    switch list[0] {
    // основные теги
    case "!":
    case "inc":
        tag = parseTagInclude(list[1:])
    case "i18n":
        tag = parseTagi18n(list[1:])
    case "for":
        tag = parseTagFor(list[1:])
    default:
        // переменная контекста
        // либо функция (расширенные теги)
        slice := []byte(list[0])
        if bytes.HasPrefix(slice, []byte(".")) {
            tag = tTagVar(list[0][1:])
        } else if bytes.HasPrefix(slice, []byte("@.")) {
            tag = tTagVarHtmlEsc(list[0][2:])
        } else {
            tag = parseTagFunc(list)
        }
    }
    return
}

开发者ID:catgatp,项目名称:gol,代码行数:33,代码来源:tplengin.go

示例16: DecodeAbortCacheKey

// DecodeAbortCacheKey decodes the provided abort cache entry,
// returning the transaction ID.
func DecodeAbortCacheKey(key roachpb.Key, dest []byte) (*uuid.UUID, error) {
    // TODO(tschottdorf): redundant check.
    if !bytes.HasPrefix(key, LocalRangeIDPrefix) {
        return nil, util.Errorf("key %s does not have %s prefix", key, LocalRangeIDPrefix)
    }
    // Cut the prefix, the Range ID, and the infix specifier.
    b := key[len(LocalRangeIDPrefix):]
    b, _, err := encoding.DecodeUvarintAscending(b)
    if err != nil {
        return nil, err
    }
    b = b[1:]
    if !bytes.HasPrefix(b, LocalAbortCacheSuffix) {
        return nil, util.Errorf("key %s does not contain the abort cache suffix %s",
            key, LocalAbortCacheSuffix)
    }
    // Cut the abort cache suffix.
    b = b[len(LocalAbortCacheSuffix):]
    // Decode the id.
    b, idBytes, err := encoding.DecodeBytesAscending(b, dest)
    if err != nil {
        return nil, err
    }
    if len(b) > 0 {
        return nil, util.Errorf("key %q has leftover bytes after decode: %s; indicates corrupt key", key, b)
    }
    txnID, err := uuid.FromBytes(idBytes)
    return txnID, err
}

开发者ID:petermattis,项目名称:cockroach,代码行数:31,代码来源:keys.go

示例17: isRelativeLink

func isRelativeLink(link []byte) (yes bool) {
    // a tag begin with '#'
    if link[0] == '#' {
        return true
    }

    // link begin with '/' but not '//', the second maybe a protocol relative link
    if len(link) >= 2 && link[0] == '/' && link[1] != '/' {
        return true
    }

    // only the root '/'
    if len(link) == 1 && link[0] == '/' {
        return true
    }

    // current directory : begin with "./"
    if bytes.HasPrefix(link, []byte("./")) {
        return true
    }

    // parent directory : begin with "../"
    if bytes.HasPrefix(link, []byte("../")) {
        return true
    }

    return false
}

开发者ID:fxnn,项目名称:gone,代码行数:28,代码来源:html.go

示例18: IdentifyRedHatRelease

// IdentifyRedHatRelease tires to identify the derivretives of Red Hat Linux.
// It supports following distributions:
//
//   - CentOS
//   - Red Hat Enterprise Linux
//
// If failed to identify the platform or the platform is the derivatives of
// Red Hat Linux, IdentifyRedHatRelease returns an ErrNotIdentifier.
func IdentifyRedHatRelease() (*Info, error) {
    file, err := os.Open("/etc/redhat-release")
    if err != nil {
        if os.IsNotExist(err) {
            return nil, ErrNotIdentified
        }
        return nil, err
    }
    b, err := ioutil.ReadAll(file)
    if err != nil {
        return nil, err
    }

    var platform Name
    lb := bytes.ToLower(b)
    switch {
    case bytes.HasPrefix(lb, []byte("centos")):
        platform = PlatformCentOS
    case bytes.HasPrefix(lb, []byte("red hat enterprise")):
        platform = PlatformRHEL
    }

    version := ""
    if matches := regexp.MustCompile(`release (\d[\d.]*)`).FindSubmatch(b); len(matches) > 1 {
        version = string(matches[1])
    }

    return &Info{
        Platform: platform,
        Family:   FamilyRHEL,
        Version:  version,
    }, nil
}

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

示例19: decodeResponseCacheKey

func (rc *ResponseCache) decodeResponseCacheKey(encKey proto.EncodedKey) (proto.ClientCmdID, error) {
    ret := proto.ClientCmdID{}
    key, _, isValue := engine.MVCCDecodeKey(encKey)
    if isValue {
        return ret, util.Errorf("key %s is not a raw MVCC value", encKey)
    }
    if !bytes.HasPrefix(key, keys.LocalRangeIDPrefix) {
        return ret, util.Errorf("key %s does not have %s prefix", key, keys.LocalRangeIDPrefix)
    }
    // Cut the prefix and the Raft ID.
    b := key[len(keys.LocalRangeIDPrefix):]
    b, _ = encoding.DecodeUvarint(b)
    if !bytes.HasPrefix(b, keys.LocalResponseCacheSuffix) {
        return ret, util.Errorf("key %s does not contain the response cache suffix %s",
            key, keys.LocalResponseCacheSuffix)
    }
    // Cut the response cache suffix.
    b = b[len(keys.LocalResponseCacheSuffix):]
    // Now, decode the command ID.
    b, wt := encoding.DecodeUvarint(b)
    b, rd := encoding.DecodeUint64(b)
    if len(b) > 0 {
        return ret, util.Errorf("key %s has leftover bytes after decode: %s; indicates corrupt key",
            encKey, b)
    }
    ret.WallTime = int64(wt)
    ret.Random = int64(rd)
    return ret, nil
}

开发者ID:Gardenya,项目名称:cockroach,代码行数:29,代码来源:response_cache.go

示例20: decodeShallow

// Expected format: shallow <hash>
func decodeShallow(d *Decoder) decoderStateFn {
    if bytes.HasPrefix(d.line, deepen) {
        return decodeDeepen
    }

    if len(d.line) == 0 {
        return nil
    }

    if !bytes.HasPrefix(d.line, shallow) {
        d.error("unexpected payload while expecting a shallow: %q", d.line)
        return nil
    }
    d.line = bytes.TrimPrefix(d.line, shallow)

    hash, ok := d.readHash()
    if !ok {
        return nil
    }
    d.data.Shallows = append(d.data.Shallows, hash)

    if ok := d.nextLine(); !ok {
        return nil
    }

    return decodeShallow
}

开发者ID:alcortesm,项目名称:go-git,代码行数:28,代码来源:decoder.go

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