Example #1
0
File: remote.go Project: vaudoc/god
func (self Remote) Less(other Remote) bool {
	val := bytes.Compare(self.Pos, other.Pos)
	if val == 0 {
		val = bytes.Compare([]byte(self.Addr), []byte(other.Addr))
	}
	return val < 0
}
Example #2
0
func (suts *SortableUiTaskSlice) Less(i, j int) bool {

	taskOne := suts.tasks[i]
	taskTwo := suts.tasks[j]

	displayNameOne := taskOne.Task.DisplayName
	displayNameTwo := taskTwo.Task.DisplayName

	if displayNameOne == evergreen.CompileStage {
		return true
	}
	if displayNameTwo == evergreen.CompileStage {
		return false
	}
	if displayNameOne == evergreen.PushStage {
		return false
	}
	if displayNameTwo == evergreen.PushStage {
		return true
	}

	if bytes.Compare([]byte(displayNameOne), []byte(displayNameTwo)) == -1 {
		return true
	}
	if bytes.Compare([]byte(displayNameOne), []byte(displayNameTwo)) == 1 {
		return false
	}
	return false
}
Example #3
0
File: server.go Project: logan/heim
func (ctrl *Controller) authorizeKey(conn ssh.ConnMetadata, key ssh.PublicKey) (
	*ssh.Permissions, error) {

	marshaledKey := key.Marshal()
	for _, authorizedKey := range ctrl.authorizedKeys {
		if bytes.Compare(authorizedKey.Marshal(), marshaledKey) == 0 {
			return &ssh.Permissions{}, nil
		}
	}

	nodes, err := ctrl.cluster.GetDir("console/authorized_keys")
	if err != nil {
		if err == cluster.ErrNotFound {
			return nil, fmt.Errorf("unauthorized")
		}
		return nil, err
	}

	for path, value := range nodes {
		key, _, _, _, err := ssh.ParseAuthorizedKey([]byte(value))
		if err != nil {
			fmt.Printf("bad authorized key from etcd: %s: %s\n", path, err)
		}
		if bytes.Compare(key.Marshal(), marshaledKey) == 0 {
			return &ssh.Permissions{}, nil
		}
	}

	return nil, fmt.Errorf("unauthorized")
}
Example #4
0
func (oc OfflineComparer) Compare(a, b []byte) int {
	p1, p2, p3 := oc.Split(a)
	p4, p5, p6 := oc.Split(b)

	if p1 == nil || p4 == nil {
		log.Infof("can't find seperate, a:%s b:%s compare bytes...\n", string(a), string(b))
		return bytes.Compare(a, b)
	}

	r1 := bytes.Compare(p1, p4)
	if r1 != 0 {
		return r1
	}

	r2 := bytes.Compare(p2, p5)
	if r2 != 0 {
		return r2
	}

	v1, err1 := strconv.ParseInt(string(p3), 10, 64)
	v2, err2 := strconv.ParseInt(string(p6), 10, 64)
	if err1 != nil || err2 != nil {
		log.Infof("parse int err, a:%s b:%s compare bytes...\n", string(a), string(b))
		return bytes.Compare(p3, p6)
	}

	if v1 < v2 {
		return -1
	} else if v1 == v2 {
		return 0
	} else {
		return 1
	}
}
Example #5
0
func (p byKeyValue) Less(i, j int) bool {
	sgn := bytes.Compare(p[i].key, p[j].key)
	if sgn == 0 {
		sgn = bytes.Compare(p[i].value, p[j].value)
	}
	return sgn < 0
}
Example #6
0
// depending on the query order (whether it's ascending or not) returns
// the min (or max in case of descending query) of the current
// [timestamp,sequence] and the self's [timestamp,sequence]
//
// This is used to determine what the next point's timestamp
// and sequence number should be.
func (self *rawColumnValue) updatePointTimeAndSequence(currentTimeRaw, currentSequenceRaw []byte, isAscendingQuery bool) ([]byte, []byte) {
	if currentTimeRaw == nil {
		return self.time, self.sequence
	}

	compareValue := 1
	if isAscendingQuery {
		compareValue = -1
	}

	timeCompare := bytes.Compare(self.time, currentTimeRaw)
	if timeCompare == compareValue {
		return self.time, self.sequence
	}

	if timeCompare != 0 {
		return currentTimeRaw, currentSequenceRaw
	}

	if bytes.Compare(self.sequence, currentSequenceRaw) == compareValue {
		return currentTimeRaw, self.sequence
	}

	return currentTimeRaw, currentSequenceRaw
}
Example #7
0
func testBasicEncodeDecode32(encFunc func([]byte, uint32) []byte,
	decFunc func([]byte) ([]byte, uint32, error), descending bool, t *testing.T) {
	testCases := []uint32{
		0, 1,
		1<<8 - 1, 1 << 8,
		1<<16 - 1, 1 << 16,
		1<<24 - 1, 1 << 24,
		math.MaxUint32 - 1, math.MaxUint32,
	}

	var lastEnc []byte
	for i, v := range testCases {
		enc := encFunc(nil, v)
		if i > 0 {
			if (descending && bytes.Compare(enc, lastEnc) >= 0) ||
				(!descending && bytes.Compare(enc, lastEnc) < 0) {
				t.Errorf("ordered constraint violated for %d: [% x] vs. [% x]", v, enc, lastEnc)
			}
		}
		b, decode, err := decFunc(enc)
		if err != nil {
			t.Error(err)
			continue
		}
		if len(b) != 0 {
			t.Errorf("leftover bytes: [% x]", b)
		}
		if decode != v {
			t.Errorf("decode yielded different value than input: %d vs. %d", decode, v)
		}
		lastEnc = enc
	}
}
Example #8
0
//Equals returns true if r==r2
func (r *Record) Equals(r2 *Record) bool {
	if r.Thread != r2.Thread {
		log.Println("unmatched threadname")
		return false
	}
	if bytes.Compare(r.Sign, r2.Sign) != 0 {
		log.Println("unmatched sign")
		return false
	}
	if !r.Stamp.Equal(r2.Stamp) {
		log.Println("unmatched stamp")
		return false
	}
	if r.self != r2.self {
		log.Println("unmatched self")
		return false
	}
	if len(r.Contents) != len(r2.Contents) {
		log.Println("unmatched contents length")
		return false
	}
	for k, v := range r.Contents {
		v2, exist := r2.Contents[k]
		if !exist || bytes.Compare(v, v2) != 0 {
			log.Println("unmatched contents", k)
			return false
		}
	}
	return true
}
Example #9
0
func TestGetSeedHash(t *testing.T) {
	seed0, err := GetSeedHash(0)
	if err != nil {
		t.Errorf("Failed to get seedHash for block 0: %v", err)
	}
	if bytes.Compare(seed0, make([]byte, 32)) != 0 {
		log.Printf("seedHash for block 0 should be 0s, was: %v\n", seed0)
	}
	seed1, err := GetSeedHash(30000)
	if err != nil {
		t.Error(err)
	}

	// From python:
	// > from pyethash import get_seedhash
	// > get_seedhash(30000)
	expectedSeed1, err := hex.DecodeString("290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563")
	if err != nil {
		t.Error(err)
	}

	if bytes.Compare(seed1, expectedSeed1) != 0 {
		log.Printf("seedHash for block 1 should be: %v,\nactual value: %v\n", expectedSeed1, seed1)
	}

}
Example #10
0
func Test_Blocks(t *testing.T) {
	byteIt := make(chan byte)
	go func() {
		for _, b := range []byte{67, 85, 70, 134, 87, 38, 85, 194, 119, 50, 6, 18, 6, 103, 38, 246, 246, 66, 7, 118, 134, 242, 7, 38, 86, 22, 198, 199, 146, 6, 182, 230, 247, 119, 50, 7, 118, 134, 87, 38, 82, 6, 134, 151, 50, 7, 70, 247, 118, 86, 194, 6, 151, 50, 16, 236, 17, 236, 17, 236, 17, 236} {
			byteIt <- b
		}
		close(byteIt)
	}()
	vi := &versionInfo{5, Q, 18, 2, 15, 2, 16}

	data := splitToBlocks(byteIt, vi).interleave(vi)
	if bytes.Compare(data, []byte{67, 246, 182, 70, 85, 246, 230, 247, 70, 66, 247, 118, 134, 7, 119, 86, 87, 118, 50, 194, 38, 134, 7, 6, 85, 242, 118, 151, 194, 7, 134, 50, 119, 38, 87, 16, 50, 86, 38, 236, 6, 22, 82, 17, 18, 198, 6, 236, 6, 199, 134, 17, 103, 146, 151, 236, 38, 6, 50, 17, 7, 236, 213, 87, 148, 235, 199, 204, 116, 159, 11, 96, 177, 5, 45, 60, 212, 173, 115, 202, 76, 24, 247, 182, 133, 147, 241, 124, 75, 59, 223, 157, 242, 33, 229, 200, 238, 106, 248, 134, 76, 40, 154, 27, 195, 255, 117, 129, 230, 172, 154, 209, 189, 82, 111, 17, 10, 2, 86, 163, 108, 131, 161, 163, 240, 32, 111, 120, 192, 178, 39, 133, 141, 236}) != 0 {
		t.Fail()
	}

	byteIt2 := make(chan byte)
	go func() {
		for _, b := range []byte{67, 85, 70, 134, 87, 38, 85, 194, 119, 50, 6, 18, 6, 103, 38, 246, 246, 66, 7, 118, 134, 242, 7, 38, 86, 22, 198, 199, 146, 6, 182, 230, 247, 119, 50, 7, 118, 134, 87, 38, 82, 6, 134, 151, 50, 7, 70, 247, 118, 86, 194, 6, 151, 50, 16, 236, 17, 236, 17, 236, 17, 236} {
			byteIt2 <- b
		}
		close(byteIt2)
	}()
	vi = &versionInfo{5, Q, 18, 2, 16, 2, 15}

	data = splitToBlocks(byteIt2, vi).interleave(vi)
	if bytes.Compare(data, []byte{67, 246, 247, 247, 85, 66, 119, 118, 70, 7, 50, 86, 134, 118, 7, 194, 87, 134, 118, 6, 38, 242, 134, 151, 85, 7, 87, 50, 194, 38, 38, 16, 119, 86, 82, 236, 50, 22, 6, 17, 6, 198, 134, 236, 18, 199, 151, 17, 6, 146, 50, 236, 103, 6, 7, 17, 38, 182, 70, 236, 246, 230, 71, 101, 27, 62, 13, 91, 166, 86, 138, 16, 78, 229, 102, 11, 199, 107, 2, 182, 132, 103, 89, 66, 136, 69, 78, 255, 116, 129, 126, 163, 219, 234, 158, 216, 42, 234, 97, 62, 186, 59, 123, 148, 220, 191, 254, 145, 82, 95, 129, 79, 236, 254, 30, 174, 228, 50, 181, 110, 150, 205, 34, 235, 242, 0, 115, 147, 58, 243, 28, 140, 221, 219}) != 0 {
		t.Fail()
	}
}
Example #11
0
func ldbDropRepo(db *leveldb.DB, repo []byte) {
	defer runtime.GC()

	snap, err := db.GetSnapshot()
	if err != nil {
		panic(err)
	}
	defer snap.Release()

	// Remove all items related to the given repo from the node->file bucket
	start := []byte{keyTypeNode}
	limit := []byte{keyTypeNode + 1}
	dbi := snap.NewIterator(&util.Range{Start: start, Limit: limit}, nil)
	for dbi.Next() {
		itemRepo := nodeKeyRepo(dbi.Key())
		if bytes.Compare(repo, itemRepo) == 0 {
			db.Delete(dbi.Key(), nil)
		}
	}
	dbi.Release()

	// Remove all items related to the given repo from the global bucket
	start = []byte{keyTypeGlobal}
	limit = []byte{keyTypeGlobal + 1}
	dbi = snap.NewIterator(&util.Range{Start: start, Limit: limit}, nil)
	for dbi.Next() {
		itemRepo := globalKeyRepo(dbi.Key())
		if bytes.Compare(repo, itemRepo) == 0 {
			db.Delete(dbi.Key(), nil)
		}
	}
	dbi.Release()
}
Example #12
0
func TestCreateAttributesMetadataObjectFromCert(t *testing.T) {
	tcert, preK0, err := loadTCertAndPreK0()
	if err != nil {
		t.Error(err)
	}

	metadata := []byte{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}
	attributeKeys := []string{"position"}
	metadataObj := CreateAttributesMetadataObjectFromCert(tcert, metadata, preK0, attributeKeys)
	if bytes.Compare(metadataObj.Metadata, metadata) != 0 {
		t.Errorf("Invalid metadata result %v but expected %v", metadataObj.Metadata, metadata)
	}

	entries := metadataObj.GetEntries()
	if len(entries) != 2 {
		t.Errorf("Invalid entries in metadata result %v but expected %v", len(entries), 3)
	}

	firstEntry := entries[0]
	if firstEntry.AttributeName != "position" {
		t.Errorf("Invalid first attribute name, this has to be %v but is %v", "position", firstEntry.AttributeName)
	}
	firstKey, err := GetKForAttribute("position", preK0, tcert)
	if err != nil {
		t.Error(err)
	}

	if bytes.Compare(firstKey, firstEntry.AttributeKey) != 0 {
		t.Errorf("Invalid K for first attribute expected %v but returned %v", firstKey, firstEntry.AttributeKey)
	}
}
Example #13
0
func TestGetAttributesMetadata(t *testing.T) {
	metadata := []byte{255, 255, 255, 255}
	entries := make([]*pb.AttributesMetadataEntry, 1)
	var entry pb.AttributesMetadataEntry
	entry.AttributeName = "position"
	entry.AttributeKey = []byte{0, 0, 0, 0}
	entries[0] = &entry
	attributesMetadata := pb.AttributesMetadata{Metadata: metadata, Entries: entries}
	raw, err := proto.Marshal(&attributesMetadata)
	if err != nil {
		t.Error(err)
	}
	resultMetadata, err := GetAttributesMetadata(raw)
	if err != nil {
		t.Error(err)
	}
	if bytes.Compare(resultMetadata.Metadata, attributesMetadata.Metadata) != 0 {
		t.Fatalf("Invalid metadata expected %v result %v", attributesMetadata.Metadata, resultMetadata.Metadata)
	}
	if resultMetadata.Entries[0].AttributeName != attributesMetadata.Entries[0].AttributeName {
		t.Fatalf("Invalid first entry attribute name expected %v result %v", attributesMetadata.Entries[0].AttributeName, resultMetadata.Entries[0].AttributeName)
	}
	if bytes.Compare(resultMetadata.Entries[0].AttributeKey, attributesMetadata.Entries[0].AttributeKey) != 0 {
		t.Fatalf("Invalid first entry attribute key expected %v result %v", attributesMetadata.Entries[0].AttributeKey, resultMetadata.Entries[0].AttributeKey)
	}
}
Example #14
0
func TestPutSerialized(t *testing.T) {
	// Create a volume with I/O serialization enabled.
	v := TempUnixVolume(t, true)
	defer _teardown(v)

	sem := make(chan int)
	go func(sem chan int) {
		err := v.Put(TEST_HASH, TEST_BLOCK)
		if err != nil {
			t.Errorf("err1: %v", err)
		}
		sem <- 1
	}(sem)

	go func(sem chan int) {
		err := v.Put(TEST_HASH_2, TEST_BLOCK_2)
		if err != nil {
			t.Errorf("err2: %v", err)
		}
		sem <- 1
	}(sem)

	go func(sem chan int) {
		err := v.Put(TEST_HASH_3, TEST_BLOCK_3)
		if err != nil {
			t.Errorf("err3: %v", err)
		}
		sem <- 1
	}(sem)

	// Wait for all goroutines to finish
	for done := 0; done < 2; {
		done += <-sem
	}

	// Double check that we actually wrote the blocks we expected to write.
	buf, err := v.Get(TEST_HASH)
	if err != nil {
		t.Errorf("Get #1: %v", err)
	}
	if bytes.Compare(buf, TEST_BLOCK) != 0 {
		t.Errorf("Get #1: expected %s, got %s", string(TEST_BLOCK), string(buf))
	}

	buf, err = v.Get(TEST_HASH_2)
	if err != nil {
		t.Errorf("Get #2: %v", err)
	}
	if bytes.Compare(buf, TEST_BLOCK_2) != 0 {
		t.Errorf("Get #2: expected %s, got %s", string(TEST_BLOCK_2), string(buf))
	}

	buf, err = v.Get(TEST_HASH_3)
	if err != nil {
		t.Errorf("Get #3: %v", err)
	}
	if bytes.Compare(buf, TEST_BLOCK_3) != 0 {
		t.Errorf("Get #3: expected %s, got %s", string(TEST_BLOCK_3), string(buf))
	}
}
Example #15
0
func TestBMPString(t *testing.T) {
	str, err := bmpString("")
	if bytes.Compare(str, []byte{0, 0}) != 0 {
		t.Errorf("expected empty string to return double 0, but found: % x", str)
	}
	if err != nil {
		t.Errorf("err: %v", err)
	}

	// Example from https://tools.ietf.org/html/rfc7292#appendix-B
	str, err = bmpString("Beavis")
	if bytes.Compare(str, []byte{0x00, 0x42, 0x00, 0x65, 0x00, 0x61, 0x00, 0x0076, 0x00, 0x69, 0x00, 0x73, 0x00, 0x00}) != 0 {
		t.Errorf("expected 'Beavis' to return 0x00 0x42 0x00 0x65 0x00 0x61 0x00 0x76 0x00 0x69 0x00 0x73 0x00 0x00, but found: % x", str)
	}
	if err != nil {
		t.Errorf("err: %v", err)
	}

	// some characters from the "Letterlike Symbols Unicode block"
	tst := "\u2115 - Double-struck N"
	str, err = bmpString(tst)
	if bytes.Compare(str, []byte{0x21, 0x15, 0x00, 0x20, 0x00, 0x2d, 0x00, 0x20, 0x00, 0x44, 0x00, 0x6f, 0x00, 0x75, 0x00, 0x62, 0x00, 0x6c, 0x00, 0x65, 0x00, 0x2d, 0x00, 0x73, 0x00, 0x74, 0x00, 0x72, 0x00, 0x75, 0x00, 0x63, 0x00, 0x6b, 0x00, 0x20, 0x00, 0x4e, 0x00, 0x00}) != 0 {
		t.Errorf("expected '%s' to return 0x21 0x15 0x00 0x20 0x00 0x2d 0x00 0x20 0x00 0x44 0x00 0x6f 0x00 0x75 0x00 0x62 0x00 0x6c 0x00 0x65 0x00 0x2d 0x00 0x73 0x00 0x74 0x00 0x72 0x00 0x75 0x00 0x63 0x00 0x6b 0x00 0x20 0x00 0x4e 0x00 0x00, but found: % x", tst, str)
	}
	if err != nil {
		t.Errorf("err: %v", err)
	}

	// some character outside the BMP should error
	tst = "\U0001f000 East wind (Mahjong)"
	str, err = bmpString(tst)
	if err == nil {
		t.Errorf("expected '%s' to throw error because the first character is not in the BMP", tst)
	}
}
Example #16
0
func BasicCodecComparator(o1 interface{}, o2 interface{}) int {
	switch o1.(type) {
	case byte:
		return int(o1.(byte) - o2.(byte))
	case int8:
		return int(o1.(int8) - o2.(int8))
	//case uint8:
	case int16:
		return int(o1.(int16) - o2.(int16))
	case uint16:
		return int(o1.(uint16) - o2.(uint16))
	case int32:
		return int(o1.(int32) - o2.(int32))
	case uint32:
		return int(o1.(uint32) - o2.(uint32))
	case int64:
		return int(o1.(int64) - o2.(int64))
	case uint64:
		return int(o1.(uint64) - o2.(uint64))
	case int:
		return o1.(int) - o2.(int)
	case uint:
		return int(o1.(uint)) - int(o2.(uint))
	case string:
		return bytes.Compare([]byte(o1.(string)), []byte(o2.(string)))
	case []byte:
		return bytes.Compare(o1.([]byte), o2.([]byte))
	case time.Time:
		return int(o1.(time.Time).UnixNano() - o2.(time.Time).UnixNano())
	default:
		panic(fmt.Sprintf("Unsupported type: %v", reflect.TypeOf(o1)))
	}
}
Example #17
0
func (m *MockQuery) sliceRow(r *Row) (*Row, error) {
	if m.components != nil || m.betweenStart != nil || m.betweenEnd != nil || m.columnLimit != 0 {
		slice, err := m.buildSlice()
		if err != nil {
			return nil, err
		}
		if m.reversed {
			slice.Start, slice.End = slice.End, slice.Start
		}
		cr := *r
		cr.Columns = []*Column{}
		for _, c := range r.Columns {
			if len(slice.Start) > 0 && bytes.Compare(slice.Start, c.Name) > 0 {
				continue
			}
			if len(slice.End) > 0 && bytes.Compare(slice.End, c.Name) < 0 {
				continue
			}
			cr.Columns = append(cr.Columns, c)
		}
		if slice.Count != 0 && len(cr.Columns) > slice.Count {
			if m.reversed {
				cr.Columns = cr.Columns[(len(cr.Columns) - slice.Count):len(cr.Columns)]
			} else {
				cr.Columns = cr.Columns[0:slice.Count]
			}
		}
		r = &cr
	}
	return r, nil
}
Example #18
0
func TestSetBodyGzip(t *testing.T) {
	s := "foo"

	// test []byte
	expB := []byte(s)
	actB, err := gzipHelper(t, expB)
	assert.T(t, err == nil, fmt.Sprintf("Expected err to be nil"))
	assert.T(t, bytes.Compare(actB, expB) == 0, fmt.Sprintf("Expected: %s, got: %s", expB, actB))

	// test string
	expS := s
	actS, err := gzipHelper(t, expS)
	assert.T(t, err == nil, fmt.Sprintf("Expected err to be nil"))
	assert.T(t, string(actS) == expS, fmt.Sprintf("Expected: %s, got: %s", expS, actS))

	// test io.Reader
	expR := strings.NewReader(s)
	actR, err := gzipHelper(t, expR)
	assert.T(t, err == nil, fmt.Sprintf("Expected err to be nil"))
	assert.T(t, bytes.Compare([]byte(s), actR) == 0, fmt.Sprintf("Expected: %s, got: %s", s, actR))

	// test other
	expO := testStruct{Name: "Travis"}
	actO, err := gzipHelper(t, expO)
	assert.T(t, err == nil, fmt.Sprintf("Expected err to not be nil"))
	assert.T(t, bytes.Compare([]byte(`{"name":"Travis"}`), actO) == 0, fmt.Sprintf("Expected: %s, got: %s", s, actO))
}
Example #19
0
/*
参数列表

a 第一个要比较的字节切片
b 第二个要比较的字节切片
返回值

int 如果a==b返回0,如果a < b返回-1,如果a > b返回1
功能说明

Compare根据字节的值比较两个字节切片的大小
*/
func main() {
	fmt.Println(bytes.Compare([]byte{1}, []byte{2}))
	fmt.Println(bytes.Compare([]byte{1}, []byte{1}))
	fmt.Println(bytes.Compare([]byte{1}, []byte{0}))
	fmt.Println(bytes.Compare([]byte{1}, []byte{1, 2}))
	fmt.Println(bytes.Compare([]byte{2}, []byte{1, 2}))
}
Example #20
0
// skipPacket processes all the DTLS records in packet. It updates
// sequence number expectations but otherwise ignores them.
func (c *Conn) skipPacket(packet []byte) error {
	for len(packet) > 0 {
		if len(packet) < 13 {
			return errors.New("tls: bad packet")
		}
		// Dropped packets are completely ignored save to update
		// expected sequence numbers for this and the next epoch. (We
		// don't assert on the contents of the packets both for
		// simplicity and because a previous test with one shorter
		// timeout schedule would have done so.)
		epoch := packet[3:5]
		seq := packet[5:11]
		length := uint16(packet[11])<<8 | uint16(packet[12])
		if bytes.Equal(c.in.seq[:2], epoch) {
			if bytes.Compare(seq, c.in.seq[2:]) < 0 {
				return errors.New("tls: sequence mismatch")
			}
			copy(c.in.seq[2:], seq)
			c.in.incSeq(false)
		} else {
			if bytes.Compare(seq, c.in.nextSeq[:]) < 0 {
				return errors.New("tls: sequence mismatch")
			}
			copy(c.in.nextSeq[:], seq)
			c.in.incNextSeq()
		}
		if len(packet) < 13+int(length) {
			return errors.New("tls: bad packet")
		}
		packet = packet[13+length:]
	}
	return nil
}
// TestNormalization tries to decode a non-normalized string.
func TestNormalization(t *testing.T) {
	a := Phrase{"abhärten"}
	b := Phrase{"abh\u00e4rten"}
	c := Phrase{"abha\u0308rten"}
	d := Phrase{"abh\u0061\u0308rten"}

	ba, err := FromPhrase(a, German)
	if err != nil {
		t.Error(err)
	}
	bb, err := FromPhrase(b, German)
	if err != nil {
		t.Error(err)
	}
	bc, err := FromPhrase(c, German)
	if err != nil {
		t.Error(err)
	}
	bd, err := FromPhrase(d, German)
	if err != nil {
		t.Error(err)
	}
	if bytes.Compare(ba, bb) != 0 {
		t.Error("bad decoding")
	}
	if bytes.Compare(bb, bc) != 0 {
		t.Error("bad decoding")
	}
	if bytes.Compare(bc, bd) != 0 {
		t.Error("bad decoding")
	}
}
Example #22
0
func TestDecryptOAEP(t *testing.T) {
	random := rand.Reader

	sha1 := sha1.New()
	n := new(big.Int)
	d := new(big.Int)
	for i, test := range testEncryptOAEPData {
		n.SetString(test.modulus, 16)
		d.SetString(test.d, 16)
		private := new(PrivateKey)
		private.PublicKey = PublicKey{n, test.e}
		private.D = d

		for j, message := range test.msgs {
			out, err := DecryptOAEP(sha1, nil, private, message.out, nil)
			if err != nil {
				t.Errorf("#%d,%d error: %s", i, j, err)
			} else if bytes.Compare(out, message.in) != 0 {
				t.Errorf("#%d,%d bad result: %#v (want %#v)", i, j, out, message.in)
			}

			// Decrypt with blinding.
			out, err = DecryptOAEP(sha1, random, private, message.out, nil)
			if err != nil {
				t.Errorf("#%d,%d (blind) error: %s", i, j, err)
			} else if bytes.Compare(out, message.in) != 0 {
				t.Errorf("#%d,%d (blind) bad result: %#v (want %#v)", i, j, out, message.in)
			}
		}
		if testing.Short() {
			break
		}
	}
}
Example #23
0
func (it *RangeLimitIterator) Valid() bool {
	if it.l.Offset < 0 {
		return false
	} else if !it.it.Valid() {
		return false
	} else if it.l.Count >= 0 && it.step >= it.l.Count {
		return false
	}

	if it.direction == IteratorForward {
		if it.r.Max != nil {
			r := bytes.Compare(it.it.RawKey(), it.r.Max)
			if it.r.Type&RangeROpen > 0 {
				return !(r >= 0)
			} else {
				return !(r > 0)
			}
		}
	} else {
		if it.r.Min != nil {
			r := bytes.Compare(it.it.RawKey(), it.r.Min)
			if it.r.Type&RangeLOpen > 0 {
				return !(r <= 0)
			} else {
				return !(r < 0)
			}
		}
	}

	return true
}
Example #24
0
func TestGetValue_Clear(t *testing.T) {
	primitives.SetSecurityLevel("SHA3", 256)

	tcert, err := loadTCertClear()
	if err != nil {
		t.Error(err)
	}
	tcertder := tcert.Raw
	value, err := GetValueFrom("position", tcertder)
	if err != nil {
		t.Error(err)
	}

	if bytes.Compare(value, []byte("Software Engineer")) != 0 {
		t.Fatalf("Value expected was [%v] and result was [%v].", []byte("Software Engineer"), value)
	}

	//Second time read from cache.
	value, err = GetValueFrom("position", tcertder)
	if err != nil {
		t.Error(err)
	}

	if bytes.Compare(value, []byte("Software Engineer")) != 0 {
		t.Fatalf("Value expected was [%v] and result was [%v].", []byte("Software Engineer"), value)
	}
}
Example #25
0
// seekBuf moves the cursor to a position within the current buffer.
func (c *Cursor) seekBuf(seek []byte) (key, value []byte) {
	for {
		// Slice off the current entry.
		buf := c.buf[c.off:]

		// Exit if current entry's timestamp is on or after the seek.
		if len(buf) == 0 {
			return
		}

		if c.direction.Forward() && bytes.Compare(buf[0:8], seek) != -1 {
			return
		} else if c.direction.Reverse() && bytes.Compare(buf[0:8], seek) != 1 {
			return
		}

		if c.direction.Forward() {
			// Otherwise skip ahead to the next entry.
			c.off += entryHeaderSize + entryDataSize(buf)
		} else {
			c.index -= 1
			if c.index < 0 {
				return
			}
			c.off = c.fieldIndices[c.index]
		}
	}
}
Example #26
0
func TestKeyPrefixEnd(t *testing.T) {
	a := Key("a1")
	aNext := a.Next()
	aEnd := a.PrefixEnd()
	if bytes.Compare(a, aEnd) >= 0 {
		t.Errorf("expected end key to be greater")
	}
	if bytes.Compare(aNext, aEnd) >= 0 {
		t.Errorf("expected end key to be greater than next")
	}

	testCases := []struct {
		key Key
		end Key
	}{
		{Key{}, KeyMax},
		{Key{0}, Key{0x01}},
		{Key{0xff}, Key{0xff}},
		{Key{0xff, 0xff}, Key{0xff, 0xff}},
		{KeyMax, KeyMax},
		{Key{0xff, 0xfe}, Key{0xff, 0xff}},
		{Key{0x00, 0x00}, Key{0x00, 0x01}},
		{Key{0x00, 0xff}, Key{0x01, 0x00}},
		{Key{0x00, 0xff, 0xff}, Key{0x01, 0x00, 0x00}},
	}
	for i, c := range testCases {
		if !bytes.Equal(c.key.PrefixEnd(), c.end) {
			t.Errorf("%d: unexpected prefix end bytes for %q: %q", i, c.key, c.key.PrefixEnd())
		}
	}
}
Example #27
0
// extractKVRanges extracts kv.KeyRanges slice from ctx.keyRanges, and also returns if it is in descending order.
func (rs *localRegion) extractKVRanges(ctx *selectContext) (kvRanges []kv.KeyRange) {
	for _, kran := range ctx.keyRanges {
		upperKey := kran.EndKey
		if bytes.Compare(upperKey, rs.startKey) <= 0 {
			continue
		}
		lowerKey := kran.StartKey
		if bytes.Compare(lowerKey, rs.endKey) >= 0 {
			break
		}
		var kvr kv.KeyRange
		if bytes.Compare(lowerKey, rs.startKey) <= 0 {
			kvr.StartKey = rs.startKey
		} else {
			kvr.StartKey = lowerKey
		}
		if bytes.Compare(upperKey, rs.endKey) <= 0 {
			kvr.EndKey = upperKey
		} else {
			kvr.EndKey = rs.endKey
		}
		kvRanges = append(kvRanges, kvr)
	}
	if ctx.descScan {
		reverseKVRanges(kvRanges)
	}
	return
}
Example #28
0
func TestCompare(t *testing.T) {
	u1, err := NewBytes(url)
	if err != nil {
		t.Error(err)
	}

	u2, err := NewBytes(url)
	if err != nil {
		t.Error(err)
	}

	u3, err := NewBytes(zero)
	if err != nil {
		t.Error(err)
	}

	if bytes.Compare(u1[:], u2[:]) != 0 {
		t.Error("Should be equal", u1, u2)
	}

	if bytes.Compare(u1[:], u3[:]) <= 0 {
		t.Error("Should be greater", u1, u3)
	}

	if bytes.Compare(u3[:], u1[:]) >= 0 {
		t.Error("Should be less", u1, u3)
	}
}
Example #29
0
func TestLoopingReader(t *testing.T) {
	b := make([]byte, 16)
	r := &loopingReader{[]byte{}, 0}
	if n, _ := r.Read(b); n != 0 {
		t.Fatalf("Empty loopingReader should return 0 bytes on Read instead of %d", n)
	}
	r.Write([]byte{1, 2})
	if n, _ := r.Read(b); n != 2 {
		t.Fatalf("loopingReader should return all bytes")
	} else if bytes.Compare(b[:2], []byte{1, 2}) != 0 {
		t.Fatalf("loopingReader output didn't match for full read")
	}
	b[0] = 0
	b[1] = 0
	if n, _ := r.Read(b[:1]); n != 1 {
		t.Fatalf("loopingReader should return 1 byte for non-full read instead of %d", n)
	} else if bytes.Compare(b[:2], []byte{1, 0}) != 0 {
		t.Fatalf("loopingReader output didn't match for non-full read")
	}
	if n, _ := r.Read(b[:1]); n != 1 {
		t.Fatalf("loopingReader should return 1 byte for non-full read2 instead of %d", n)
	} else if bytes.Compare(b[:2], []byte{2, 0}) != 0 {
		t.Fatalf("loopingReader output didn't match for non-full read2, returned %+v instead pf %+v", b[:2], []byte{2, 0})
	}
	if n, _ := r.Read(b[:1]); n != 1 {
		t.Fatalf("loopingReader should return 1 byte for non-full read3 instead of %d", n)
	} else if bytes.Compare(b[:2], []byte{1, 0}) != 0 {
		t.Fatalf("loopingReader output didn't match for non-full read3")
	}
}
Example #30
0
// KeyRangesOverlap returns the overlap between two KeyRanges.
// They need to overlap, otherwise an error is returned.
func KeyRangesOverlap(first, second *topodatapb.KeyRange) (*topodatapb.KeyRange, error) {
	if !KeyRangesIntersect(first, second) {
		return nil, fmt.Errorf("KeyRanges %v and %v don't overlap", first, second)
	}
	if first == nil {
		return second, nil
	}
	if second == nil {
		return first, nil
	}
	// compute max(c,a) and min(b,d)
	// start with (a,b)
	result := *first
	// if c > a, then use c
	if bytes.Compare(second.Start, first.Start) > 0 {
		result.Start = second.Start
	}
	// if b is maxed out, or
	// (d is not maxed out and d < b)
	//                           ^ valid test as neither b nor d are max
	// then use d
	if len(first.End) == 0 || (len(second.End) != 0 && bytes.Compare(second.End, first.End) < 0) {
		result.End = second.End
	}
	return &result, nil
}