github.com/outcaste-io/ristretto@v0.2.3/z/z_test.go (about) 1 /* 2 * Copyright 2019 Dgraph Labs, Inc. and Contributors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package z 18 19 import ( 20 "math" 21 "testing" 22 23 "github.com/stretchr/testify/require" 24 ) 25 26 func verifyHashProduct(t *testing.T, wantKey, wantConflict, key, conflict uint64) { 27 require.Equal(t, wantKey, key) 28 require.Equal(t, wantConflict, conflict) 29 } 30 31 func TestKeyToHash(t *testing.T) { 32 var key uint64 33 var conflict uint64 34 35 key, conflict = KeyToHash(uint64(1)) 36 verifyHashProduct(t, 1, 0, key, conflict) 37 38 key, conflict = KeyToHash(1) 39 verifyHashProduct(t, 1, 0, key, conflict) 40 41 key, conflict = KeyToHash(int32(2)) 42 verifyHashProduct(t, 2, 0, key, conflict) 43 44 key, conflict = KeyToHash(int32(-2)) 45 verifyHashProduct(t, math.MaxUint64-1, 0, key, conflict) 46 47 key, conflict = KeyToHash(int64(-2)) 48 verifyHashProduct(t, math.MaxUint64-1, 0, key, conflict) 49 50 key, conflict = KeyToHash(uint32(3)) 51 verifyHashProduct(t, 3, 0, key, conflict) 52 53 key, conflict = KeyToHash(int64(3)) 54 verifyHashProduct(t, 3, 0, key, conflict) 55 } 56 57 func TestMulipleSignals(t *testing.T) { 58 closer := NewCloser(0) 59 require.NotPanics(t, func() { closer.Signal() }) 60 // Should not panic. 61 require.NotPanics(t, func() { closer.Signal() }) 62 require.NotPanics(t, func() { closer.SignalAndWait() }) 63 64 // Attempt 2. 65 closer = NewCloser(1) 66 require.NotPanics(t, func() { closer.Done() }) 67 68 require.NotPanics(t, func() { closer.SignalAndWait() }) 69 // Should not panic. 70 require.NotPanics(t, func() { closer.SignalAndWait() }) 71 require.NotPanics(t, func() { closer.Signal() }) 72 } 73 74 func TestCloser(t *testing.T) { 75 closer := NewCloser(1) 76 go func() { 77 defer closer.Done() 78 <-closer.Ctx().Done() 79 }() 80 closer.SignalAndWait() 81 } 82 83 func TestZeroOut(t *testing.T) { 84 dst := make([]byte, 4*1024) 85 fill := func() { 86 for i := 0; i < len(dst); i++ { 87 dst[i] = 0xFF 88 } 89 } 90 check := func(buf []byte, b byte) { 91 for i := 0; i < len(buf); i++ { 92 require.Equalf(t, b, buf[i], "idx: %d", i) 93 } 94 } 95 fill() 96 97 ZeroOut(dst, 0, 1) 98 check(dst[:1], 0x00) 99 check(dst[1:], 0xFF) 100 101 ZeroOut(dst, 0, 1024) 102 check(dst[:1024], 0x00) 103 check(dst[1024:], 0xFF) 104 105 ZeroOut(dst, 0, len(dst)) 106 check(dst, 0x00) 107 }