bufio_test.go 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572
  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 bufio_test
  5. import (
  6. . "bufio"
  7. "bytes"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "io/ioutil"
  12. "strings"
  13. "testing"
  14. "testing/iotest"
  15. "time"
  16. "unicode/utf8"
  17. )
  18. // Reads from a reader and rot13s the result.
  19. type rot13Reader struct {
  20. r io.Reader
  21. }
  22. func newRot13Reader(r io.Reader) *rot13Reader {
  23. r13 := new(rot13Reader)
  24. r13.r = r
  25. return r13
  26. }
  27. func (r13 *rot13Reader) Read(p []byte) (int, error) {
  28. n, err := r13.r.Read(p)
  29. for i := 0; i < n; i++ {
  30. c := p[i] | 0x20 // lowercase byte
  31. if 'a' <= c && c <= 'm' {
  32. p[i] += 13
  33. } else if 'n' <= c && c <= 'z' {
  34. p[i] -= 13
  35. }
  36. }
  37. return n, err
  38. }
  39. // Call ReadByte to accumulate the text of a file
  40. func readBytes(buf *Reader) string {
  41. var b [1000]byte
  42. nb := 0
  43. for {
  44. c, err := buf.ReadByte()
  45. if err == io.EOF {
  46. break
  47. }
  48. if err == nil {
  49. b[nb] = c
  50. nb++
  51. } else if err != iotest.ErrTimeout {
  52. panic("Data: " + err.Error())
  53. }
  54. }
  55. return string(b[0:nb])
  56. }
  57. func TestReaderSimple(t *testing.T) {
  58. data := "hello world"
  59. b := NewReader(strings.NewReader(data))
  60. if s := readBytes(b); s != "hello world" {
  61. t.Errorf("simple hello world test failed: got %q", s)
  62. }
  63. b = NewReader(newRot13Reader(strings.NewReader(data)))
  64. if s := readBytes(b); s != "uryyb jbeyq" {
  65. t.Errorf("rot13 hello world test failed: got %q", s)
  66. }
  67. }
  68. type readMaker struct {
  69. name string
  70. fn func(io.Reader) io.Reader
  71. }
  72. var readMakers = []readMaker{
  73. {"full", func(r io.Reader) io.Reader { return r }},
  74. {"byte", iotest.OneByteReader},
  75. {"half", iotest.HalfReader},
  76. {"data+err", iotest.DataErrReader},
  77. {"timeout", iotest.TimeoutReader},
  78. }
  79. // Call ReadString (which ends up calling everything else)
  80. // to accumulate the text of a file.
  81. func readLines(b *Reader) string {
  82. s := ""
  83. for {
  84. s1, err := b.ReadString('\n')
  85. if err == io.EOF {
  86. break
  87. }
  88. if err != nil && err != iotest.ErrTimeout {
  89. panic("GetLines: " + err.Error())
  90. }
  91. s += s1
  92. }
  93. return s
  94. }
  95. // Call Read to accumulate the text of a file
  96. func reads(buf *Reader, m int) string {
  97. var b [1000]byte
  98. nb := 0
  99. for {
  100. n, err := buf.Read(b[nb : nb+m])
  101. nb += n
  102. if err == io.EOF {
  103. break
  104. }
  105. }
  106. return string(b[0:nb])
  107. }
  108. type bufReader struct {
  109. name string
  110. fn func(*Reader) string
  111. }
  112. var bufreaders = []bufReader{
  113. {"1", func(b *Reader) string { return reads(b, 1) }},
  114. {"2", func(b *Reader) string { return reads(b, 2) }},
  115. {"3", func(b *Reader) string { return reads(b, 3) }},
  116. {"4", func(b *Reader) string { return reads(b, 4) }},
  117. {"5", func(b *Reader) string { return reads(b, 5) }},
  118. {"7", func(b *Reader) string { return reads(b, 7) }},
  119. {"bytes", readBytes},
  120. {"lines", readLines},
  121. }
  122. const minReadBufferSize = 16
  123. var bufsizes = []int{
  124. 0, minReadBufferSize, 23, 32, 46, 64, 93, 128, 1024, 4096,
  125. }
  126. func TestReader(t *testing.T) {
  127. var texts [31]string
  128. str := ""
  129. all := ""
  130. for i := 0; i < len(texts)-1; i++ {
  131. texts[i] = str + "\n"
  132. all += texts[i]
  133. str += string(i%26 + 'a')
  134. }
  135. texts[len(texts)-1] = all
  136. for h := 0; h < len(texts); h++ {
  137. text := texts[h]
  138. for i := 0; i < len(readMakers); i++ {
  139. for j := 0; j < len(bufreaders); j++ {
  140. for k := 0; k < len(bufsizes); k++ {
  141. readmaker := readMakers[i]
  142. bufreader := bufreaders[j]
  143. bufsize := bufsizes[k]
  144. read := readmaker.fn(strings.NewReader(text))
  145. buf := NewReaderSize(read, bufsize)
  146. s := bufreader.fn(buf)
  147. if s != text {
  148. t.Errorf("reader=%s fn=%s bufsize=%d want=%q got=%q",
  149. readmaker.name, bufreader.name, bufsize, text, s)
  150. }
  151. }
  152. }
  153. }
  154. }
  155. }
  156. type zeroReader struct{}
  157. func (zeroReader) Read(p []byte) (int, error) {
  158. return 0, nil
  159. }
  160. func TestZeroReader(t *testing.T) {
  161. var z zeroReader
  162. r := NewReader(z)
  163. c := make(chan error)
  164. go func() {
  165. _, err := r.ReadByte()
  166. c <- err
  167. }()
  168. select {
  169. case err := <-c:
  170. if err == nil {
  171. t.Error("error expected")
  172. } else if err != io.ErrNoProgress {
  173. t.Error("unexpected error:", err)
  174. }
  175. case <-time.After(time.Second):
  176. t.Error("test timed out (endless loop in ReadByte?)")
  177. }
  178. }
  179. // A StringReader delivers its data one string segment at a time via Read.
  180. type StringReader struct {
  181. data []string
  182. step int
  183. }
  184. func (r *StringReader) Read(p []byte) (n int, err error) {
  185. if r.step < len(r.data) {
  186. s := r.data[r.step]
  187. n = copy(p, s)
  188. r.step++
  189. } else {
  190. err = io.EOF
  191. }
  192. return
  193. }
  194. func readRuneSegments(t *testing.T, segments []string) {
  195. got := ""
  196. want := strings.Join(segments, "")
  197. r := NewReader(&StringReader{data: segments})
  198. for {
  199. r, _, err := r.ReadRune()
  200. if err != nil {
  201. if err != io.EOF {
  202. return
  203. }
  204. break
  205. }
  206. got += string(r)
  207. }
  208. if got != want {
  209. t.Errorf("segments=%v got=%s want=%s", segments, got, want)
  210. }
  211. }
  212. var segmentList = [][]string{
  213. {},
  214. {""},
  215. {"日", "本語"},
  216. {"\u65e5", "\u672c", "\u8a9e"},
  217. {"\U000065e5", "\U0000672c", "\U00008a9e"},
  218. {"\xe6", "\x97\xa5\xe6", "\x9c\xac\xe8\xaa\x9e"},
  219. {"Hello", ", ", "World", "!"},
  220. {"Hello", ", ", "", "World", "!"},
  221. }
  222. func TestReadRune(t *testing.T) {
  223. for _, s := range segmentList {
  224. readRuneSegments(t, s)
  225. }
  226. }
  227. func TestUnreadRune(t *testing.T) {
  228. segments := []string{"Hello, world:", "日本語"}
  229. r := NewReader(&StringReader{data: segments})
  230. got := ""
  231. want := strings.Join(segments, "")
  232. // Normal execution.
  233. for {
  234. r1, _, err := r.ReadRune()
  235. if err != nil {
  236. if err != io.EOF {
  237. t.Error("unexpected error on ReadRune:", err)
  238. }
  239. break
  240. }
  241. got += string(r1)
  242. // Put it back and read it again.
  243. if err = r.UnreadRune(); err != nil {
  244. t.Fatal("unexpected error on UnreadRune:", err)
  245. }
  246. r2, _, err := r.ReadRune()
  247. if err != nil {
  248. t.Fatal("unexpected error reading after unreading:", err)
  249. }
  250. if r1 != r2 {
  251. t.Fatalf("incorrect rune after unread: got %c, want %c", r1, r2)
  252. }
  253. }
  254. if got != want {
  255. t.Errorf("got %q, want %q", got, want)
  256. }
  257. }
  258. func TestUnreadByte(t *testing.T) {
  259. segments := []string{"Hello, ", "world"}
  260. r := NewReader(&StringReader{data: segments})
  261. got := ""
  262. want := strings.Join(segments, "")
  263. // Normal execution.
  264. for {
  265. b1, err := r.ReadByte()
  266. if err != nil {
  267. if err != io.EOF {
  268. t.Error("unexpected error on ReadByte:", err)
  269. }
  270. break
  271. }
  272. got += string(b1)
  273. // Put it back and read it again.
  274. if err = r.UnreadByte(); err != nil {
  275. t.Fatal("unexpected error on UnreadByte:", err)
  276. }
  277. b2, err := r.ReadByte()
  278. if err != nil {
  279. t.Fatal("unexpected error reading after unreading:", err)
  280. }
  281. if b1 != b2 {
  282. t.Fatalf("incorrect byte after unread: got %q, want %q", b1, b2)
  283. }
  284. }
  285. if got != want {
  286. t.Errorf("got %q, want %q", got, want)
  287. }
  288. }
  289. func TestUnreadByteMultiple(t *testing.T) {
  290. segments := []string{"Hello, ", "world"}
  291. data := strings.Join(segments, "")
  292. for n := 0; n <= len(data); n++ {
  293. r := NewReader(&StringReader{data: segments})
  294. // Read n bytes.
  295. for i := 0; i < n; i++ {
  296. b, err := r.ReadByte()
  297. if err != nil {
  298. t.Fatalf("n = %d: unexpected error on ReadByte: %v", n, err)
  299. }
  300. if b != data[i] {
  301. t.Fatalf("n = %d: incorrect byte returned from ReadByte: got %q, want %q", n, b, data[i])
  302. }
  303. }
  304. // Unread one byte if there is one.
  305. if n > 0 {
  306. if err := r.UnreadByte(); err != nil {
  307. t.Errorf("n = %d: unexpected error on UnreadByte: %v", n, err)
  308. }
  309. }
  310. // Test that we cannot unread any further.
  311. if err := r.UnreadByte(); err == nil {
  312. t.Errorf("n = %d: expected error on UnreadByte", n)
  313. }
  314. }
  315. }
  316. func TestUnreadByteOthers(t *testing.T) {
  317. // A list of readers to use in conjunction with UnreadByte.
  318. var readers = []func(*Reader, byte) ([]byte, error){
  319. (*Reader).ReadBytes,
  320. (*Reader).ReadSlice,
  321. func(r *Reader, delim byte) ([]byte, error) {
  322. data, err := r.ReadString(delim)
  323. return []byte(data), err
  324. },
  325. // ReadLine doesn't fit the data/pattern easily
  326. // so we leave it out. It should be covered via
  327. // the ReadSlice test since ReadLine simply calls
  328. // ReadSlice, and it's that function that handles
  329. // the last byte.
  330. }
  331. // Try all readers with UnreadByte.
  332. for rno, read := range readers {
  333. // Some input data that is longer than the minimum reader buffer size.
  334. const n = 10
  335. var buf bytes.Buffer
  336. for i := 0; i < n; i++ {
  337. buf.WriteString("abcdefg")
  338. }
  339. r := NewReaderSize(&buf, minReadBufferSize)
  340. readTo := func(delim byte, want string) {
  341. data, err := read(r, delim)
  342. if err != nil {
  343. t.Fatalf("#%d: unexpected error reading to %c: %v", rno, delim, err)
  344. }
  345. if got := string(data); got != want {
  346. t.Fatalf("#%d: got %q, want %q", rno, got, want)
  347. }
  348. }
  349. // Read the data with occasional UnreadByte calls.
  350. for i := 0; i < n; i++ {
  351. readTo('d', "abcd")
  352. for j := 0; j < 3; j++ {
  353. if err := r.UnreadByte(); err != nil {
  354. t.Fatalf("#%d: unexpected error on UnreadByte: %v", rno, err)
  355. }
  356. readTo('d', "d")
  357. }
  358. readTo('g', "efg")
  359. }
  360. // All data should have been read.
  361. _, err := r.ReadByte()
  362. if err != io.EOF {
  363. t.Errorf("#%d: got error %v; want EOF", rno, err)
  364. }
  365. }
  366. }
  367. // Test that UnreadRune fails if the preceding operation was not a ReadRune.
  368. func TestUnreadRuneError(t *testing.T) {
  369. buf := make([]byte, 3) // All runes in this test are 3 bytes long
  370. r := NewReader(&StringReader{data: []string{"日本語日本語日本語"}})
  371. if r.UnreadRune() == nil {
  372. t.Error("expected error on UnreadRune from fresh buffer")
  373. }
  374. _, _, err := r.ReadRune()
  375. if err != nil {
  376. t.Error("unexpected error on ReadRune (1):", err)
  377. }
  378. if err = r.UnreadRune(); err != nil {
  379. t.Error("unexpected error on UnreadRune (1):", err)
  380. }
  381. if r.UnreadRune() == nil {
  382. t.Error("expected error after UnreadRune (1)")
  383. }
  384. // Test error after Read.
  385. _, _, err = r.ReadRune() // reset state
  386. if err != nil {
  387. t.Error("unexpected error on ReadRune (2):", err)
  388. }
  389. _, err = r.Read(buf)
  390. if err != nil {
  391. t.Error("unexpected error on Read (2):", err)
  392. }
  393. if r.UnreadRune() == nil {
  394. t.Error("expected error after Read (2)")
  395. }
  396. // Test error after ReadByte.
  397. _, _, err = r.ReadRune() // reset state
  398. if err != nil {
  399. t.Error("unexpected error on ReadRune (2):", err)
  400. }
  401. for range buf {
  402. _, err = r.ReadByte()
  403. if err != nil {
  404. t.Error("unexpected error on ReadByte (2):", err)
  405. }
  406. }
  407. if r.UnreadRune() == nil {
  408. t.Error("expected error after ReadByte")
  409. }
  410. // Test error after UnreadByte.
  411. _, _, err = r.ReadRune() // reset state
  412. if err != nil {
  413. t.Error("unexpected error on ReadRune (3):", err)
  414. }
  415. _, err = r.ReadByte()
  416. if err != nil {
  417. t.Error("unexpected error on ReadByte (3):", err)
  418. }
  419. err = r.UnreadByte()
  420. if err != nil {
  421. t.Error("unexpected error on UnreadByte (3):", err)
  422. }
  423. if r.UnreadRune() == nil {
  424. t.Error("expected error after UnreadByte (3)")
  425. }
  426. // Test error after ReadSlice.
  427. _, _, err = r.ReadRune() // reset state
  428. if err != nil {
  429. t.Error("unexpected error on ReadRune (4):", err)
  430. }
  431. _, err = r.ReadSlice(0)
  432. if err != io.EOF {
  433. t.Error("unexpected error on ReadSlice (4):", err)
  434. }
  435. if r.UnreadRune() == nil {
  436. t.Error("expected error after ReadSlice (4)")
  437. }
  438. }
  439. func TestUnreadRuneAtEOF(t *testing.T) {
  440. // UnreadRune/ReadRune should error at EOF (was a bug; used to panic)
  441. r := NewReader(strings.NewReader("x"))
  442. r.ReadRune()
  443. r.ReadRune()
  444. r.UnreadRune()
  445. _, _, err := r.ReadRune()
  446. if err == nil {
  447. t.Error("expected error at EOF")
  448. } else if err != io.EOF {
  449. t.Error("expected EOF; got", err)
  450. }
  451. }
  452. func TestReadWriteRune(t *testing.T) {
  453. const NRune = 1000
  454. byteBuf := new(bytes.Buffer)
  455. w := NewWriter(byteBuf)
  456. // Write the runes out using WriteRune
  457. buf := make([]byte, utf8.UTFMax)
  458. for r := rune(0); r < NRune; r++ {
  459. size := utf8.EncodeRune(buf, r)
  460. nbytes, err := w.WriteRune(r)
  461. if err != nil {
  462. t.Fatalf("WriteRune(0x%x) error: %s", r, err)
  463. }
  464. if nbytes != size {
  465. t.Fatalf("WriteRune(0x%x) expected %d, got %d", r, size, nbytes)
  466. }
  467. }
  468. w.Flush()
  469. r := NewReader(byteBuf)
  470. // Read them back with ReadRune
  471. for r1 := rune(0); r1 < NRune; r1++ {
  472. size := utf8.EncodeRune(buf, r1)
  473. nr, nbytes, err := r.ReadRune()
  474. if nr != r1 || nbytes != size || err != nil {
  475. t.Fatalf("ReadRune(0x%x) got 0x%x,%d not 0x%x,%d (err=%s)", r1, nr, nbytes, r1, size, err)
  476. }
  477. }
  478. }
  479. func TestWriter(t *testing.T) {
  480. var data [8192]byte
  481. for i := 0; i < len(data); i++ {
  482. data[i] = byte(' ' + i%('~'-' '))
  483. }
  484. w := new(bytes.Buffer)
  485. for i := 0; i < len(bufsizes); i++ {
  486. for j := 0; j < len(bufsizes); j++ {
  487. nwrite := bufsizes[i]
  488. bs := bufsizes[j]
  489. // Write nwrite bytes using buffer size bs.
  490. // Check that the right amount makes it out
  491. // and that the data is correct.
  492. w.Reset()
  493. buf := NewWriterSize(w, bs)
  494. context := fmt.Sprintf("nwrite=%d bufsize=%d", nwrite, bs)
  495. n, e1 := buf.Write(data[0:nwrite])
  496. if e1 != nil || n != nwrite {
  497. t.Errorf("%s: buf.Write %d = %d, %v", context, nwrite, n, e1)
  498. continue
  499. }
  500. if e := buf.Flush(); e != nil {
  501. t.Errorf("%s: buf.Flush = %v", context, e)
  502. }
  503. written := w.Bytes()
  504. if len(written) != nwrite {
  505. t.Errorf("%s: %d bytes written", context, len(written))
  506. }
  507. for l := 0; l < len(written); l++ {
  508. if written[i] != data[i] {
  509. t.Errorf("wrong bytes written")
  510. t.Errorf("want=%q", data[0:len(written)])
  511. t.Errorf("have=%q", written)
  512. }
  513. }
  514. }
  515. }
  516. }
  517. // Check that write errors are returned properly.
  518. type errorWriterTest struct {
  519. n, m int
  520. err error
  521. expect error
  522. }
  523. func (w errorWriterTest) Write(p []byte) (int, error) {
  524. return len(p) * w.n / w.m, w.err
  525. }
  526. var errorWriterTests = []errorWriterTest{
  527. {0, 1, nil, io.ErrShortWrite},
  528. {1, 2, nil, io.ErrShortWrite},
  529. {1, 1, nil, nil},
  530. {0, 1, io.ErrClosedPipe, io.ErrClosedPipe},
  531. {1, 2, io.ErrClosedPipe, io.ErrClosedPipe},
  532. {1, 1, io.ErrClosedPipe, io.ErrClosedPipe},
  533. }
  534. func TestWriteErrors(t *testing.T) {
  535. for _, w := range errorWriterTests {
  536. buf := NewWriter(w)
  537. _, e := buf.Write([]byte("hello world"))
  538. if e != nil {
  539. t.Errorf("Write hello to %v: %v", w, e)
  540. continue
  541. }
  542. // Two flushes, to verify the error is sticky.
  543. for i := 0; i < 2; i++ {
  544. e = buf.Flush()
  545. if e != w.expect {
  546. t.Errorf("Flush %d/2 %v: got %v, wanted %v", i+1, w, e, w.expect)
  547. }
  548. }
  549. }
  550. }
  551. func TestNewReaderSizeIdempotent(t *testing.T) {
  552. const BufSize = 1000
  553. b := NewReaderSize(strings.NewReader("hello world"), BufSize)
  554. // Does it recognize itself?
  555. b1 := NewReaderSize(b, BufSize)
  556. if b1 != b {
  557. t.Error("NewReaderSize did not detect underlying Reader")
  558. }
  559. // Does it wrap if existing buffer is too small?
  560. b2 := NewReaderSize(b, 2*BufSize)
  561. if b2 == b {
  562. t.Error("NewReaderSize did not enlarge buffer")
  563. }
  564. }
  565. func TestNewWriterSizeIdempotent(t *testing.T) {
  566. const BufSize = 1000
  567. b := NewWriterSize(new(bytes.Buffer), BufSize)
  568. // Does it recognize itself?
  569. b1 := NewWriterSize(b, BufSize)
  570. if b1 != b {
  571. t.Error("NewWriterSize did not detect underlying Writer")
  572. }
  573. // Does it wrap if existing buffer is too small?
  574. b2 := NewWriterSize(b, 2*BufSize)
  575. if b2 == b {
  576. t.Error("NewWriterSize did not enlarge buffer")
  577. }
  578. }
  579. func TestWriteString(t *testing.T) {
  580. const BufSize = 8
  581. buf := new(bytes.Buffer)
  582. b := NewWriterSize(buf, BufSize)
  583. b.WriteString("0") // easy
  584. b.WriteString("123456") // still easy
  585. b.WriteString("7890") // easy after flush
  586. b.WriteString("abcdefghijklmnopqrstuvwxy") // hard
  587. b.WriteString("z")
  588. if err := b.Flush(); err != nil {
  589. t.Error("WriteString", err)
  590. }
  591. s := "01234567890abcdefghijklmnopqrstuvwxyz"
  592. if string(buf.Bytes()) != s {
  593. t.Errorf("WriteString wants %q gets %q", s, string(buf.Bytes()))
  594. }
  595. }
  596. func TestBufferFull(t *testing.T) {
  597. const longString = "And now, hello, world! It is the time for all good men to come to the aid of their party"
  598. buf := NewReaderSize(strings.NewReader(longString), minReadBufferSize)
  599. line, err := buf.ReadSlice('!')
  600. if string(line) != "And now, hello, " || err != ErrBufferFull {
  601. t.Errorf("first ReadSlice(,) = %q, %v", line, err)
  602. }
  603. line, err = buf.ReadSlice('!')
  604. if string(line) != "world!" || err != nil {
  605. t.Errorf("second ReadSlice(,) = %q, %v", line, err)
  606. }
  607. }
  608. func TestPeek(t *testing.T) {
  609. p := make([]byte, 10)
  610. // string is 16 (minReadBufferSize) long.
  611. buf := NewReaderSize(strings.NewReader("abcdefghijklmnop"), minReadBufferSize)
  612. if s, err := buf.Peek(1); string(s) != "a" || err != nil {
  613. t.Fatalf("want %q got %q, err=%v", "a", string(s), err)
  614. }
  615. if s, err := buf.Peek(4); string(s) != "abcd" || err != nil {
  616. t.Fatalf("want %q got %q, err=%v", "abcd", string(s), err)
  617. }
  618. if _, err := buf.Peek(-1); err != ErrNegativeCount {
  619. t.Fatalf("want ErrNegativeCount got %v", err)
  620. }
  621. if _, err := buf.Peek(32); err != ErrBufferFull {
  622. t.Fatalf("want ErrBufFull got %v", err)
  623. }
  624. if _, err := buf.Read(p[0:3]); string(p[0:3]) != "abc" || err != nil {
  625. t.Fatalf("want %q got %q, err=%v", "abc", string(p[0:3]), err)
  626. }
  627. if s, err := buf.Peek(1); string(s) != "d" || err != nil {
  628. t.Fatalf("want %q got %q, err=%v", "d", string(s), err)
  629. }
  630. if s, err := buf.Peek(2); string(s) != "de" || err != nil {
  631. t.Fatalf("want %q got %q, err=%v", "de", string(s), err)
  632. }
  633. if _, err := buf.Read(p[0:3]); string(p[0:3]) != "def" || err != nil {
  634. t.Fatalf("want %q got %q, err=%v", "def", string(p[0:3]), err)
  635. }
  636. if s, err := buf.Peek(4); string(s) != "ghij" || err != nil {
  637. t.Fatalf("want %q got %q, err=%v", "ghij", string(s), err)
  638. }
  639. if _, err := buf.Read(p[0:]); string(p[0:]) != "ghijklmnop" || err != nil {
  640. t.Fatalf("want %q got %q, err=%v", "ghijklmnop", string(p[0:minReadBufferSize]), err)
  641. }
  642. if s, err := buf.Peek(0); string(s) != "" || err != nil {
  643. t.Fatalf("want %q got %q, err=%v", "", string(s), err)
  644. }
  645. if _, err := buf.Peek(1); err != io.EOF {
  646. t.Fatalf("want EOF got %v", err)
  647. }
  648. // Test for issue 3022, not exposing a reader's error on a successful Peek.
  649. buf = NewReaderSize(dataAndEOFReader("abcd"), 32)
  650. if s, err := buf.Peek(2); string(s) != "ab" || err != nil {
  651. t.Errorf(`Peek(2) on "abcd", EOF = %q, %v; want "ab", nil`, string(s), err)
  652. }
  653. if s, err := buf.Peek(4); string(s) != "abcd" || err != nil {
  654. t.Errorf(`Peek(4) on "abcd", EOF = %q, %v; want "abcd", nil`, string(s), err)
  655. }
  656. if n, err := buf.Read(p[0:5]); string(p[0:n]) != "abcd" || err != nil {
  657. t.Fatalf("Read after peek = %q, %v; want abcd, EOF", p[0:n], err)
  658. }
  659. if n, err := buf.Read(p[0:1]); string(p[0:n]) != "" || err != io.EOF {
  660. t.Fatalf(`second Read after peek = %q, %v; want "", EOF`, p[0:n], err)
  661. }
  662. }
  663. type dataAndEOFReader string
  664. func (r dataAndEOFReader) Read(p []byte) (int, error) {
  665. return copy(p, r), io.EOF
  666. }
  667. func TestPeekThenUnreadRune(t *testing.T) {
  668. // This sequence used to cause a crash.
  669. r := NewReader(strings.NewReader("x"))
  670. r.ReadRune()
  671. r.Peek(1)
  672. r.UnreadRune()
  673. r.ReadRune() // Used to panic here
  674. }
  675. var testOutput = []byte("0123456789abcdefghijklmnopqrstuvwxy")
  676. var testInput = []byte("012\n345\n678\n9ab\ncde\nfgh\nijk\nlmn\nopq\nrst\nuvw\nxy")
  677. var testInputrn = []byte("012\r\n345\r\n678\r\n9ab\r\ncde\r\nfgh\r\nijk\r\nlmn\r\nopq\r\nrst\r\nuvw\r\nxy\r\n\n\r\n")
  678. // TestReader wraps a []byte and returns reads of a specific length.
  679. type testReader struct {
  680. data []byte
  681. stride int
  682. }
  683. func (t *testReader) Read(buf []byte) (n int, err error) {
  684. n = t.stride
  685. if n > len(t.data) {
  686. n = len(t.data)
  687. }
  688. if n > len(buf) {
  689. n = len(buf)
  690. }
  691. copy(buf, t.data)
  692. t.data = t.data[n:]
  693. if len(t.data) == 0 {
  694. err = io.EOF
  695. }
  696. return
  697. }
  698. func testReadLine(t *testing.T, input []byte) {
  699. //for stride := 1; stride < len(input); stride++ {
  700. for stride := 1; stride < 2; stride++ {
  701. done := 0
  702. reader := testReader{input, stride}
  703. l := NewReaderSize(&reader, len(input)+1)
  704. for {
  705. line, isPrefix, err := l.ReadLine()
  706. if len(line) > 0 && err != nil {
  707. t.Errorf("ReadLine returned both data and error: %s", err)
  708. }
  709. if isPrefix {
  710. t.Errorf("ReadLine returned prefix")
  711. }
  712. if err != nil {
  713. if err != io.EOF {
  714. t.Fatalf("Got unknown error: %s", err)
  715. }
  716. break
  717. }
  718. if want := testOutput[done : done+len(line)]; !bytes.Equal(want, line) {
  719. t.Errorf("Bad line at stride %d: want: %x got: %x", stride, want, line)
  720. }
  721. done += len(line)
  722. }
  723. if done != len(testOutput) {
  724. t.Errorf("ReadLine didn't return everything: got: %d, want: %d (stride: %d)", done, len(testOutput), stride)
  725. }
  726. }
  727. }
  728. func TestReadLine(t *testing.T) {
  729. testReadLine(t, testInput)
  730. testReadLine(t, testInputrn)
  731. }
  732. func TestLineTooLong(t *testing.T) {
  733. data := make([]byte, 0)
  734. for i := 0; i < minReadBufferSize*5/2; i++ {
  735. data = append(data, '0'+byte(i%10))
  736. }
  737. buf := bytes.NewReader(data)
  738. l := NewReaderSize(buf, minReadBufferSize)
  739. line, isPrefix, err := l.ReadLine()
  740. if !isPrefix || !bytes.Equal(line, data[:minReadBufferSize]) || err != nil {
  741. t.Errorf("bad result for first line: got %q want %q %v", line, data[:minReadBufferSize], err)
  742. }
  743. data = data[len(line):]
  744. line, isPrefix, err = l.ReadLine()
  745. if !isPrefix || !bytes.Equal(line, data[:minReadBufferSize]) || err != nil {
  746. t.Errorf("bad result for second line: got %q want %q %v", line, data[:minReadBufferSize], err)
  747. }
  748. data = data[len(line):]
  749. line, isPrefix, err = l.ReadLine()
  750. if isPrefix || !bytes.Equal(line, data[:minReadBufferSize/2]) || err != nil {
  751. t.Errorf("bad result for third line: got %q want %q %v", line, data[:minReadBufferSize/2], err)
  752. }
  753. line, isPrefix, err = l.ReadLine()
  754. if isPrefix || err == nil {
  755. t.Errorf("expected no more lines: %x %s", line, err)
  756. }
  757. }
  758. func TestReadAfterLines(t *testing.T) {
  759. line1 := "this is line1"
  760. restData := "this is line2\nthis is line 3\n"
  761. inbuf := bytes.NewReader([]byte(line1 + "\n" + restData))
  762. outbuf := new(bytes.Buffer)
  763. maxLineLength := len(line1) + len(restData)/2
  764. l := NewReaderSize(inbuf, maxLineLength)
  765. line, isPrefix, err := l.ReadLine()
  766. if isPrefix || err != nil || string(line) != line1 {
  767. t.Errorf("bad result for first line: isPrefix=%v err=%v line=%q", isPrefix, err, string(line))
  768. }
  769. n, err := io.Copy(outbuf, l)
  770. if int(n) != len(restData) || err != nil {
  771. t.Errorf("bad result for Read: n=%d err=%v", n, err)
  772. }
  773. if outbuf.String() != restData {
  774. t.Errorf("bad result for Read: got %q; expected %q", outbuf.String(), restData)
  775. }
  776. }
  777. func TestReadEmptyBuffer(t *testing.T) {
  778. l := NewReaderSize(new(bytes.Buffer), minReadBufferSize)
  779. line, isPrefix, err := l.ReadLine()
  780. if err != io.EOF {
  781. t.Errorf("expected EOF from ReadLine, got '%s' %t %s", line, isPrefix, err)
  782. }
  783. }
  784. func TestLinesAfterRead(t *testing.T) {
  785. l := NewReaderSize(bytes.NewReader([]byte("foo")), minReadBufferSize)
  786. _, err := ioutil.ReadAll(l)
  787. if err != nil {
  788. t.Error(err)
  789. return
  790. }
  791. line, isPrefix, err := l.ReadLine()
  792. if err != io.EOF {
  793. t.Errorf("expected EOF from ReadLine, got '%s' %t %s", line, isPrefix, err)
  794. }
  795. }
  796. func TestReadLineNonNilLineOrError(t *testing.T) {
  797. r := NewReader(strings.NewReader("line 1\n"))
  798. for i := 0; i < 2; i++ {
  799. l, _, err := r.ReadLine()
  800. if l != nil && err != nil {
  801. t.Fatalf("on line %d/2; ReadLine=%#v, %v; want non-nil line or Error, but not both",
  802. i+1, l, err)
  803. }
  804. }
  805. }
  806. type readLineResult struct {
  807. line []byte
  808. isPrefix bool
  809. err error
  810. }
  811. var readLineNewlinesTests = []struct {
  812. input string
  813. expect []readLineResult
  814. }{
  815. {"012345678901234\r\n012345678901234\r\n", []readLineResult{
  816. {[]byte("012345678901234"), true, nil},
  817. {nil, false, nil},
  818. {[]byte("012345678901234"), true, nil},
  819. {nil, false, nil},
  820. {nil, false, io.EOF},
  821. }},
  822. {"0123456789012345\r012345678901234\r", []readLineResult{
  823. {[]byte("0123456789012345"), true, nil},
  824. {[]byte("\r012345678901234"), true, nil},
  825. {[]byte("\r"), false, nil},
  826. {nil, false, io.EOF},
  827. }},
  828. }
  829. func TestReadLineNewlines(t *testing.T) {
  830. for _, e := range readLineNewlinesTests {
  831. testReadLineNewlines(t, e.input, e.expect)
  832. }
  833. }
  834. func testReadLineNewlines(t *testing.T, input string, expect []readLineResult) {
  835. b := NewReaderSize(strings.NewReader(input), minReadBufferSize)
  836. for i, e := range expect {
  837. line, isPrefix, err := b.ReadLine()
  838. if !bytes.Equal(line, e.line) {
  839. t.Errorf("%q call %d, line == %q, want %q", input, i, line, e.line)
  840. return
  841. }
  842. if isPrefix != e.isPrefix {
  843. t.Errorf("%q call %d, isPrefix == %v, want %v", input, i, isPrefix, e.isPrefix)
  844. return
  845. }
  846. if err != e.err {
  847. t.Errorf("%q call %d, err == %v, want %v", input, i, err, e.err)
  848. return
  849. }
  850. }
  851. }
  852. func createTestInput(n int) []byte {
  853. input := make([]byte, n)
  854. for i := range input {
  855. // 101 and 251 are arbitrary prime numbers.
  856. // The idea is to create an input sequence
  857. // which doesn't repeat too frequently.
  858. input[i] = byte(i % 251)
  859. if i%101 == 0 {
  860. input[i] ^= byte(i / 101)
  861. }
  862. }
  863. return input
  864. }
  865. func TestReaderWriteTo(t *testing.T) {
  866. input := createTestInput(8192)
  867. r := NewReader(onlyReader{bytes.NewReader(input)})
  868. w := new(bytes.Buffer)
  869. if n, err := r.WriteTo(w); err != nil || n != int64(len(input)) {
  870. t.Fatalf("r.WriteTo(w) = %d, %v, want %d, nil", n, err, len(input))
  871. }
  872. for i, val := range w.Bytes() {
  873. if val != input[i] {
  874. t.Errorf("after write: out[%d] = %#x, want %#x", i, val, input[i])
  875. }
  876. }
  877. }
  878. type errorWriterToTest struct {
  879. rn, wn int
  880. rerr, werr error
  881. expected error
  882. }
  883. func (r errorWriterToTest) Read(p []byte) (int, error) {
  884. return len(p) * r.rn, r.rerr
  885. }
  886. func (w errorWriterToTest) Write(p []byte) (int, error) {
  887. return len(p) * w.wn, w.werr
  888. }
  889. var errorWriterToTests = []errorWriterToTest{
  890. {1, 0, nil, io.ErrClosedPipe, io.ErrClosedPipe},
  891. {0, 1, io.ErrClosedPipe, nil, io.ErrClosedPipe},
  892. {0, 0, io.ErrUnexpectedEOF, io.ErrClosedPipe, io.ErrClosedPipe},
  893. {0, 1, io.EOF, nil, nil},
  894. }
  895. func TestReaderWriteToErrors(t *testing.T) {
  896. for i, rw := range errorWriterToTests {
  897. r := NewReader(rw)
  898. if _, err := r.WriteTo(rw); err != rw.expected {
  899. t.Errorf("r.WriteTo(errorWriterToTests[%d]) = _, %v, want _,%v", i, err, rw.expected)
  900. }
  901. }
  902. }
  903. func TestWriterReadFrom(t *testing.T) {
  904. ws := []func(io.Writer) io.Writer{
  905. func(w io.Writer) io.Writer { return onlyWriter{w} },
  906. func(w io.Writer) io.Writer { return w },
  907. }
  908. rs := []func(io.Reader) io.Reader{
  909. iotest.DataErrReader,
  910. func(r io.Reader) io.Reader { return r },
  911. }
  912. for ri, rfunc := range rs {
  913. for wi, wfunc := range ws {
  914. input := createTestInput(8192)
  915. b := new(bytes.Buffer)
  916. w := NewWriter(wfunc(b))
  917. r := rfunc(bytes.NewReader(input))
  918. if n, err := w.ReadFrom(r); err != nil || n != int64(len(input)) {
  919. t.Errorf("ws[%d],rs[%d]: w.ReadFrom(r) = %d, %v, want %d, nil", wi, ri, n, err, len(input))
  920. continue
  921. }
  922. if err := w.Flush(); err != nil {
  923. t.Errorf("Flush returned %v", err)
  924. continue
  925. }
  926. if got, want := b.String(), string(input); got != want {
  927. t.Errorf("ws[%d], rs[%d]:\ngot %q\nwant %q\n", wi, ri, got, want)
  928. }
  929. }
  930. }
  931. }
  932. type errorReaderFromTest struct {
  933. rn, wn int
  934. rerr, werr error
  935. expected error
  936. }
  937. func (r errorReaderFromTest) Read(p []byte) (int, error) {
  938. return len(p) * r.rn, r.rerr
  939. }
  940. func (w errorReaderFromTest) Write(p []byte) (int, error) {
  941. return len(p) * w.wn, w.werr
  942. }
  943. var errorReaderFromTests = []errorReaderFromTest{
  944. {0, 1, io.EOF, nil, nil},
  945. {1, 1, io.EOF, nil, nil},
  946. {0, 1, io.ErrClosedPipe, nil, io.ErrClosedPipe},
  947. {0, 0, io.ErrClosedPipe, io.ErrShortWrite, io.ErrClosedPipe},
  948. {1, 0, nil, io.ErrShortWrite, io.ErrShortWrite},
  949. }
  950. func TestWriterReadFromErrors(t *testing.T) {
  951. for i, rw := range errorReaderFromTests {
  952. w := NewWriter(rw)
  953. if _, err := w.ReadFrom(rw); err != rw.expected {
  954. t.Errorf("w.ReadFrom(errorReaderFromTests[%d]) = _, %v, want _,%v", i, err, rw.expected)
  955. }
  956. }
  957. }
  958. // TestWriterReadFromCounts tests that using io.Copy to copy into a
  959. // bufio.Writer does not prematurely flush the buffer. For example, when
  960. // buffering writes to a network socket, excessive network writes should be
  961. // avoided.
  962. func TestWriterReadFromCounts(t *testing.T) {
  963. var w0 writeCountingDiscard
  964. b0 := NewWriterSize(&w0, 1234)
  965. b0.WriteString(strings.Repeat("x", 1000))
  966. if w0 != 0 {
  967. t.Fatalf("write 1000 'x's: got %d writes, want 0", w0)
  968. }
  969. b0.WriteString(strings.Repeat("x", 200))
  970. if w0 != 0 {
  971. t.Fatalf("write 1200 'x's: got %d writes, want 0", w0)
  972. }
  973. io.Copy(b0, onlyReader{strings.NewReader(strings.Repeat("x", 30))})
  974. if w0 != 0 {
  975. t.Fatalf("write 1230 'x's: got %d writes, want 0", w0)
  976. }
  977. io.Copy(b0, onlyReader{strings.NewReader(strings.Repeat("x", 9))})
  978. if w0 != 1 {
  979. t.Fatalf("write 1239 'x's: got %d writes, want 1", w0)
  980. }
  981. var w1 writeCountingDiscard
  982. b1 := NewWriterSize(&w1, 1234)
  983. b1.WriteString(strings.Repeat("x", 1200))
  984. b1.Flush()
  985. if w1 != 1 {
  986. t.Fatalf("flush 1200 'x's: got %d writes, want 1", w1)
  987. }
  988. b1.WriteString(strings.Repeat("x", 89))
  989. if w1 != 1 {
  990. t.Fatalf("write 1200 + 89 'x's: got %d writes, want 1", w1)
  991. }
  992. io.Copy(b1, onlyReader{strings.NewReader(strings.Repeat("x", 700))})
  993. if w1 != 1 {
  994. t.Fatalf("write 1200 + 789 'x's: got %d writes, want 1", w1)
  995. }
  996. io.Copy(b1, onlyReader{strings.NewReader(strings.Repeat("x", 600))})
  997. if w1 != 2 {
  998. t.Fatalf("write 1200 + 1389 'x's: got %d writes, want 2", w1)
  999. }
  1000. b1.Flush()
  1001. if w1 != 3 {
  1002. t.Fatalf("flush 1200 + 1389 'x's: got %d writes, want 3", w1)
  1003. }
  1004. }
  1005. // A writeCountingDiscard is like ioutil.Discard and counts the number of times
  1006. // Write is called on it.
  1007. type writeCountingDiscard int
  1008. func (w *writeCountingDiscard) Write(p []byte) (int, error) {
  1009. *w++
  1010. return len(p), nil
  1011. }
  1012. type negativeReader int
  1013. func (r *negativeReader) Read([]byte) (int, error) { return -1, nil }
  1014. func TestNegativeRead(t *testing.T) {
  1015. // should panic with a description pointing at the reader, not at itself.
  1016. // (should NOT panic with slice index error, for example.)
  1017. b := NewReader(new(negativeReader))
  1018. defer func() {
  1019. switch err := recover().(type) {
  1020. case nil:
  1021. t.Fatal("read did not panic")
  1022. case error:
  1023. if !strings.Contains(err.Error(), "reader returned negative count from Read") {
  1024. t.Fatalf("wrong panic: %v", err)
  1025. }
  1026. default:
  1027. t.Fatalf("unexpected panic value: %T(%v)", err, err)
  1028. }
  1029. }()
  1030. b.Read(make([]byte, 100))
  1031. }
  1032. var errFake = errors.New("fake error")
  1033. type errorThenGoodReader struct {
  1034. didErr bool
  1035. nread int
  1036. }
  1037. func (r *errorThenGoodReader) Read(p []byte) (int, error) {
  1038. r.nread++
  1039. if !r.didErr {
  1040. r.didErr = true
  1041. return 0, errFake
  1042. }
  1043. return len(p), nil
  1044. }
  1045. func TestReaderClearError(t *testing.T) {
  1046. r := &errorThenGoodReader{}
  1047. b := NewReader(r)
  1048. buf := make([]byte, 1)
  1049. if _, err := b.Read(nil); err != nil {
  1050. t.Fatalf("1st nil Read = %v; want nil", err)
  1051. }
  1052. if _, err := b.Read(buf); err != errFake {
  1053. t.Fatalf("1st Read = %v; want errFake", err)
  1054. }
  1055. if _, err := b.Read(nil); err != nil {
  1056. t.Fatalf("2nd nil Read = %v; want nil", err)
  1057. }
  1058. if _, err := b.Read(buf); err != nil {
  1059. t.Fatalf("3rd Read with buffer = %v; want nil", err)
  1060. }
  1061. if r.nread != 2 {
  1062. t.Errorf("num reads = %d; want 2", r.nread)
  1063. }
  1064. }
  1065. // Test for golang.org/issue/5947
  1066. func TestWriterReadFromWhileFull(t *testing.T) {
  1067. buf := new(bytes.Buffer)
  1068. w := NewWriterSize(buf, 10)
  1069. // Fill buffer exactly.
  1070. n, err := w.Write([]byte("0123456789"))
  1071. if n != 10 || err != nil {
  1072. t.Fatalf("Write returned (%v, %v), want (10, nil)", n, err)
  1073. }
  1074. // Use ReadFrom to read in some data.
  1075. n2, err := w.ReadFrom(strings.NewReader("abcdef"))
  1076. if n2 != 6 || err != nil {
  1077. t.Fatalf("ReadFrom returned (%v, %v), want (6, nil)", n2, err)
  1078. }
  1079. }
  1080. type emptyThenNonEmptyReader struct {
  1081. r io.Reader
  1082. n int
  1083. }
  1084. func (r *emptyThenNonEmptyReader) Read(p []byte) (int, error) {
  1085. if r.n <= 0 {
  1086. return r.r.Read(p)
  1087. }
  1088. r.n--
  1089. return 0, nil
  1090. }
  1091. // Test for golang.org/issue/7611
  1092. func TestWriterReadFromUntilEOF(t *testing.T) {
  1093. buf := new(bytes.Buffer)
  1094. w := NewWriterSize(buf, 5)
  1095. // Partially fill buffer
  1096. n, err := w.Write([]byte("0123"))
  1097. if n != 4 || err != nil {
  1098. t.Fatalf("Write returned (%v, %v), want (4, nil)", n, err)
  1099. }
  1100. // Use ReadFrom to read in some data.
  1101. r := &emptyThenNonEmptyReader{r: strings.NewReader("abcd"), n: 3}
  1102. n2, err := w.ReadFrom(r)
  1103. if n2 != 4 || err != nil {
  1104. t.Fatalf("ReadFrom returned (%v, %v), want (4, nil)", n2, err)
  1105. }
  1106. w.Flush()
  1107. if got, want := string(buf.Bytes()), "0123abcd"; got != want {
  1108. t.Fatalf("buf.Bytes() returned %q, want %q", got, want)
  1109. }
  1110. }
  1111. func TestWriterReadFromErrNoProgress(t *testing.T) {
  1112. buf := new(bytes.Buffer)
  1113. w := NewWriterSize(buf, 5)
  1114. // Partially fill buffer
  1115. n, err := w.Write([]byte("0123"))
  1116. if n != 4 || err != nil {
  1117. t.Fatalf("Write returned (%v, %v), want (4, nil)", n, err)
  1118. }
  1119. // Use ReadFrom to read in some data.
  1120. r := &emptyThenNonEmptyReader{r: strings.NewReader("abcd"), n: 100}
  1121. n2, err := w.ReadFrom(r)
  1122. if n2 != 0 || err != io.ErrNoProgress {
  1123. t.Fatalf("buf.Bytes() returned (%v, %v), want (0, io.ErrNoProgress)", n2, err)
  1124. }
  1125. }
  1126. func TestReaderReset(t *testing.T) {
  1127. r := NewReader(strings.NewReader("foo foo"))
  1128. buf := make([]byte, 3)
  1129. r.Read(buf)
  1130. if string(buf) != "foo" {
  1131. t.Errorf("buf = %q; want foo", buf)
  1132. }
  1133. r.Reset(strings.NewReader("bar bar"))
  1134. all, err := ioutil.ReadAll(r)
  1135. if err != nil {
  1136. t.Fatal(err)
  1137. }
  1138. if string(all) != "bar bar" {
  1139. t.Errorf("ReadAll = %q; want bar bar", all)
  1140. }
  1141. }
  1142. func TestWriterReset(t *testing.T) {
  1143. var buf1, buf2 bytes.Buffer
  1144. w := NewWriter(&buf1)
  1145. w.WriteString("foo")
  1146. w.Reset(&buf2) // and not flushed
  1147. w.WriteString("bar")
  1148. w.Flush()
  1149. if buf1.String() != "" {
  1150. t.Errorf("buf1 = %q; want empty", buf1.String())
  1151. }
  1152. if buf2.String() != "bar" {
  1153. t.Errorf("buf2 = %q; want bar", buf2.String())
  1154. }
  1155. }
  1156. func TestReaderDiscard(t *testing.T) {
  1157. tests := []struct {
  1158. name string
  1159. r io.Reader
  1160. bufSize int // 0 means 16
  1161. peekSize int
  1162. n int // input to Discard
  1163. want int // from Discard
  1164. wantErr error // from Discard
  1165. wantBuffered int
  1166. }{
  1167. {
  1168. name: "normal case",
  1169. r: strings.NewReader("abcdefghijklmnopqrstuvwxyz"),
  1170. peekSize: 16,
  1171. n: 6,
  1172. want: 6,
  1173. wantBuffered: 10,
  1174. },
  1175. {
  1176. name: "discard causing read",
  1177. r: strings.NewReader("abcdefghijklmnopqrstuvwxyz"),
  1178. n: 6,
  1179. want: 6,
  1180. wantBuffered: 10,
  1181. },
  1182. {
  1183. name: "discard all without peek",
  1184. r: strings.NewReader("abcdefghijklmnopqrstuvwxyz"),
  1185. n: 26,
  1186. want: 26,
  1187. wantBuffered: 0,
  1188. },
  1189. {
  1190. name: "discard more than end",
  1191. r: strings.NewReader("abcdefghijklmnopqrstuvwxyz"),
  1192. n: 27,
  1193. want: 26,
  1194. wantErr: io.EOF,
  1195. wantBuffered: 0,
  1196. },
  1197. // Any error from filling shouldn't show up until we
  1198. // get past the valid bytes. Here we return we return 5 valid bytes at the same time
  1199. // as an error, but test that we don't see the error from Discard.
  1200. {
  1201. name: "fill error, discard less",
  1202. r: newScriptedReader(func(p []byte) (n int, err error) {
  1203. if len(p) < 5 {
  1204. panic("unexpected small read")
  1205. }
  1206. return 5, errors.New("5-then-error")
  1207. }),
  1208. n: 4,
  1209. want: 4,
  1210. wantErr: nil,
  1211. wantBuffered: 1,
  1212. },
  1213. {
  1214. name: "fill error, discard equal",
  1215. r: newScriptedReader(func(p []byte) (n int, err error) {
  1216. if len(p) < 5 {
  1217. panic("unexpected small read")
  1218. }
  1219. return 5, errors.New("5-then-error")
  1220. }),
  1221. n: 5,
  1222. want: 5,
  1223. wantErr: nil,
  1224. wantBuffered: 0,
  1225. },
  1226. {
  1227. name: "fill error, discard more",
  1228. r: newScriptedReader(func(p []byte) (n int, err error) {
  1229. if len(p) < 5 {
  1230. panic("unexpected small read")
  1231. }
  1232. return 5, errors.New("5-then-error")
  1233. }),
  1234. n: 6,
  1235. want: 5,
  1236. wantErr: errors.New("5-then-error"),
  1237. wantBuffered: 0,
  1238. },
  1239. // Discard of 0 shouldn't cause a read:
  1240. {
  1241. name: "discard zero",
  1242. r: newScriptedReader(), // will panic on Read
  1243. n: 0,
  1244. want: 0,
  1245. wantErr: nil,
  1246. wantBuffered: 0,
  1247. },
  1248. {
  1249. name: "discard negative",
  1250. r: newScriptedReader(), // will panic on Read
  1251. n: -1,
  1252. want: 0,
  1253. wantErr: ErrNegativeCount,
  1254. wantBuffered: 0,
  1255. },
  1256. }
  1257. for _, tt := range tests {
  1258. br := NewReaderSize(tt.r, tt.bufSize)
  1259. if tt.peekSize > 0 {
  1260. peekBuf, err := br.Peek(tt.peekSize)
  1261. if err != nil {
  1262. t.Errorf("%s: Peek(%d): %v", tt.name, tt.peekSize, err)
  1263. continue
  1264. }
  1265. if len(peekBuf) != tt.peekSize {
  1266. t.Errorf("%s: len(Peek(%d)) = %v; want %v", tt.name, tt.peekSize, len(peekBuf), tt.peekSize)
  1267. continue
  1268. }
  1269. }
  1270. discarded, err := br.Discard(tt.n)
  1271. if ge, we := fmt.Sprint(err), fmt.Sprint(tt.wantErr); discarded != tt.want || ge != we {
  1272. t.Errorf("%s: Discard(%d) = (%v, %v); want (%v, %v)", tt.name, tt.n, discarded, ge, tt.want, we)
  1273. continue
  1274. }
  1275. if bn := br.Buffered(); bn != tt.wantBuffered {
  1276. t.Errorf("%s: after Discard, Buffered = %d; want %d", tt.name, bn, tt.wantBuffered)
  1277. }
  1278. }
  1279. }
  1280. // An onlyReader only implements io.Reader, no matter what other methods the underlying implementation may have.
  1281. type onlyReader struct {
  1282. io.Reader
  1283. }
  1284. // An onlyWriter only implements io.Writer, no matter what other methods the underlying implementation may have.
  1285. type onlyWriter struct {
  1286. io.Writer
  1287. }
  1288. // A scriptedReader is an io.Reader that executes its steps sequentially.
  1289. type scriptedReader []func(p []byte) (n int, err error)
  1290. func (sr *scriptedReader) Read(p []byte) (n int, err error) {
  1291. if len(*sr) == 0 {
  1292. panic("too many Read calls on scripted Reader. No steps remain.")
  1293. }
  1294. step := (*sr)[0]
  1295. *sr = (*sr)[1:]
  1296. return step(p)
  1297. }
  1298. func newScriptedReader(steps ...func(p []byte) (n int, err error)) io.Reader {
  1299. sr := scriptedReader(steps)
  1300. return &sr
  1301. }
  1302. func BenchmarkReaderCopyOptimal(b *testing.B) {
  1303. // Optimal case is where the underlying reader implements io.WriterTo
  1304. srcBuf := bytes.NewBuffer(make([]byte, 8192))
  1305. src := NewReader(srcBuf)
  1306. dstBuf := new(bytes.Buffer)
  1307. dst := onlyWriter{dstBuf}
  1308. for i := 0; i < b.N; i++ {
  1309. srcBuf.Reset()
  1310. src.Reset(srcBuf)
  1311. dstBuf.Reset()
  1312. io.Copy(dst, src)
  1313. }
  1314. }
  1315. func BenchmarkReaderCopyUnoptimal(b *testing.B) {
  1316. // Unoptimal case is where the underlying reader doesn't implement io.WriterTo
  1317. srcBuf := bytes.NewBuffer(make([]byte, 8192))
  1318. src := NewReader(onlyReader{srcBuf})
  1319. dstBuf := new(bytes.Buffer)
  1320. dst := onlyWriter{dstBuf}
  1321. for i := 0; i < b.N; i++ {
  1322. srcBuf.Reset()
  1323. src.Reset(onlyReader{srcBuf})
  1324. dstBuf.Reset()
  1325. io.Copy(dst, src)
  1326. }
  1327. }
  1328. func BenchmarkReaderCopyNoWriteTo(b *testing.B) {
  1329. srcBuf := bytes.NewBuffer(make([]byte, 8192))
  1330. srcReader := NewReader(srcBuf)
  1331. src := onlyReader{srcReader}
  1332. dstBuf := new(bytes.Buffer)
  1333. dst := onlyWriter{dstBuf}
  1334. for i := 0; i < b.N; i++ {
  1335. srcBuf.Reset()
  1336. srcReader.Reset(srcBuf)
  1337. dstBuf.Reset()
  1338. io.Copy(dst, src)
  1339. }
  1340. }
  1341. func BenchmarkReaderWriteToOptimal(b *testing.B) {
  1342. const bufSize = 16 << 10
  1343. buf := make([]byte, bufSize)
  1344. r := bytes.NewReader(buf)
  1345. srcReader := NewReaderSize(onlyReader{r}, 1<<10)
  1346. if _, ok := ioutil.Discard.(io.ReaderFrom); !ok {
  1347. b.Fatal("ioutil.Discard doesn't support ReaderFrom")
  1348. }
  1349. for i := 0; i < b.N; i++ {
  1350. r.Seek(0, 0)
  1351. srcReader.Reset(onlyReader{r})
  1352. n, err := srcReader.WriteTo(ioutil.Discard)
  1353. if err != nil {
  1354. b.Fatal(err)
  1355. }
  1356. if n != bufSize {
  1357. b.Fatalf("n = %d; want %d", n, bufSize)
  1358. }
  1359. }
  1360. }
  1361. func BenchmarkWriterCopyOptimal(b *testing.B) {
  1362. // Optimal case is where the underlying writer implements io.ReaderFrom
  1363. srcBuf := bytes.NewBuffer(make([]byte, 8192))
  1364. src := onlyReader{srcBuf}
  1365. dstBuf := new(bytes.Buffer)
  1366. dst := NewWriter(dstBuf)
  1367. for i := 0; i < b.N; i++ {
  1368. srcBuf.Reset()
  1369. dstBuf.Reset()
  1370. dst.Reset(dstBuf)
  1371. io.Copy(dst, src)
  1372. }
  1373. }
  1374. func BenchmarkWriterCopyUnoptimal(b *testing.B) {
  1375. srcBuf := bytes.NewBuffer(make([]byte, 8192))
  1376. src := onlyReader{srcBuf}
  1377. dstBuf := new(bytes.Buffer)
  1378. dst := NewWriter(onlyWriter{dstBuf})
  1379. for i := 0; i < b.N; i++ {
  1380. srcBuf.Reset()
  1381. dstBuf.Reset()
  1382. dst.Reset(onlyWriter{dstBuf})
  1383. io.Copy(dst, src)
  1384. }
  1385. }
  1386. func BenchmarkWriterCopyNoReadFrom(b *testing.B) {
  1387. srcBuf := bytes.NewBuffer(make([]byte, 8192))
  1388. src := onlyReader{srcBuf}
  1389. dstBuf := new(bytes.Buffer)
  1390. dstWriter := NewWriter(dstBuf)
  1391. dst := onlyWriter{dstWriter}
  1392. for i := 0; i < b.N; i++ {
  1393. srcBuf.Reset()
  1394. dstBuf.Reset()
  1395. dstWriter.Reset(dstBuf)
  1396. io.Copy(dst, src)
  1397. }
  1398. }
  1399. func BenchmarkReaderEmpty(b *testing.B) {
  1400. b.ReportAllocs()
  1401. str := strings.Repeat("x", 16<<10)
  1402. for i := 0; i < b.N; i++ {
  1403. br := NewReader(strings.NewReader(str))
  1404. n, err := io.Copy(ioutil.Discard, br)
  1405. if err != nil {
  1406. b.Fatal(err)
  1407. }
  1408. if n != int64(len(str)) {
  1409. b.Fatal("wrong length")
  1410. }
  1411. }
  1412. }
  1413. func BenchmarkWriterEmpty(b *testing.B) {
  1414. b.ReportAllocs()
  1415. str := strings.Repeat("x", 1<<10)
  1416. bs := []byte(str)
  1417. for i := 0; i < b.N; i++ {
  1418. bw := NewWriter(ioutil.Discard)
  1419. bw.Flush()
  1420. bw.WriteByte('a')
  1421. bw.Flush()
  1422. bw.WriteRune('B')
  1423. bw.Flush()
  1424. bw.Write(bs)
  1425. bw.Flush()
  1426. bw.WriteString(str)
  1427. bw.Flush()
  1428. }
  1429. }
  1430. func BenchmarkWriterFlush(b *testing.B) {
  1431. b.ReportAllocs()
  1432. bw := NewWriter(ioutil.Discard)
  1433. str := strings.Repeat("x", 50)
  1434. for i := 0; i < b.N; i++ {
  1435. bw.WriteString(str)
  1436. bw.Flush()
  1437. }
  1438. }