example_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. // Copyright 2011 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. "encoding/base64"
  8. "fmt"
  9. "io"
  10. "os"
  11. "sort"
  12. "unicode"
  13. )
  14. func ExampleBuffer() {
  15. var b bytes.Buffer // A Buffer needs no initialization.
  16. b.Write([]byte("Hello "))
  17. fmt.Fprintf(&b, "world!")
  18. b.WriteTo(os.Stdout)
  19. // Output: Hello world!
  20. }
  21. func ExampleBuffer_reader() {
  22. // A Buffer can turn a string or a []byte into an io.Reader.
  23. buf := bytes.NewBufferString("R29waGVycyBydWxlIQ==")
  24. dec := base64.NewDecoder(base64.StdEncoding, buf)
  25. io.Copy(os.Stdout, dec)
  26. // Output: Gophers rule!
  27. }
  28. func ExampleBuffer_Bytes() {
  29. buf := bytes.Buffer{}
  30. buf.Write([]byte{'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'})
  31. os.Stdout.Write(buf.Bytes())
  32. // Output: hello world
  33. }
  34. func ExampleBuffer_Cap() {
  35. buf1 := bytes.NewBuffer(make([]byte, 10))
  36. buf2 := bytes.NewBuffer(make([]byte, 0, 10))
  37. fmt.Println(buf1.Cap())
  38. fmt.Println(buf2.Cap())
  39. // Output:
  40. // 10
  41. // 10
  42. }
  43. func ExampleBuffer_Grow() {
  44. var b bytes.Buffer
  45. b.Grow(64)
  46. bb := b.Bytes()
  47. b.Write([]byte("64 bytes or fewer"))
  48. fmt.Printf("%q", bb[:b.Len()])
  49. // Output: "64 bytes or fewer"
  50. }
  51. func ExampleBuffer_Len() {
  52. var b bytes.Buffer
  53. b.Grow(64)
  54. b.Write([]byte("abcde"))
  55. fmt.Printf("%d", b.Len())
  56. // Output: 5
  57. }
  58. func ExampleBuffer_Next() {
  59. var b bytes.Buffer
  60. b.Grow(64)
  61. b.Write([]byte("abcde"))
  62. fmt.Printf("%s\n", string(b.Next(2)))
  63. fmt.Printf("%s\n", string(b.Next(2)))
  64. fmt.Printf("%s", string(b.Next(2)))
  65. // Output:
  66. // ab
  67. // cd
  68. // e
  69. }
  70. func ExampleBuffer_Read() {
  71. var b bytes.Buffer
  72. b.Grow(64)
  73. b.Write([]byte("abcde"))
  74. rdbuf := make([]byte, 1)
  75. n, err := b.Read(rdbuf)
  76. if err != nil {
  77. panic(err)
  78. }
  79. fmt.Println(n)
  80. fmt.Println(b.String())
  81. fmt.Println(string(rdbuf))
  82. // Output
  83. // 1
  84. // bcde
  85. // a
  86. }
  87. func ExampleBuffer_ReadByte() {
  88. var b bytes.Buffer
  89. b.Grow(64)
  90. b.Write([]byte("abcde"))
  91. c, err := b.ReadByte()
  92. if err != nil {
  93. panic(err)
  94. }
  95. fmt.Println(c)
  96. fmt.Println(b.String())
  97. // Output
  98. // 97
  99. // bcde
  100. }
  101. func ExampleCompare() {
  102. // Interpret Compare's result by comparing it to zero.
  103. var a, b []byte
  104. if bytes.Compare(a, b) < 0 {
  105. // a less b
  106. }
  107. if bytes.Compare(a, b) <= 0 {
  108. // a less or equal b
  109. }
  110. if bytes.Compare(a, b) > 0 {
  111. // a greater b
  112. }
  113. if bytes.Compare(a, b) >= 0 {
  114. // a greater or equal b
  115. }
  116. // Prefer Equal to Compare for equality comparisons.
  117. if bytes.Equal(a, b) {
  118. // a equal b
  119. }
  120. if !bytes.Equal(a, b) {
  121. // a not equal b
  122. }
  123. }
  124. func ExampleCompare_search() {
  125. // Binary search to find a matching byte slice.
  126. var needle []byte
  127. var haystack [][]byte // Assume sorted
  128. i := sort.Search(len(haystack), func(i int) bool {
  129. // Return haystack[i] >= needle.
  130. return bytes.Compare(haystack[i], needle) >= 0
  131. })
  132. if i < len(haystack) && bytes.Equal(haystack[i], needle) {
  133. // Found it!
  134. }
  135. }
  136. func ExampleContains() {
  137. fmt.Println(bytes.Contains([]byte("seafood"), []byte("foo")))
  138. fmt.Println(bytes.Contains([]byte("seafood"), []byte("bar")))
  139. fmt.Println(bytes.Contains([]byte("seafood"), []byte("")))
  140. fmt.Println(bytes.Contains([]byte(""), []byte("")))
  141. // Output:
  142. // true
  143. // false
  144. // true
  145. // true
  146. }
  147. func ExampleContainsAny() {
  148. fmt.Println(bytes.ContainsAny([]byte("I like seafood."), "fÄo!"))
  149. fmt.Println(bytes.ContainsAny([]byte("I like seafood."), "去是伟大的."))
  150. fmt.Println(bytes.ContainsAny([]byte("I like seafood."), ""))
  151. fmt.Println(bytes.ContainsAny([]byte(""), ""))
  152. // Output:
  153. // true
  154. // true
  155. // false
  156. // false
  157. }
  158. func ExampleContainsRune() {
  159. fmt.Println(bytes.ContainsRune([]byte("I like seafood."), 'f'))
  160. fmt.Println(bytes.ContainsRune([]byte("I like seafood."), 'ö'))
  161. fmt.Println(bytes.ContainsRune([]byte("去是伟大的!"), '大'))
  162. fmt.Println(bytes.ContainsRune([]byte("去是伟大的!"), '!'))
  163. fmt.Println(bytes.ContainsRune([]byte(""), '@'))
  164. // Output:
  165. // true
  166. // false
  167. // true
  168. // true
  169. // false
  170. }
  171. func ExampleCount() {
  172. fmt.Println(bytes.Count([]byte("cheese"), []byte("e")))
  173. fmt.Println(bytes.Count([]byte("five"), []byte(""))) // before & after each rune
  174. // Output:
  175. // 3
  176. // 5
  177. }
  178. func ExampleCut() {
  179. show := func(s, sep string) {
  180. before, after, found := bytes.Cut([]byte(s), []byte(sep))
  181. fmt.Printf("Cut(%q, %q) = %q, %q, %v\n", s, sep, before, after, found)
  182. }
  183. show("Gopher", "Go")
  184. show("Gopher", "ph")
  185. show("Gopher", "er")
  186. show("Gopher", "Badger")
  187. // Output:
  188. // Cut("Gopher", "Go") = "", "pher", true
  189. // Cut("Gopher", "ph") = "Go", "er", true
  190. // Cut("Gopher", "er") = "Goph", "", true
  191. // Cut("Gopher", "Badger") = "Gopher", "", false
  192. }
  193. func ExampleEqual() {
  194. fmt.Println(bytes.Equal([]byte("Go"), []byte("Go")))
  195. fmt.Println(bytes.Equal([]byte("Go"), []byte("C++")))
  196. // Output:
  197. // true
  198. // false
  199. }
  200. func ExampleEqualFold() {
  201. fmt.Println(bytes.EqualFold([]byte("Go"), []byte("go")))
  202. // Output: true
  203. }
  204. func ExampleFields() {
  205. fmt.Printf("Fields are: %q", bytes.Fields([]byte(" foo bar baz ")))
  206. // Output: Fields are: ["foo" "bar" "baz"]
  207. }
  208. func ExampleFieldsFunc() {
  209. f := func(c rune) bool {
  210. return !unicode.IsLetter(c) && !unicode.IsNumber(c)
  211. }
  212. fmt.Printf("Fields are: %q", bytes.FieldsFunc([]byte(" foo1;bar2,baz3..."), f))
  213. // Output: Fields are: ["foo1" "bar2" "baz3"]
  214. }
  215. func ExampleHasPrefix() {
  216. fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("Go")))
  217. fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("C")))
  218. fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("")))
  219. // Output:
  220. // true
  221. // false
  222. // true
  223. }
  224. func ExampleHasSuffix() {
  225. fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("go")))
  226. fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("O")))
  227. fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("Ami")))
  228. fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("")))
  229. // Output:
  230. // true
  231. // false
  232. // false
  233. // true
  234. }
  235. func ExampleIndex() {
  236. fmt.Println(bytes.Index([]byte("chicken"), []byte("ken")))
  237. fmt.Println(bytes.Index([]byte("chicken"), []byte("dmr")))
  238. // Output:
  239. // 4
  240. // -1
  241. }
  242. func ExampleIndexByte() {
  243. fmt.Println(bytes.IndexByte([]byte("chicken"), byte('k')))
  244. fmt.Println(bytes.IndexByte([]byte("chicken"), byte('g')))
  245. // Output:
  246. // 4
  247. // -1
  248. }
  249. func ExampleIndexFunc() {
  250. f := func(c rune) bool {
  251. return unicode.Is(unicode.Han, c)
  252. }
  253. fmt.Println(bytes.IndexFunc([]byte("Hello, 世界"), f))
  254. fmt.Println(bytes.IndexFunc([]byte("Hello, world"), f))
  255. // Output:
  256. // 7
  257. // -1
  258. }
  259. func ExampleIndexAny() {
  260. fmt.Println(bytes.IndexAny([]byte("chicken"), "aeiouy"))
  261. fmt.Println(bytes.IndexAny([]byte("crwth"), "aeiouy"))
  262. // Output:
  263. // 2
  264. // -1
  265. }
  266. func ExampleIndexRune() {
  267. fmt.Println(bytes.IndexRune([]byte("chicken"), 'k'))
  268. fmt.Println(bytes.IndexRune([]byte("chicken"), 'd'))
  269. // Output:
  270. // 4
  271. // -1
  272. }
  273. func ExampleJoin() {
  274. s := [][]byte{[]byte("foo"), []byte("bar"), []byte("baz")}
  275. fmt.Printf("%s", bytes.Join(s, []byte(", ")))
  276. // Output: foo, bar, baz
  277. }
  278. func ExampleLastIndex() {
  279. fmt.Println(bytes.Index([]byte("go gopher"), []byte("go")))
  280. fmt.Println(bytes.LastIndex([]byte("go gopher"), []byte("go")))
  281. fmt.Println(bytes.LastIndex([]byte("go gopher"), []byte("rodent")))
  282. // Output:
  283. // 0
  284. // 3
  285. // -1
  286. }
  287. func ExampleLastIndexAny() {
  288. fmt.Println(bytes.LastIndexAny([]byte("go gopher"), "MüQp"))
  289. fmt.Println(bytes.LastIndexAny([]byte("go 地鼠"), "地大"))
  290. fmt.Println(bytes.LastIndexAny([]byte("go gopher"), "z,!."))
  291. // Output:
  292. // 5
  293. // 3
  294. // -1
  295. }
  296. func ExampleLastIndexByte() {
  297. fmt.Println(bytes.LastIndexByte([]byte("go gopher"), byte('g')))
  298. fmt.Println(bytes.LastIndexByte([]byte("go gopher"), byte('r')))
  299. fmt.Println(bytes.LastIndexByte([]byte("go gopher"), byte('z')))
  300. // Output:
  301. // 3
  302. // 8
  303. // -1
  304. }
  305. func ExampleLastIndexFunc() {
  306. fmt.Println(bytes.LastIndexFunc([]byte("go gopher!"), unicode.IsLetter))
  307. fmt.Println(bytes.LastIndexFunc([]byte("go gopher!"), unicode.IsPunct))
  308. fmt.Println(bytes.LastIndexFunc([]byte("go gopher!"), unicode.IsNumber))
  309. // Output:
  310. // 8
  311. // 9
  312. // -1
  313. }
  314. func ExampleReader_Len() {
  315. fmt.Println(bytes.NewReader([]byte("Hi!")).Len())
  316. fmt.Println(bytes.NewReader([]byte("こんにちは!")).Len())
  317. // Output:
  318. // 3
  319. // 16
  320. }
  321. func ExampleRepeat() {
  322. fmt.Printf("ba%s", bytes.Repeat([]byte("na"), 2))
  323. // Output: banana
  324. }
  325. func ExampleReplace() {
  326. fmt.Printf("%s\n", bytes.Replace([]byte("oink oink oink"), []byte("k"), []byte("ky"), 2))
  327. fmt.Printf("%s\n", bytes.Replace([]byte("oink oink oink"), []byte("oink"), []byte("moo"), -1))
  328. // Output:
  329. // oinky oinky oink
  330. // moo moo moo
  331. }
  332. func ExampleReplaceAll() {
  333. fmt.Printf("%s\n", bytes.ReplaceAll([]byte("oink oink oink"), []byte("oink"), []byte("moo")))
  334. // Output:
  335. // moo moo moo
  336. }
  337. func ExampleRunes() {
  338. rs := bytes.Runes([]byte("go gopher"))
  339. for _, r := range rs {
  340. fmt.Printf("%#U\n", r)
  341. }
  342. // Output:
  343. // U+0067 'g'
  344. // U+006F 'o'
  345. // U+0020 ' '
  346. // U+0067 'g'
  347. // U+006F 'o'
  348. // U+0070 'p'
  349. // U+0068 'h'
  350. // U+0065 'e'
  351. // U+0072 'r'
  352. }
  353. func ExampleSplit() {
  354. fmt.Printf("%q\n", bytes.Split([]byte("a,b,c"), []byte(",")))
  355. fmt.Printf("%q\n", bytes.Split([]byte("a man a plan a canal panama"), []byte("a ")))
  356. fmt.Printf("%q\n", bytes.Split([]byte(" xyz "), []byte("")))
  357. fmt.Printf("%q\n", bytes.Split([]byte(""), []byte("Bernardo O'Higgins")))
  358. // Output:
  359. // ["a" "b" "c"]
  360. // ["" "man " "plan " "canal panama"]
  361. // [" " "x" "y" "z" " "]
  362. // [""]
  363. }
  364. func ExampleSplitN() {
  365. fmt.Printf("%q\n", bytes.SplitN([]byte("a,b,c"), []byte(","), 2))
  366. z := bytes.SplitN([]byte("a,b,c"), []byte(","), 0)
  367. fmt.Printf("%q (nil = %v)\n", z, z == nil)
  368. // Output:
  369. // ["a" "b,c"]
  370. // [] (nil = true)
  371. }
  372. func ExampleSplitAfter() {
  373. fmt.Printf("%q\n", bytes.SplitAfter([]byte("a,b,c"), []byte(",")))
  374. // Output: ["a," "b," "c"]
  375. }
  376. func ExampleSplitAfterN() {
  377. fmt.Printf("%q\n", bytes.SplitAfterN([]byte("a,b,c"), []byte(","), 2))
  378. // Output: ["a," "b,c"]
  379. }
  380. func ExampleTitle() {
  381. fmt.Printf("%s", bytes.Title([]byte("her royal highness")))
  382. // Output: Her Royal Highness
  383. }
  384. func ExampleToTitle() {
  385. fmt.Printf("%s\n", bytes.ToTitle([]byte("loud noises")))
  386. fmt.Printf("%s\n", bytes.ToTitle([]byte("хлеб")))
  387. // Output:
  388. // LOUD NOISES
  389. // ХЛЕБ
  390. }
  391. func ExampleToTitleSpecial() {
  392. str := []byte("ahoj vývojári golang")
  393. totitle := bytes.ToTitleSpecial(unicode.AzeriCase, str)
  394. fmt.Println("Original : " + string(str))
  395. fmt.Println("ToTitle : " + string(totitle))
  396. // Output:
  397. // Original : ahoj vývojári golang
  398. // ToTitle : AHOJ VÝVOJÁRİ GOLANG
  399. }
  400. func ExampleTrim() {
  401. fmt.Printf("[%q]", bytes.Trim([]byte(" !!! Achtung! Achtung! !!! "), "! "))
  402. // Output: ["Achtung! Achtung"]
  403. }
  404. func ExampleTrimFunc() {
  405. fmt.Println(string(bytes.TrimFunc([]byte("go-gopher!"), unicode.IsLetter)))
  406. fmt.Println(string(bytes.TrimFunc([]byte("\"go-gopher!\""), unicode.IsLetter)))
  407. fmt.Println(string(bytes.TrimFunc([]byte("go-gopher!"), unicode.IsPunct)))
  408. fmt.Println(string(bytes.TrimFunc([]byte("1234go-gopher!567"), unicode.IsNumber)))
  409. // Output:
  410. // -gopher!
  411. // "go-gopher!"
  412. // go-gopher
  413. // go-gopher!
  414. }
  415. func ExampleTrimLeft() {
  416. fmt.Print(string(bytes.TrimLeft([]byte("453gopher8257"), "0123456789")))
  417. // Output:
  418. // gopher8257
  419. }
  420. func ExampleTrimLeftFunc() {
  421. fmt.Println(string(bytes.TrimLeftFunc([]byte("go-gopher"), unicode.IsLetter)))
  422. fmt.Println(string(bytes.TrimLeftFunc([]byte("go-gopher!"), unicode.IsPunct)))
  423. fmt.Println(string(bytes.TrimLeftFunc([]byte("1234go-gopher!567"), unicode.IsNumber)))
  424. // Output:
  425. // -gopher
  426. // go-gopher!
  427. // go-gopher!567
  428. }
  429. func ExampleTrimPrefix() {
  430. var b = []byte("Goodbye,, world!")
  431. b = bytes.TrimPrefix(b, []byte("Goodbye,"))
  432. b = bytes.TrimPrefix(b, []byte("See ya,"))
  433. fmt.Printf("Hello%s", b)
  434. // Output: Hello, world!
  435. }
  436. func ExampleTrimSpace() {
  437. fmt.Printf("%s", bytes.TrimSpace([]byte(" \t\n a lone gopher \n\t\r\n")))
  438. // Output: a lone gopher
  439. }
  440. func ExampleTrimSuffix() {
  441. var b = []byte("Hello, goodbye, etc!")
  442. b = bytes.TrimSuffix(b, []byte("goodbye, etc!"))
  443. b = bytes.TrimSuffix(b, []byte("gopher"))
  444. b = append(b, bytes.TrimSuffix([]byte("world!"), []byte("x!"))...)
  445. os.Stdout.Write(b)
  446. // Output: Hello, world!
  447. }
  448. func ExampleTrimRight() {
  449. fmt.Print(string(bytes.TrimRight([]byte("453gopher8257"), "0123456789")))
  450. // Output:
  451. // 453gopher
  452. }
  453. func ExampleTrimRightFunc() {
  454. fmt.Println(string(bytes.TrimRightFunc([]byte("go-gopher"), unicode.IsLetter)))
  455. fmt.Println(string(bytes.TrimRightFunc([]byte("go-gopher!"), unicode.IsPunct)))
  456. fmt.Println(string(bytes.TrimRightFunc([]byte("1234go-gopher!567"), unicode.IsNumber)))
  457. // Output:
  458. // go-
  459. // go-gopher
  460. // 1234go-gopher!
  461. }
  462. func ExampleToLower() {
  463. fmt.Printf("%s", bytes.ToLower([]byte("Gopher")))
  464. // Output: gopher
  465. }
  466. func ExampleToLowerSpecial() {
  467. str := []byte("AHOJ VÝVOJÁRİ GOLANG")
  468. totitle := bytes.ToLowerSpecial(unicode.AzeriCase, str)
  469. fmt.Println("Original : " + string(str))
  470. fmt.Println("ToLower : " + string(totitle))
  471. // Output:
  472. // Original : AHOJ VÝVOJÁRİ GOLANG
  473. // ToLower : ahoj vývojári golang
  474. }
  475. func ExampleToUpper() {
  476. fmt.Printf("%s", bytes.ToUpper([]byte("Gopher")))
  477. // Output: GOPHER
  478. }
  479. func ExampleToUpperSpecial() {
  480. str := []byte("ahoj vývojári golang")
  481. totitle := bytes.ToUpperSpecial(unicode.AzeriCase, str)
  482. fmt.Println("Original : " + string(str))
  483. fmt.Println("ToUpper : " + string(totitle))
  484. // Output:
  485. // Original : ahoj vývojári golang
  486. // ToUpper : AHOJ VÝVOJÁRİ GOLANG
  487. }