码迷,mamicode.com
首页 > 其他好文 > 详细

compare.go

时间:2017-08-30 14:18:09      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:creat   visio   hub   nbsp   union   package   core   pack   panic   


package clientv3

import (
    pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
)

type CompareTarget int
type CompareResult int

const (
    CompareVersion CompareTarget = iota
    CompareCreated
    CompareModified
    CompareValue
)

type Cmp pb.Compare

func Compare(cmp Cmp, result string, v interface{}) Cmp {
    var r pb.Compare_CompareResult

    switch result {
    case "=":
        r = pb.Compare_EQUAL
    case "!=":
        r = pb.Compare_NOT_EQUAL
    case ">":
        r = pb.Compare_GREATER
    case "<":
        r = pb.Compare_LESS
    default:
        panic("Unknown result op")
    }

    cmp.Result = r
    switch cmp.Target {
    case pb.Compare_VALUE:
        val, ok := v.(string)
        if !ok {
            panic("bad compare value")
        }
        cmp.TargetUnion = &pb.Compare_Value{Value: []byte(val)}
    case pb.Compare_VERSION:
        cmp.TargetUnion = &pb.Compare_Version{Version: mustInt64(v)}
    case pb.Compare_CREATE:
        cmp.TargetUnion = &pb.Compare_CreateRevision{CreateRevision: mustInt64(v)}
    case pb.Compare_MOD:
        cmp.TargetUnion = &pb.Compare_ModRevision{ModRevision: mustInt64(v)}
    default:
        panic("Unknown compare type")
    }
    return cmp
}

func Value(key string) Cmp {
    return Cmp{Key: []byte(key), Target: pb.Compare_VALUE}
}

func Version(key string) Cmp {
    return Cmp{Key: []byte(key), Target: pb.Compare_VERSION}
}

func CreateRevision(key string) Cmp {
    return Cmp{Key: []byte(key), Target: pb.Compare_CREATE}
}

func ModRevision(key string) Cmp {
    return Cmp{Key: []byte(key), Target: pb.Compare_MOD}
}

func mustInt64(val interface{}) int64 {
    if v, ok := val.(int64); ok {
        return v
    }
    if v, ok := val.(int); ok {
        return int64(v)
    }
    panic("bad value")
}

compare.go

标签:creat   visio   hub   nbsp   union   package   core   pack   panic   

原文地址:http://www.cnblogs.com/zhangboyu/p/7452671.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!