influxdb/request_vote_response.go

62 lines
1.4 KiB
Go
Raw Normal View History

package raft
import (
2013-07-18 16:26:31 +00:00
"code.google.com/p/goprotobuf/proto"
2013-07-18 16:41:33 +00:00
"github.com/benbjohnson/go-raft/protobuf"
"io"
2013-07-18 16:26:31 +00:00
"io/ioutil"
)
// The response returned from a server after a vote for a candidate to become a leader.
type RequestVoteResponse struct {
peer *Peer
Term uint64
VoteGranted bool
}
// Creates a new RequestVote response.
func newRequestVoteResponse(term uint64, voteGranted bool) *RequestVoteResponse {
return &RequestVoteResponse{
Term: term,
VoteGranted: voteGranted,
}
}
2013-07-18 16:26:31 +00:00
// Encodes the RequestVoteResponse to a buffer. Returns the number of bytes
// written and any error that may have occurred.
func (resp *RequestVoteResponse) encode(w io.Writer) (int, error) {
2013-07-18 16:26:31 +00:00
pb := &protobuf.ProtoRequestVoteResponse{
Term: proto.Uint64(resp.Term),
VoteGranted: proto.Bool(resp.VoteGranted),
}
p, err := proto.Marshal(pb)
2013-07-18 16:26:31 +00:00
if err != nil {
return -1, err
}
return w.Write(p)
}
2013-07-18 16:26:31 +00:00
// Decodes the RequestVoteResponse from a buffer. Returns the number of bytes read and
// any error that occurs.
func (resp *RequestVoteResponse) decode(r io.Reader) (int, error) {
2013-07-18 16:26:31 +00:00
data, err := ioutil.ReadAll(r)
if err != nil {
return 0, err
}
2013-07-18 16:26:31 +00:00
totalBytes := len(data)
pb := &protobuf.ProtoRequestVoteResponse{}
if err = proto.Unmarshal(data, pb); err != nil {
2013-07-18 16:26:31 +00:00
return -1, err
}
2013-07-18 16:26:31 +00:00
resp.Term = pb.GetTerm()
resp.VoteGranted = pb.GetVoteGranted()
2013-07-18 16:26:31 +00:00
return totalBytes, nil
}