本文整理汇总了Golang中math/rand.Int31函数的典型用法代码示例。如果您正苦于以下问题:Golang Int31函数的具体用法?Golang Int31怎么用?Golang Int31使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Int31函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: setWithCallback
// Callback is invoked while holding the mutate() lock, allowing
// the caller to do more atomic things.
func (p *partitionstore) setWithCallback(newItem *item, oldItem *item,
cb func()) (deltaItemBytes int64, err error) {
cBytes := casBytes(newItem.cas)
cItem := &gkvlite.Item{
Key: cBytes,
Val: newItem.toValueBytes(),
Priority: rand.Int31(),
Transient: unsafe.Pointer(newItem),
}
var kItem *gkvlite.Item
if newItem.key != nil && len(newItem.key) > 0 {
kItem = &gkvlite.Item{
Key: newItem.key,
Val: cBytes,
Priority: rand.Int31(),
Transient: unsafe.Pointer(newItem),
}
}
deltaItemBytes = newItem.NumBytes()
var oldItemCasBytes []byte
if oldItem != nil {
oldItemCasBytes = make([]byte, 8)
casBytesFill(oldItem.cas, oldItemCasBytes)
deltaItemBytes -= oldItem.NumBytes()
}
p.mutate(func(keys, changes *gkvlite.Collection) {
if err = changes.SetItem(cItem); err != nil {
return
}
dirtyForce := false
if newItem.key != nil && len(newItem.key) > 0 {
// TODO: What if we flush between the keys update and changes
// update? That could result in an inconsistent db file?
// Solution idea #1 is to have load-time fixup, that
// incorporates changes into the key-index.
if err = keys.SetItem(kItem); err != nil {
return
}
} else {
dirtyForce = true // An nil/empty key means this is a metadata change.
}
if oldItem != nil {
// TODO: Need a "frozen" CAS point where we don't de-duplicate changes stream.
changes.Delete(oldItemCasBytes)
}
p.parent.dirty(dirtyForce)
if cb != nil {
cb()
}
})
return deltaItemBytes, err
}
示例2: PushPromiseFuzzer
func (fuzzer *Fuzzer) PushPromiseFuzzer() {
fuzzer.CheckConnection()
for fuzzer.Alive {
payloadLength := int32(rand.Intn(10000))
payload := make([]byte, payloadLength)
crand.Read(payload)
promise := http2.PushPromiseParam{
StreamID: uint32(rand.Int31()),
PromiseID: uint32(rand.Int31()),
BlockFragment: payload,
EndHeaders: rand.Int31()%2 == 0,
PadLength: uint8(rand.Intn(256)),
}
fuzzer.Mu.Lock()
fuzzer.Conn.WritePushPromiseFrame(promise)
fuzzer.Mu.Unlock()
time.Sleep(config.FuzzDelay)
fuzzer.CheckConnection()
}
fmt.Println("Stopping PushPromiseFuzzer:", fuzzer.Conn.Err)
}
示例3: Run
func (stream *Stream) Run() {
stream.emit(&trace.StreamStart{
ProcessID: trace.ID(rand.Int31()),
MachineID: trace.ID(rand.Int31()),
Time: stream.advanceTime(0),
Freq: 1e9, // ticks per second
})
for stream.Alive() {
time.Sleep(stream.threadInterval)
stream.advanceTime(rand.Int31n(100))
n := rand.Intn(stream.max.Threads)
if n < len(stream.threads) {
thread := stream.threads[n]
thread.Stop()
stream.threads = append(stream.threads[:n], stream.threads[n+1:]...)
} else {
thread := &Thread{}
thread.stream = stream
thread.id = stream.lastThreadID
stream.lastThreadID++
stream.threads = append(stream.threads, thread)
thread.Start()
}
}
for _, thread := range stream.threads {
thread.Stop()
}
}
示例4: GetShard
func (kv *ShardKV) GetShard(req *GetShardReq, rsp *GetShardRsp) error {
kv.mu.Lock()
// Use a fake operation to synchorize the data
fake := Op{Opr: OpGet, Key: "tmp", Pid: kv.genPid(int(rand.Int31()), int(rand.Int31()))}
kv.sync(fake)
op := Op{Opr: OpLeave, Data: make(map[string]Value)}
rsp.Data = make(map[string]Value)
rsp.ReqData = make(map[string]reqdata)
for k, v := range kv.data {
if req.Shard == key2shard(k) {
DPrintf("Reshard: %s %#v gid:%d seq:%d\n", k, v, kv.gid, kv.cfg.Num)
rsp.Data[k] = v
op.Data[k] = v
pid, val := kv.v.GetByKey(k)
rsp.ReqData[pid] = reqdata{k, val}
}
}
DPrintf("Shard:%#v seq:%d gid:%d\n", kv.cfg.Shards, kv.cfg.Num, kv.gid)
kv.cfg.Shards[req.Shard] = req.Gid
/*
if len(op.Data) > 0 {
op.Pid = kv.genPid(req.Num, req.Shard)
kv.sync(op)
}
*/
kv.mu.Unlock()
return nil
}
示例5: expectAreSameDirectory
func expectAreSameDirectory(dir1, dir2 string) {
// we can't just compare equality of strings, because one may be a symlink
// this happens with temp dir on mac
filename := fmt.Sprintf("%x", rand.Int31())
data := []byte(fmt.Sprintf("%x", rand.Int31()))
Expect(ioutil.WriteFile(filepath.Join(dir1, filename), data, 0600)).To(Succeed())
actualData, err := ioutil.ReadFile(filepath.Join(dir2, filename))
Expect(err).NotTo(HaveOccurred())
Expect(actualData).To(Equal(data))
}
示例6: BenchmarkInt32
// There's no difference between this and int64 benchmarks.
func BenchmarkInt32(b *testing.B) {
rand.Seed(time.Now().UnixNano())
var m, n int32
m = rand.Int31()
n = rand.Int31()
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = m == n
}
}
示例7: newIrcClient
func newIrcClient(conn net.Conn) *ircClient {
c := &ircClient{
conn,
textproto.NewWriter(bufio.NewWriter(conn)),
make(chan []string, 1024),
make(chan string, 1),
make(chan []string, 6),
}
go func() {
var line string
var fields []string
var err error
r := textproto.NewReader(bufio.NewReader(conn))
for {
if line, err = r.ReadLine(); err == nil {
fields = strings.Fields(line)[1:]
if len(fields) > 3 {
switch fields[0] {
case RPL_NAMREPLY:
c.namesReplies <- fields[2:]
case RPL_WHOISUSER, RPL_WHOISSERVER, RPL_WHOISOPERATOR, RPL_WHOISIDLE, RPL_ENDOFWHOIS, RPL_WHOISCHANNELS:
c.whoisReplies <- fields
case RPL_ENDOFNAMES:
default:
if Verbose {
fmt.Fprintln(os.Stderr, "\t ", line)
}
}
} else if len(fields) >= 2 && fields[0] == "PING" {
c.w.PrintfLine("PONG %s", fields[1])
} else {
if Verbose {
fmt.Fprintf(os.Stderr, "got some sort of short unhandled msg %q\n", line)
}
}
} else {
fmt.Fprintln(os.Stderr, err)
conn.Close()
break
}
}
}()
c.w.PrintfLine("NICK fc%x", rand.Int31())
c.w.PrintfLine("USER %x 8 * :%x", rand.Int31(), rand.Int31())
return c
}
示例8: TestBlockAPI
func TestBlockAPI(t *testing.T) {
datastore.OpenTest()
defer datastore.CloseTest()
uuid, _ := initTestRepo()
grayscale := makeGrayscale(uuid, t, "grayscale")
// construct random blocks of data.
numBlockBytes := int32(grayscale.BlockSize().Prod())
testBlocks := 1001
var blockData []byte
for i := 0; i < testBlocks; i++ {
blockData = append(blockData, dvid.RandomBytes(numBlockBytes)...)
}
// set start of span
x := rand.Int31()
y := rand.Int31()
z := rand.Int31()
// Test uncompressed roundtrip
// send the blocks
blockReq := fmt.Sprintf("%snode/%s/grayscale/blocks/%d_%d_%d/%d", server.WebAPIPath, uuid, x, y, z, testBlocks)
server.TestHTTP(t, "POST", blockReq, bytes.NewBuffer(blockData))
// read same span of blocks
returnedData := server.TestHTTP(t, "GET", blockReq, nil)
// make sure blocks are same
totBytes := testBlocks * int(numBlockBytes)
if len(returnedData) != totBytes {
t.Errorf("Returned %d bytes, expected %d bytes", len(returnedData), totBytes)
}
if !reflect.DeepEqual(returnedData, blockData) {
t.Errorf("Returned block data != original block data\n")
}
// We should get blank blocks at different z
z += 1
blockReq = fmt.Sprintf("%snode/%s/grayscale/blocks/%d_%d_%d/%d", server.WebAPIPath, uuid, x, y, z, testBlocks)
returnedData = server.TestHTTP(t, "GET", blockReq, nil)
if len(returnedData) != totBytes {
t.Errorf("Returned %d bytes, expected %d bytes", len(returnedData), totBytes)
}
for i, b := range returnedData {
if b != 0 {
t.Fatalf("Expected 0 at returned byte %d, got %d instead.\n", i, b)
}
}
}
示例9: BLookup
func BLookup(n int) string {
var res bytes.Buffer
for i := 0; i < n; i++ {
res.WriteByte(chars[rand.Int31()&63])
}
return res.String()
}
示例10: clientGo
func clientGo(id int) {
defer wg.Done()
conn, err := net.DialTimeout(SERVER_NETWORK, SERVER_ADDRESS, 2*time.Second)
if err != nil {
printLog("Dial Error: %s (Client[%d])\n", err, id)
return
}
defer conn.Close()
printLog("Connected to server. (remote address: %s, local address: %s) (Client[%d])\n",
conn.RemoteAddr(), conn.LocalAddr(), id)
time.Sleep(200 * time.Millisecond)
requestNumber := 5
conn.SetDeadline(time.Now().Add(5 * time.Millisecond))
for i := 0; i < requestNumber; i++ {
i32Req := rand.Int31()
n, err := write(conn, fmt.Sprintf("%d", i32Req))
if err != nil {
printLog("Write Error: %s (Client[%d])\n", err, id)
continue
}
printLog("Sent request (written %d bytes): %d (Client[%d])\n", n, i32Req, id)
}
for j := 0; j < requestNumber; j++ {
strResp, err := read(conn)
if err != nil {
if err == io.EOF {
printLog("The connection is closed by another side. (Client[%d])\n", id)
} else {
printLog("Read Error: %s (Client[%d])\n", err, id)
}
break
}
printLog("Received response: %s (Client[%d])\n", strResp, id)
}
}
示例11: TestDecodeEncode
func TestDecodeEncode(t *testing.T) {
for i := 0; i < 1000; i++ {
c := rand.Int31()
d := encode(decode(c))
if d != c {
t.Errorf("DecodeEncode(%v) == %v, want %v", i, d, c)
}
}
for i := 0; i < 1000; i++ {
c := -rand.Int31()
d := encode(decode(c))
if d != c {
t.Errorf("DecodeEncode(%v) == %v, want %v", i, d, c)
}
}
}
示例12: main
func main() {
if len(os.Args) != 2 {
fmt.Fprintf(os.Stderr, "usage: %s <elem_count>\n", os.Args[0])
os.Exit(-1)
}
count, err := strconv.Atoi(os.Args[1])
if err != nil {
panic(err)
}
file, err := os.Create("vec_gen.out")
if err != nil {
panic(err)
}
defer file.Close()
bw := bufio.NewWriter(file)
defer func() {
err := bw.Flush()
if err != nil {
log.Fatal(err)
}
}()
for i := 0; i < count; i++ {
r := rand.Int31()
fmt.Fprintf(bw, "%d\n", r)
}
}
示例13: randomId
func (self *Server) randomId() string {
buf := make([]byte, idLength)
for index, _ := range buf {
buf[index] = byte(rand.Int31())
}
return (base64.URLEncoding.EncodeToString(buf))
}
示例14: writeCheckedFile
func writeCheckedFile(r io.ReadCloser, fileName string, checker fileChecker) error {
tmpFile := fileName + ".tmp-" + strconv.FormatInt(int64(rand.Int31()), 16)
f, err := os.Create(tmpFile)
if err != nil {
return err
}
defer r.Close()
defer os.Remove(tmpFile) // make sure temp file always gets removed
_, err = io.Copy(f, r)
f.Close()
if err != nil {
return err
}
f, err = os.Open(tmpFile)
if err != nil {
return err
}
defer f.Close()
if err := checker(f); err != nil {
return err
}
if err := os.Rename(tmpFile, fileName); err != nil {
return err
}
return nil
}
示例15: runClient
func runClient() {
if *server == "" {
log.Printf("Please specify a -server id")
flag.Usage()
return
}
log.Printf("Starting client, connecting to server %s ...", *server)
traversalId := uint32(rand.Int31())
log.Printf("Starting traversal: %d", traversalId)
serverId, err := waddell.PeerIdFromString(*server)
if err != nil {
log.Fatalf("Unable to parse PeerID for server %s: %s", *server, err)
}
t := natty.Offer(TIMEOUT)
defer t.Close()
go sendMessages(t, serverId, traversalId)
go receiveMessages(t, traversalId)
ft, err := t.FiveTuple()
if err != nil {
t.Close()
log.Fatalf("Unable to offer: %s", err)
}
log.Printf("Got five tuple: %s", ft)
if <-serverReady {
writeUDP(ft)
}
}