首页 > 其他分享 >rand.Read() 和 io.ReadFull(rand.Reader) 的区别?

rand.Read() 和 io.ReadFull(rand.Reader) 的区别?

时间:2023-07-18 21:01:18浏览次数:40  
标签:rand Read bytes io Reader ReadFull

golang的随机包 rand.go 中我们可以看到 rand.Read 其实是调用的io.Reader.Read()

1: // Package rand implements a cryptographically secure
 1: // Package rand implements a cryptographically secure
   2: // pseudorandom number generator.
   3: package rand
   4:  
   5: import "io"
   6:  
   7: // Reader is a global, shared instance of a cryptographically
   8: // strong pseudo-random generator.
   9: // On Unix-like systems, Reader reads from /dev/urandom.
  10: // On Windows systems, Reader uses the CryptGenRandom API.
  11: var Reader io.Reader
  12:  
  13: // Read is a helper function that calls Reader.Read.
  14: func Read(b []byte) (n int, err error) { return Reader.Read(b) }

io.Reader.Read() 函数的说明如下:

Read reads up to len(p) bytes into p. It returns the number of bytes read (0 <= n <= len(p)) and any error encountered. Even if Read returns n < len(p), it may use all of p as scratch space during the call. If some data is available but not len(p) bytes, Read conventionally returns what is available instead of waiting for more.

简单来说,它读出的数据,并不一定是指定长度的。

 

io.ReadFull 函数则相反:

ReadFull reads exactly len(buf) bytes from r into buf. It returns the number of bytes copied and an error if fewer bytes were read. The error is EOF only if no bytes were read. If an EOF happens after reading some but not all the bytes, ReadFull returns ErrUnexpectedEOF. On return, n == len(buf) if and only if err == nil.

读取正好len(buf)长度的字节。如果字节数不是指定长度,则返回错误信息和正确的字节数。

当没有字节能被读时,返回EOF错误。

如果读了一些,但是没读完产生EOF错误时,返回ErrUnexpectedEOF错误。

综上对比,获取随机数时,最好是下面的写法。

 1: import crand "crypto/rand"
   2:  
   3: r := make([]byte, length)
   4:  
   5: if _, err := io.ReadFull(crand.Reader, r); err != nil {
   6:     panic("error reading from random source: " + err.Error())
   7: }
 
7: }

 

参考资料:

rand.Read() or io.ReadFull(rand.Reader)?
https://groups.google.com/forum/#!topic/golang-nuts/eFS5GN-en3w

标签:rand,Read,bytes,io,Reader,ReadFull
From: https://blog.51cto.com/u_15588078/6768348

相关文章

  • MIT6.s081/6.828 lectrue1:Introduction and examples
    目前课程官网能够查到2020,2021.2022秋季的课程表,但是视频都是2020年录制的那一版简单复习+回顾下自己的OS学习之旅参考资料:官网:https://pdos.csail.mit.edu/6.828/2022/schedule.html视频翻译:https://mit-public-courses-cn-translatio.gitbook.io/mit6-s081/教材英文......
  • The file extension is not supported by Shapefile data provider.
     后端返回:文件上传失败:Thefileextension isnotsupportedbyShapefiledataprovider. 表明此时上传/处理的文件不符合标准。 ......
  • [Typescript] 150 Hard - OptionalUndefined
    Implementtheutiltype OptionalUndefined<T,Props> thatturnsallthepropertiesof T thatcanbe undefined,intooptionalproperties.Inaddition,asecond-optional-generic Props canbepassedtorestrictthepropertiesthatcanbealtered.Opti......
  • poj 1632 Vase collection
    题意:有n个花瓶,每个花瓶都带有两种属性-形状和颜色,而每种属性都有36种不同的状态。求最大的k,使得k*k个花瓶的形状和颜色都有k种状态,且k*k个花瓶的两种属性都是由形状和颜色的k种状态组合而成的。题解:我们用一个数组(comb[])存放形状和颜色,数组的下标为形状,然后将颜色状态压缩成为数组......
  • 洛谷 P8923 -『MdOI R5』Many Minimizations
    怎么ARC还能撞题的?只能说Kubic牛逼。首先显然没法保序回归。考虑用类似于凸壳优化DP的做法解决原问题(也就是P4331):设\(dp_{i,j}\)表示考虑前\(i\)位,\(x_i=j\)的最小代价,显然有\(dp_{i,j}=\min_{k\lej}\{dp_{i-1,k}+|j-a_i|\}\)\(dp\)值显然是一个折线,用堆维护斜......
  • POJ 1410 Intersection
    判断线段与多边形是否相交。模板:#include<stdio.h>#include<math.h>#include<algorithm>usingnamespacestd;#definePi3.14159265358979#definePRECISION1e-8//点typedefstruct{doublex,y;}POINT;//直线两点的表达structLINE{POINTp1,p2;};......
  • 加速github访问、git使用及其原理、错误error: remote origin already exists,error: s
    访问GithubGithub:https://github.com修改hosts1.在C:\Windows\System32\drivers\etc找到hosts2.将hosts文件复制到其他位置(D盘等等),再复制一份备份3.将#github20.205.243.166github.com185.199.108.153assets-cdn.github.com添加到hosts最后面保存(最新2023/07/1......
  • 详细说明Python中的Condition类(转)
    addbyzhj: 之前只知道在Queue的实现中使用了Condition对象,可以实现生产者消费者功能,但具体怎么使用Condition还是一知半解,看了这篇文章,终于懂了。很多事情往往一时看不明白,看得多了,某一天就突然明白了。 原文:https://blog.csdn.net/ckk727/article/details/99950843作者:二......
  • These are the list of external providers available to the application.
    Thesearethelistofexternalprovidersavailabletotheapplication.https://github.com/davidfowl/TodoApi/blob/c209f6ae5c5f31f4808b0df85f358d4a572ea770/Todo.Web/Server/Authentication/AuthenticationExtensions.cs#L42 ......
  • 翻译文件存到sessionStorage,减少请求
    测试本地翻译文件,格式正不正确,检查JSON格式可以一部分str_info_english1.js,一部分的检查,是否报错<script>functionfoo(){varformData=newFormData();//提交表单varxhr=newXMLHttpRequest();xhr......