buffer_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package bytes_test
  5. import (
  6. . "bytes"
  7. "io"
  8. "math/rand"
  9. "runtime"
  10. "testing"
  11. "unicode/utf8"
  12. )
  13. const N = 10000 // make this bigger for a larger (and slower) test
  14. var data string // test data for write tests
  15. var testBytes []byte // test data; same as data but as a slice.
  16. func init() {
  17. testBytes = make([]byte, N)
  18. for i := 0; i < N; i++ {
  19. testBytes[i] = 'a' + byte(i%26)
  20. }
  21. data = string(testBytes)
  22. }
  23. // Verify that contents of buf match the string s.
  24. func check(t *testing.T, testname string, buf *Buffer, s string) {
  25. bytes := buf.Bytes()
  26. str := buf.String()
  27. if buf.Len() != len(bytes) {
  28. t.Errorf("%s: buf.Len() == %d, len(buf.Bytes()) == %d", testname, buf.Len(), len(bytes))
  29. }
  30. if buf.Len() != len(str) {
  31. t.Errorf("%s: buf.Len() == %d, len(buf.String()) == %d", testname, buf.Len(), len(str))
  32. }
  33. if buf.Len() != len(s) {
  34. t.Errorf("%s: buf.Len() == %d, len(s) == %d", testname, buf.Len(), len(s))
  35. }
  36. if string(bytes) != s {
  37. t.Errorf("%s: string(buf.Bytes()) == %q, s == %q", testname, string(bytes), s)
  38. }
  39. }
  40. // Fill buf through n writes of string fus.
  41. // The initial contents of buf corresponds to the string s;
  42. // the result is the final contents of buf returned as a string.
  43. func fillString(t *testing.T, testname string, buf *Buffer, s string, n int, fus string) string {
  44. check(t, testname+" (fill 1)", buf, s)
  45. for ; n > 0; n-- {
  46. m, err := buf.WriteString(fus)
  47. if m != len(fus) {
  48. t.Errorf(testname+" (fill 2): m == %d, expected %d", m, len(fus))
  49. }
  50. if err != nil {
  51. t.Errorf(testname+" (fill 3): err should always be nil, found err == %s", err)
  52. }
  53. s += fus
  54. check(t, testname+" (fill 4)", buf, s)
  55. }
  56. return s
  57. }
  58. // Fill buf through n writes of byte slice fub.
  59. // The initial contents of buf corresponds to the string s;
  60. // the result is the final contents of buf returned as a string.
  61. func fillBytes(t *testing.T, testname string, buf *Buffer, s string, n int, fub []byte) string {
  62. check(t, testname+" (fill 1)", buf, s)
  63. for ; n > 0; n-- {
  64. m, err := buf.Write(fub)
  65. if m != len(fub) {
  66. t.Errorf(testname+" (fill 2): m == %d, expected %d", m, len(fub))
  67. }
  68. if err != nil {
  69. t.Errorf(testname+" (fill 3): err should always be nil, found err == %s", err)
  70. }
  71. s += string(fub)
  72. check(t, testname+" (fill 4)", buf, s)
  73. }
  74. return s
  75. }
  76. func TestNewBuffer(t *testing.T) {
  77. buf := NewBuffer(testBytes)
  78. check(t, "NewBuffer", buf, data)
  79. }
  80. func TestNewBufferString(t *testing.T) {
  81. buf := NewBufferString(data)
  82. check(t, "NewBufferString", buf, data)
  83. }
  84. // Empty buf through repeated reads into fub.
  85. // The initial contents of buf corresponds to the string s.
  86. func empty(t *testing.T, testname string, buf *Buffer, s string, fub []byte) {
  87. check(t, testname+" (empty 1)", buf, s)
  88. for {
  89. n, err := buf.Read(fub)
  90. if n == 0 {
  91. break
  92. }
  93. if err != nil {
  94. t.Errorf(testname+" (empty 2): err should always be nil, found err == %s", err)
  95. }
  96. s = s[n:]
  97. check(t, testname+" (empty 3)", buf, s)
  98. }
  99. check(t, testname+" (empty 4)", buf, "")
  100. }
  101. func TestBasicOperations(t *testing.T) {
  102. var buf Buffer
  103. for i := 0; i < 5; i++ {
  104. check(t, "TestBasicOperations (1)", &buf, "")
  105. buf.Reset()
  106. check(t, "TestBasicOperations (2)", &buf, "")
  107. buf.Truncate(0)
  108. check(t, "TestBasicOperations (3)", &buf, "")
  109. n, err := buf.Write([]byte(data[0:1]))
  110. if n != 1 {
  111. t.Errorf("wrote 1 byte, but n == %d", n)
  112. }
  113. if err != nil {
  114. t.Errorf("err should always be nil, but err == %s", err)
  115. }
  116. check(t, "TestBasicOperations (4)", &buf, "a")
  117. buf.WriteByte(data[1])
  118. check(t, "TestBasicOperations (5)", &buf, "ab")
  119. n, err = buf.Write([]byte(data[2:26]))
  120. if n != 24 {
  121. t.Errorf("wrote 25 bytes, but n == %d", n)
  122. }
  123. check(t, "TestBasicOperations (6)", &buf, string(data[0:26]))
  124. buf.Truncate(26)
  125. check(t, "TestBasicOperations (7)", &buf, string(data[0:26]))
  126. buf.Truncate(20)
  127. check(t, "TestBasicOperations (8)", &buf, string(data[0:20]))
  128. empty(t, "TestBasicOperations (9)", &buf, string(data[0:20]), make([]byte, 5))
  129. empty(t, "TestBasicOperations (10)", &buf, "", make([]byte, 100))
  130. buf.WriteByte(data[1])
  131. c, err := buf.ReadByte()
  132. if err != nil {
  133. t.Error("ReadByte unexpected eof")
  134. }
  135. if c != data[1] {
  136. t.Errorf("ReadByte wrong value c=%v", c)
  137. }
  138. c, err = buf.ReadByte()
  139. if err == nil {
  140. t.Error("ReadByte unexpected not eof")
  141. }
  142. }
  143. }
  144. func TestLargeStringWrites(t *testing.T) {
  145. var buf Buffer
  146. limit := 30
  147. if testing.Short() {
  148. limit = 9
  149. }
  150. for i := 3; i < limit; i += 3 {
  151. s := fillString(t, "TestLargeWrites (1)", &buf, "", 5, data)
  152. empty(t, "TestLargeStringWrites (2)", &buf, s, make([]byte, len(data)/i))
  153. }
  154. check(t, "TestLargeStringWrites (3)", &buf, "")
  155. }
  156. func TestLargeByteWrites(t *testing.T) {
  157. var buf Buffer
  158. limit := 30
  159. if testing.Short() {
  160. limit = 9
  161. }
  162. for i := 3; i < limit; i += 3 {
  163. s := fillBytes(t, "TestLargeWrites (1)", &buf, "", 5, testBytes)
  164. empty(t, "TestLargeByteWrites (2)", &buf, s, make([]byte, len(data)/i))
  165. }
  166. check(t, "TestLargeByteWrites (3)", &buf, "")
  167. }
  168. func TestLargeStringReads(t *testing.T) {
  169. var buf Buffer
  170. for i := 3; i < 30; i += 3 {
  171. s := fillString(t, "TestLargeReads (1)", &buf, "", 5, data[0:len(data)/i])
  172. empty(t, "TestLargeReads (2)", &buf, s, make([]byte, len(data)))
  173. }
  174. check(t, "TestLargeStringReads (3)", &buf, "")
  175. }
  176. func TestLargeByteReads(t *testing.T) {
  177. var buf Buffer
  178. for i := 3; i < 30; i += 3 {
  179. s := fillBytes(t, "TestLargeReads (1)", &buf, "", 5, testBytes[0:len(testBytes)/i])
  180. empty(t, "TestLargeReads (2)", &buf, s, make([]byte, len(data)))
  181. }
  182. check(t, "TestLargeByteReads (3)", &buf, "")
  183. }
  184. func TestMixedReadsAndWrites(t *testing.T) {
  185. var buf Buffer
  186. s := ""
  187. for i := 0; i < 50; i++ {
  188. wlen := rand.Intn(len(data))
  189. if i%2 == 0 {
  190. s = fillString(t, "TestMixedReadsAndWrites (1)", &buf, s, 1, data[0:wlen])
  191. } else {
  192. s = fillBytes(t, "TestMixedReadsAndWrites (1)", &buf, s, 1, testBytes[0:wlen])
  193. }
  194. rlen := rand.Intn(len(data))
  195. fub := make([]byte, rlen)
  196. n, _ := buf.Read(fub)
  197. s = s[n:]
  198. }
  199. empty(t, "TestMixedReadsAndWrites (2)", &buf, s, make([]byte, buf.Len()))
  200. }
  201. func TestNil(t *testing.T) {
  202. var b *Buffer
  203. if b.String() != "<nil>" {
  204. t.Errorf("expected <nil>; got %q", b.String())
  205. }
  206. }
  207. func TestReadFrom(t *testing.T) {
  208. var buf Buffer
  209. for i := 3; i < 30; i += 3 {
  210. s := fillBytes(t, "TestReadFrom (1)", &buf, "", 5, testBytes[0:len(testBytes)/i])
  211. var b Buffer
  212. b.ReadFrom(&buf)
  213. empty(t, "TestReadFrom (2)", &b, s, make([]byte, len(data)))
  214. }
  215. }
  216. func TestWriteTo(t *testing.T) {
  217. var buf Buffer
  218. for i := 3; i < 30; i += 3 {
  219. s := fillBytes(t, "TestWriteTo (1)", &buf, "", 5, testBytes[0:len(testBytes)/i])
  220. var b Buffer
  221. buf.WriteTo(&b)
  222. empty(t, "TestWriteTo (2)", &b, s, make([]byte, len(data)))
  223. }
  224. }
  225. func TestRuneIO(t *testing.T) {
  226. const NRune = 1000
  227. // Built a test slice while we write the data
  228. b := make([]byte, utf8.UTFMax*NRune)
  229. var buf Buffer
  230. n := 0
  231. for r := rune(0); r < NRune; r++ {
  232. size := utf8.EncodeRune(b[n:], r)
  233. nbytes, err := buf.WriteRune(r)
  234. if err != nil {
  235. t.Fatalf("WriteRune(%U) error: %s", r, err)
  236. }
  237. if nbytes != size {
  238. t.Fatalf("WriteRune(%U) expected %d, got %d", r, size, nbytes)
  239. }
  240. n += size
  241. }
  242. b = b[0:n]
  243. // Check the resulting bytes
  244. if !Equal(buf.Bytes(), b) {
  245. t.Fatalf("incorrect result from WriteRune: %q not %q", buf.Bytes(), b)
  246. }
  247. p := make([]byte, utf8.UTFMax)
  248. // Read it back with ReadRune
  249. for r := rune(0); r < NRune; r++ {
  250. size := utf8.EncodeRune(p, r)
  251. nr, nbytes, err := buf.ReadRune()
  252. if nr != r || nbytes != size || err != nil {
  253. t.Fatalf("ReadRune(%U) got %U,%d not %U,%d (err=%s)", r, nr, nbytes, r, size, err)
  254. }
  255. }
  256. // Check that UnreadRune works
  257. buf.Reset()
  258. buf.Write(b)
  259. for r := rune(0); r < NRune; r++ {
  260. r1, size, _ := buf.ReadRune()
  261. if err := buf.UnreadRune(); err != nil {
  262. t.Fatalf("UnreadRune(%U) got error %q", r, err)
  263. }
  264. r2, nbytes, err := buf.ReadRune()
  265. if r1 != r2 || r1 != r || nbytes != size || err != nil {
  266. t.Fatalf("ReadRune(%U) after UnreadRune got %U,%d not %U,%d (err=%s)", r, r2, nbytes, r, size, err)
  267. }
  268. }
  269. }
  270. func TestNext(t *testing.T) {
  271. b := []byte{0, 1, 2, 3, 4}
  272. tmp := make([]byte, 5)
  273. for i := 0; i <= 5; i++ {
  274. for j := i; j <= 5; j++ {
  275. for k := 0; k <= 6; k++ {
  276. // 0 <= i <= j <= 5; 0 <= k <= 6
  277. // Check that if we start with a buffer
  278. // of length j at offset i and ask for
  279. // Next(k), we get the right bytes.
  280. buf := NewBuffer(b[0:j])
  281. n, _ := buf.Read(tmp[0:i])
  282. if n != i {
  283. t.Fatalf("Read %d returned %d", i, n)
  284. }
  285. bb := buf.Next(k)
  286. want := k
  287. if want > j-i {
  288. want = j - i
  289. }
  290. if len(bb) != want {
  291. t.Fatalf("in %d,%d: len(Next(%d)) == %d", i, j, k, len(bb))
  292. }
  293. for l, v := range bb {
  294. if v != byte(l+i) {
  295. t.Fatalf("in %d,%d: Next(%d)[%d] = %d, want %d", i, j, k, l, v, l+i)
  296. }
  297. }
  298. }
  299. }
  300. }
  301. }
  302. var readBytesTests = []struct {
  303. buffer string
  304. delim byte
  305. expected []string
  306. err error
  307. }{
  308. {"", 0, []string{""}, io.EOF},
  309. {"a\x00", 0, []string{"a\x00"}, nil},
  310. {"abbbaaaba", 'b', []string{"ab", "b", "b", "aaab"}, nil},
  311. {"hello\x01world", 1, []string{"hello\x01"}, nil},
  312. {"foo\nbar", 0, []string{"foo\nbar"}, io.EOF},
  313. {"alpha\nbeta\ngamma\n", '\n', []string{"alpha\n", "beta\n", "gamma\n"}, nil},
  314. {"alpha\nbeta\ngamma", '\n', []string{"alpha\n", "beta\n", "gamma"}, io.EOF},
  315. }
  316. func TestReadBytes(t *testing.T) {
  317. for _, test := range readBytesTests {
  318. buf := NewBufferString(test.buffer)
  319. var err error
  320. for _, expected := range test.expected {
  321. var bytes []byte
  322. bytes, err = buf.ReadBytes(test.delim)
  323. if string(bytes) != expected {
  324. t.Errorf("expected %q, got %q", expected, bytes)
  325. }
  326. if err != nil {
  327. break
  328. }
  329. }
  330. if err != test.err {
  331. t.Errorf("expected error %v, got %v", test.err, err)
  332. }
  333. }
  334. }
  335. func TestReadString(t *testing.T) {
  336. for _, test := range readBytesTests {
  337. buf := NewBufferString(test.buffer)
  338. var err error
  339. for _, expected := range test.expected {
  340. var s string
  341. s, err = buf.ReadString(test.delim)
  342. if s != expected {
  343. t.Errorf("expected %q, got %q", expected, s)
  344. }
  345. if err != nil {
  346. break
  347. }
  348. }
  349. if err != test.err {
  350. t.Errorf("expected error %v, got %v", test.err, err)
  351. }
  352. }
  353. }
  354. func BenchmarkReadString(b *testing.B) {
  355. const n = 32 << 10
  356. data := make([]byte, n)
  357. data[n-1] = 'x'
  358. b.SetBytes(int64(n))
  359. for i := 0; i < b.N; i++ {
  360. buf := NewBuffer(data)
  361. _, err := buf.ReadString('x')
  362. if err != nil {
  363. b.Fatal(err)
  364. }
  365. }
  366. }
  367. func TestGrow(t *testing.T) {
  368. x := []byte{'x'}
  369. y := []byte{'y'}
  370. tmp := make([]byte, 72)
  371. for _, startLen := range []int{0, 100, 1000, 10000, 100000} {
  372. xBytes := Repeat(x, startLen)
  373. for _, growLen := range []int{0, 100, 1000, 10000, 100000} {
  374. buf := NewBuffer(xBytes)
  375. // If we read, this affects buf.off, which is good to test.
  376. readBytes, _ := buf.Read(tmp)
  377. buf.Grow(growLen)
  378. yBytes := Repeat(y, growLen)
  379. // Check no allocation occurs in write, as long as we're single-threaded.
  380. var m1, m2 runtime.MemStats
  381. runtime.ReadMemStats(&m1)
  382. buf.Write(yBytes)
  383. runtime.ReadMemStats(&m2)
  384. if runtime.GOMAXPROCS(-1) == 1 && m1.Mallocs != m2.Mallocs {
  385. t.Errorf("allocation occurred during write")
  386. }
  387. // Check that buffer has correct data.
  388. if !Equal(buf.Bytes()[0:startLen-readBytes], xBytes[readBytes:]) {
  389. t.Errorf("bad initial data at %d %d", startLen, growLen)
  390. }
  391. if !Equal(buf.Bytes()[startLen-readBytes:startLen-readBytes+growLen], yBytes) {
  392. t.Errorf("bad written data at %d %d", startLen, growLen)
  393. }
  394. }
  395. }
  396. }
  397. // Was a bug: used to give EOF reading empty slice at EOF.
  398. func TestReadEmptyAtEOF(t *testing.T) {
  399. b := new(Buffer)
  400. slice := make([]byte, 0)
  401. n, err := b.Read(slice)
  402. if err != nil {
  403. t.Errorf("read error: %v", err)
  404. }
  405. if n != 0 {
  406. t.Errorf("wrong count; got %d want 0", n)
  407. }
  408. }
  409. func TestUnreadByte(t *testing.T) {
  410. b := new(Buffer)
  411. b.WriteString("abcdefghijklmnopqrstuvwxyz")
  412. _, err := b.ReadBytes('m')
  413. if err != nil {
  414. t.Fatalf("ReadBytes: %v", err)
  415. }
  416. err = b.UnreadByte()
  417. if err != nil {
  418. t.Fatalf("UnreadByte: %v", err)
  419. }
  420. c, err := b.ReadByte()
  421. if err != nil {
  422. t.Fatalf("ReadByte: %v", err)
  423. }
  424. if c != 'm' {
  425. t.Errorf("ReadByte = %q; want %q", c, 'm')
  426. }
  427. }
  428. // Tests that we occasionally compact. Issue 5154.
  429. func TestBufferGrowth(t *testing.T) {
  430. var b Buffer
  431. buf := make([]byte, 1024)
  432. b.Write(buf[0:1])
  433. var cap0 int
  434. for i := 0; i < 5<<10; i++ {
  435. b.Write(buf)
  436. b.Read(buf)
  437. if i == 0 {
  438. cap0 = b.Cap()
  439. }
  440. }
  441. cap1 := b.Cap()
  442. // (*Buffer).grow allows for 2x capacity slop before sliding,
  443. // so set our error threshold at 3x.
  444. if cap1 > cap0*3 {
  445. t.Errorf("buffer cap = %d; too big (grew from %d)", cap1, cap0)
  446. }
  447. }
  448. // From Issue 5154.
  449. func BenchmarkBufferNotEmptyWriteRead(b *testing.B) {
  450. buf := make([]byte, 1024)
  451. for i := 0; i < b.N; i++ {
  452. var b Buffer
  453. b.Write(buf[0:1])
  454. for i := 0; i < 5<<10; i++ {
  455. b.Write(buf)
  456. b.Read(buf)
  457. }
  458. }
  459. }
  460. // Check that we don't compact too often. From Issue 5154.
  461. func BenchmarkBufferFullSmallReads(b *testing.B) {
  462. buf := make([]byte, 1024)
  463. for i := 0; i < b.N; i++ {
  464. var b Buffer
  465. b.Write(buf)
  466. for b.Len()+20 < b.Cap() {
  467. b.Write(buf[:10])
  468. }
  469. for i := 0; i < 5<<10; i++ {
  470. b.Read(buf[:1])
  471. b.Write(buf[:1])
  472. }
  473. }
  474. }