Documentation
¶
Overview ¶
bytesパッケージはバイトスライスの操作のための関数を実装します。 これは strings パッケージの機能に類似しています。
Index ¶
- Constants
- Variables
- func Clone(b []byte) []byte
- func Compare(a, b []byte) int
- func Contains(b, subslice []byte) bool
- func ContainsAny(b []byte, chars string) bool
- func ContainsFunc(b []byte, f func(rune) bool) bool
- func ContainsRune(b []byte, r rune) bool
- func Count(s, sep []byte) int
- func Cut(s, sep []byte) (before, after []byte, found bool)
- func CutPrefix(s, prefix []byte) (after []byte, found bool)
- func CutSuffix(s, suffix []byte) (before []byte, found bool)
- func Equal(a, b []byte) bool
- func EqualFold(s, t []byte) bool
- func Fields(s []byte) [][]byte
- func FieldsFunc(s []byte, f func(rune) bool) [][]byte
- func FieldsFuncSeq(s []byte, f func(rune) bool) iter.Seq[[]byte]
- func FieldsSeq(s []byte) iter.Seq[[]byte]
- func HasPrefix(s, prefix []byte) bool
- func HasSuffix(s, suffix []byte) bool
- func Index(s, sep []byte) int
- func IndexAny(s []byte, chars string) int
- func IndexByte(b []byte, c byte) int
- func IndexFunc(s []byte, f func(r rune) bool) int
- func IndexRune(s []byte, r rune) int
- func Join(s [][]byte, sep []byte) []byte
- func LastIndex(s, sep []byte) int
- func LastIndexAny(s []byte, chars string) int
- func LastIndexByte(s []byte, c byte) int
- func LastIndexFunc(s []byte, f func(r rune) bool) int
- func Lines(s []byte) iter.Seq[[]byte]
- func Map(mapping func(r rune) rune, s []byte) []byte
- func Repeat(b []byte, count int) []byte
- func Replace(s, old, new []byte, n int) []byte
- func ReplaceAll(s, old, new []byte) []byte
- func Runes(s []byte) []rune
- func Split(s, sep []byte) [][]byte
- func SplitAfter(s, sep []byte) [][]byte
- func SplitAfterN(s, sep []byte, n int) [][]byte
- func SplitAfterSeq(s, sep []byte) iter.Seq[[]byte]
- func SplitN(s, sep []byte, n int) [][]byte
- func SplitSeq(s, sep []byte) iter.Seq[[]byte]
- func Title(s []byte) []bytedeprecated
- func ToLower(s []byte) []byte
- func ToLowerSpecial(c unicode.SpecialCase, s []byte) []byte
- func ToTitle(s []byte) []byte
- func ToTitleSpecial(c unicode.SpecialCase, s []byte) []byte
- func ToUpper(s []byte) []byte
- func ToUpperSpecial(c unicode.SpecialCase, s []byte) []byte
- func ToValidUTF8(s, replacement []byte) []byte
- func Trim(s []byte, cutset string) []byte
- func TrimFunc(s []byte, f func(r rune) bool) []byte
- func TrimLeft(s []byte, cutset string) []byte
- func TrimLeftFunc(s []byte, f func(r rune) bool) []byte
- func TrimPrefix(s, prefix []byte) []byte
- func TrimRight(s []byte, cutset string) []byte
- func TrimRightFunc(s []byte, f func(r rune) bool) []byte
- func TrimSpace(s []byte) []byte
- func TrimSuffix(s, suffix []byte) []byte
- type Buffer
- func (b *Buffer) Available() int
- func (b *Buffer) AvailableBuffer() []byte
- func (b *Buffer) Bytes() []byte
- func (b *Buffer) Cap() int
- func (b *Buffer) Grow(n int)
- func (b *Buffer) Len() int
- func (b *Buffer) Next(n int) []byte
- func (b *Buffer) Read(p []byte) (n int, err error)
- func (b *Buffer) ReadByte() (byte, error)
- func (b *Buffer) ReadBytes(delim byte) (line []byte, err error)
- func (b *Buffer) ReadFrom(r io.Reader) (n int64, err error)
- func (b *Buffer) ReadRune() (r rune, size int, err error)
- func (b *Buffer) ReadString(delim byte) (line string, err error)
- func (b *Buffer) Reset()
- func (b *Buffer) String() string
- func (b *Buffer) Truncate(n int)
- func (b *Buffer) UnreadByte() error
- func (b *Buffer) UnreadRune() error
- func (b *Buffer) Write(p []byte) (n int, err error)
- func (b *Buffer) WriteByte(c byte) error
- func (b *Buffer) WriteRune(r rune) (n int, err error)
- func (b *Buffer) WriteString(s string) (n int, err error)
- func (b *Buffer) WriteTo(w io.Writer) (n int64, err error)
- type Reader
- func (r *Reader) Len() int
- func (r *Reader) Read(b []byte) (n int, err error)
- func (r *Reader) ReadAt(b []byte, off int64) (n int, err error)
- func (r *Reader) ReadByte() (byte, error)
- func (r *Reader) ReadRune() (ch rune, size int, err error)
- func (r *Reader) Reset(b []byte)
- func (r *Reader) Seek(offset int64, whence int) (int64, error)
- func (r *Reader) Size() int64
- func (r *Reader) UnreadByte() error
- func (r *Reader) UnreadRune() error
- func (r *Reader) WriteTo(w io.Writer) (n int64, err error)
Examples ¶
- Buffer
- Buffer (Reader)
- Buffer.AvailableBuffer
- Buffer.Bytes
- Buffer.Cap
- Buffer.Grow
- Buffer.Len
- Buffer.Next
- Buffer.Read
- Buffer.ReadByte
- Clone
- Compare
- Compare (Search)
- Contains
- ContainsAny
- ContainsFunc
- ContainsRune
- Count
- Cut
- CutPrefix
- CutSuffix
- Equal
- EqualFold
- Fields
- FieldsFunc
- FieldsFuncSeq
- FieldsSeq
- HasPrefix
- HasSuffix
- Index
- IndexAny
- IndexByte
- IndexFunc
- IndexRune
- Join
- LastIndex
- LastIndexAny
- LastIndexByte
- LastIndexFunc
- Lines
- Map
- Reader.Len
- Repeat
- Replace
- ReplaceAll
- Runes
- Split
- SplitAfter
- SplitAfterN
- SplitAfterSeq
- SplitN
- SplitSeq
- Title
- ToLower
- ToLowerSpecial
- ToTitle
- ToTitleSpecial
- ToUpper
- ToUpperSpecial
- ToValidUTF8
- Trim
- TrimFunc
- TrimLeft
- TrimLeftFunc
- TrimPrefix
- TrimRight
- TrimRightFunc
- TrimSpace
- TrimSuffix
Constants ¶
const MinRead = 512
MinReadは、Buffer.ReadFrom によって Buffer.Read 呼び出しに渡される最小スライスサイズです。 Buffer がrの内容を保持するのに必要なバイト数を超えて少なくともMinReadバイトを持っている限り、 Buffer.ReadFrom は基礎となるバッファを拡張しません。
Variables ¶
var ErrTooLarge = errors.New("bytes.Buffer: too large")
ErrTooLargeは、バッファにデータを格納するためのメモリを割り当てることができない場合にpanicに渡されます。
Functions ¶
func Clone ¶ added in v1.20.0
Cloneはb[:len(b)]のコピーを返します。 結果には余分な未使用の容量があるかもしれません。 Clone(nil)はnilを返します。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
b := []byte("abc")
clone := bytes.Clone(b)
fmt.Printf("%s\n", clone)
clone[0] = 'd'
fmt.Printf("%s\n", b)
fmt.Printf("%s\n", clone)
}
Output: abc abc dbc
func Compare ¶
Compare関数は2つのバイトスライスを辞書的に比較して整数を返します。 a == bの場合は0、a < bの場合は-1、a > bの場合は+1となります。 nilの引数は空スライスと同等です。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
)
func main() {
// Interpret Compare's result by comparing it to zero.
var a, b []byte
if bytes.Compare(a, b) < 0 {
// a less b
}
if bytes.Compare(a, b) <= 0 {
// a less or equal b
}
if bytes.Compare(a, b) > 0 {
// a greater b
}
if bytes.Compare(a, b) >= 0 {
// a greater or equal b
}
// Prefer Equal to Compare for equality comparisons.
if bytes.Equal(a, b) {
// a equal b
}
if !bytes.Equal(a, b) {
// a not equal b
}
}
Example (Search) ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/slices"
)
func main() {
// Binary search to find a matching byte slice.
var needle []byte
var haystack [][]byte // Assume sorted
_, found := slices.BinarySearchFunc(haystack, needle, bytes.Compare)
if found {
// Found it!
}
}
func Contains ¶
subsliceがb内に含まれているかどうかを報告します。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
fmt.Println(bytes.Contains([]byte("seafood"), []byte("foo")))
fmt.Println(bytes.Contains([]byte("seafood"), []byte("bar")))
fmt.Println(bytes.Contains([]byte("seafood"), []byte("")))
fmt.Println(bytes.Contains([]byte(""), []byte("")))
}
Output: true false true true
func ContainsAny ¶ added in v1.7.0
ContainsAnyは、chars内のUTF-8エンコードされたコードポイントのいずれかがb内に含まれているかどうかを報告します。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
fmt.Println(bytes.ContainsAny([]byte("I like seafood."), "fÄo!"))
fmt.Println(bytes.ContainsAny([]byte("I like seafood."), "去是伟大的."))
fmt.Println(bytes.ContainsAny([]byte("I like seafood."), ""))
fmt.Println(bytes.ContainsAny([]byte(""), ""))
}
Output: true true false false
func ContainsFunc ¶ added in v1.21.0
ContainsFuncは、UTF-8エンコードされたコードポイントの中で、bのどれかがf(r)を満たすかどうかを報告します。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
f := func(r rune) bool {
return r >= 'a' && r <= 'z'
}
fmt.Println(bytes.ContainsFunc([]byte("HELLO"), f))
fmt.Println(bytes.ContainsFunc([]byte("World"), f))
}
Output: false true
func ContainsRune ¶ added in v1.7.0
ContainsRuneは、UTF-8でエンコードされたバイトスライスbにルーンが含まれているかどうかを報告します。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
fmt.Println(bytes.ContainsRune([]byte("I like seafood."), 'f'))
fmt.Println(bytes.ContainsRune([]byte("I like seafood."), 'ö'))
fmt.Println(bytes.ContainsRune([]byte("去是伟大的!"), '大'))
fmt.Println(bytes.ContainsRune([]byte("去是伟大的!"), '!'))
fmt.Println(bytes.ContainsRune([]byte(""), '@'))
}
Output: true false true true false
func Count ¶
Count は s において非重複の sep の出現回数を数えます。 もし sep が空のスライスなら、Count は s 中の UTF-8 エンコードされたコードポイントの数に 1 を加えた値を返します。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
fmt.Println(bytes.Count([]byte("cheese"), []byte("e")))
fmt.Println(bytes.Count([]byte("five"), []byte(""))) // before & after each rune
}
Output: 3 5
func Cut ¶ added in v1.18.0
最初の「sep」のインスタンス周りのスライス「s」を切り取り、 sepの前と後のテキストを返します。 見つかった結果は「sep」が「s」に現れるかどうかを報告します。 もし「sep」が「s」に現れない場合、cutは「s」とnil、falseを返します。
Cutは元のスライス「s」のスライスを返します、コピーではありません。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
show := func(s, sep string) {
before, after, found := bytes.Cut([]byte(s), []byte(sep))
fmt.Printf("Cut(%q, %q) = %q, %q, %v\n", s, sep, before, after, found)
}
show("Gopher", "Go")
show("Gopher", "ph")
show("Gopher", "er")
show("Gopher", "Badger")
}
Output: Cut("Gopher", "Go") = "", "pher", true Cut("Gopher", "ph") = "Go", "er", true Cut("Gopher", "er") = "Goph", "", true Cut("Gopher", "Badger") = "Gopher", "", false
func CutPrefix ¶ added in v1.20.0
CutPrefixは与えられた先頭接頭辞のバイトスライスを取り除き、 接頭辞が見つかったかどうかを報告します。 もしsが接頭辞で始まっていない場合、CutPrefixはs、falseを返します。 もし接頭辞が空のバイトスライスの場合、CutPrefixはs、trueを返します。
CutPrefixは元のスライスsの断片を返します、コピーではありません。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
show := func(s, prefix string) {
after, found := bytes.CutPrefix([]byte(s), []byte(prefix))
fmt.Printf("CutPrefix(%q, %q) = %q, %v\n", s, prefix, after, found)
}
show("Gopher", "Go")
show("Gopher", "ph")
}
Output: CutPrefix("Gopher", "Go") = "pher", true CutPrefix("Gopher", "ph") = "Gopher", false
func CutSuffix ¶ added in v1.20.0
CutSuffixは与えられた終了サフィックスのバイトスライスを除いたsを返し、そのサフィックスが見つかったかどうかを報告します。 もしsがサフィックスで終わらない場合、CutSuffixはs、falseを返します。 もしサフィックスが空のバイトスライスである場合、CutSuffixはs、trueを返します。
CutSuffixは元のスライスsのスライスを返しますが、コピーではありません。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
show := func(s, suffix string) {
before, found := bytes.CutSuffix([]byte(s), []byte(suffix))
fmt.Printf("CutSuffix(%q, %q) = %q, %v\n", s, suffix, before, found)
}
show("Gopher", "Go")
show("Gopher", "er")
}
Output: CutSuffix("Gopher", "Go") = "Gopher", false CutSuffix("Gopher", "er") = "Goph", true
func Equal ¶
Equalは、aとbが同じ長さで同じバイトを含むかどうかを報告します。 nilの引数は空のスライスと等価です。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
fmt.Println(bytes.Equal([]byte("Go"), []byte("Go")))
fmt.Println(bytes.Equal([]byte("Go"), []byte("C++")))
}
Output: true false
func EqualFold ¶
EqualFoldは、UTF-8文字列として解釈されたsとtが、単純なUnicodeの大文字小文字を区別しない比較で等しいかどうかを報告します。これは、大文字小文字を区別しない形式の一般的なUnicodeです。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
fmt.Println(bytes.EqualFold([]byte("Go"), []byte("go")))
}
Output: true
func Fields ¶
FieldsはsをUTF-8エンコードされたコードポイントのシーケンスとして解釈します。 unicode.IsSpace で定義される1つ以上の連続する空白文字の各インスタンスの周りで スライスsを分割し、sのサブスライスのスライスを返すか、 sが空白のみを含む場合は空のスライスを返します。返されるスライスのすべての要素は 空ではありません。Split とは異なり、先頭と末尾の空白文字の連続は破棄されます。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
fmt.Printf("Fields are: %q", bytes.Fields([]byte(" foo bar baz ")))
}
Output: Fields are: ["foo" "bar" "baz"]
func FieldsFunc ¶
FieldsFuncは、sをUTF-8エンコードされたコードポイントのシーケンスとして解釈します。 f(c)を満たすコードポイントcの各連続部分でスライスsを分割し、 sのサブスライスのスライスを返します。sのすべてのコードポイントがf(c)を満たすか、 len(s) == 0の場合、空のスライスを返します。返されるスライスのすべての要素は 空ではありません。[SplitFunc] とは異なり、f(c)を満たすコードポイントの 先頭と末尾の連続部分は破棄されます。
FieldsFuncは、f(c)をどの順序で呼び出すかについて保証はなく、fは常に同じ値を返すと仮定しています。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
"github.com/shogo82148/std/unicode"
)
func main() {
f := func(c rune) bool {
return !unicode.IsLetter(c) && !unicode.IsNumber(c)
}
fmt.Printf("Fields are: %q", bytes.FieldsFunc([]byte(" foo1;bar2,baz3..."), f))
}
Output: Fields are: ["foo1" "bar2" "baz3"]
func FieldsFuncSeq ¶ added in v1.25.0
FieldsFuncSeq returns an iterator over subslices of s split around runs of Unicode code points satisfying f(c). The iterator yields the same subslices that would be returned by FieldsFunc(s), but without constructing a new slice containing the subslices.
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
"github.com/shogo82148/std/unicode"
)
func main() {
text := []byte("The quick brown fox")
fmt.Println("Split on whitespace(similar to FieldsSeq):")
for word := range bytes.FieldsFuncSeq(text, unicode.IsSpace) {
fmt.Printf("%q\n", word)
}
mixedText := []byte("abc123def456ghi")
fmt.Println("\nSplit on digits:")
for word := range bytes.FieldsFuncSeq(mixedText, unicode.IsDigit) {
fmt.Printf("%q\n", word)
}
}
Output: Split on whitespace(similar to FieldsSeq): "The" "quick" "brown" "fox" Split on digits: "abc" "def" "ghi"
func FieldsSeq ¶ added in v1.25.0
FieldsSeq returns an iterator over subslices of s split around runs of whitespace characters, as defined by unicode.IsSpace. The iterator yields the same subslices that would be returned by Fields(s), but without constructing a new slice containing the subslices.
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
text := []byte("The quick brown fox")
fmt.Println("Split byte slice into fields:")
for word := range bytes.FieldsSeq(text) {
fmt.Printf("%q\n", word)
}
textWithSpaces := []byte(" lots of spaces ")
fmt.Println("\nSplit byte slice with multiple spaces:")
for word := range bytes.FieldsSeq(textWithSpaces) {
fmt.Printf("%q\n", word)
}
}
Output: Split byte slice into fields: "The" "quick" "brown" "fox" Split byte slice with multiple spaces: "lots" "of" "spaces"
func HasPrefix ¶
HasPrefixは、バイトスライスsがprefixで始まるかどうかを報告します。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("Go")))
fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("C")))
fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("")))
}
Output: true false true
func HasSuffix ¶
HasSuffixは、バイトスライスsがsuffixで終わるかどうかを報告します。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("go")))
fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("O")))
fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("Ami")))
fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("")))
}
Output: true false false true
func Index ¶
Indexは、sの最初のsepのインスタンスのインデックスを返します。sepがsに存在しない場合は、-1を返します。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
fmt.Println(bytes.Index([]byte("chicken"), []byte("ken")))
fmt.Println(bytes.Index([]byte("chicken"), []byte("dmr")))
}
Output: 4 -1
func IndexAny ¶
IndexAnyはsをUTF-8エンコードされたUnicodeのコードポイントのシーケンスとして解釈します。 sの中でcharsのいずれかのUnicodeコードポイントの最初の出現のバイトインデックスを返します。 charsが空であるか、共通のコードポイントがない場合は-1を返します。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
fmt.Println(bytes.IndexAny([]byte("chicken"), "aeiouy"))
fmt.Println(bytes.IndexAny([]byte("crwth"), "aeiouy"))
}
Output: 2 -1
func IndexByte ¶
IndexByteはb内の最初のcのインスタンスのインデックスを返します。もしcがbに存在しない場合は、-1を返します。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
fmt.Println(bytes.IndexByte([]byte("chicken"), byte('k')))
fmt.Println(bytes.IndexByte([]byte("chicken"), byte('g')))
}
Output: 4 -1
func IndexFunc ¶
IndexFuncは、sをUTF-8エンコードされたコードポイントのシーケンスとして解釈します。 sの中でf(c)を満たす最初のUnicodeコードポイントのバイトインデックスを返します。 該当するコードポイントがない場合は-1を返します。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
"github.com/shogo82148/std/unicode"
)
func main() {
f := func(c rune) bool {
return unicode.Is(unicode.Han, c)
}
fmt.Println(bytes.IndexFunc([]byte("Hello, 世界"), f))
fmt.Println(bytes.IndexFunc([]byte("Hello, world"), f))
}
Output: 7 -1
func IndexRune ¶
IndexRuneはsをUTF-8でエンコードされたコードポイントのシーケンスとして解釈します。 sの中で指定されたルーンの最初の出現のバイトインデックスを返します。 sにルーンが含まれていない場合は-1を返します。 rが [utf8.RuneError] である場合、無効なUTF-8バイトシーケンスの最初のインスタンスを返します。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
fmt.Println(bytes.IndexRune([]byte("chicken"), 'k'))
fmt.Println(bytes.IndexRune([]byte("chicken"), 'd'))
}
Output: 4 -1
func Join ¶
Join関数は、sの要素を連結して新しいバイトスライスを作成します。結果のスライスの要素間にはセパレーターsepが配置されます。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
s := [][]byte{[]byte("foo"), []byte("bar"), []byte("baz")}
fmt.Printf("%s", bytes.Join(s, []byte(", ")))
}
Output: foo, bar, baz
func LastIndex ¶
LastIndex関数は、s内のsepの最後のインスタンスのインデックスを返します。sepがs内に存在しない場合は、-1を返します。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
fmt.Println(bytes.Index([]byte("go gopher"), []byte("go")))
fmt.Println(bytes.LastIndex([]byte("go gopher"), []byte("go")))
fmt.Println(bytes.LastIndex([]byte("go gopher"), []byte("rodent")))
}
Output: 0 3 -1
func LastIndexAny ¶
LastIndexAnyは、sをUTF-8でエンコードされたUnicodeコードポイントの シーケンスとして解釈します。charsに含まれる任意のUnicodeコードポイントの 最後の出現のバイトインデックスを返します。charsが空である場合や、 共通のコードポイントが存在しない場合は、-1を返します。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
fmt.Println(bytes.LastIndexAny([]byte("go gopher"), "MüQp"))
fmt.Println(bytes.LastIndexAny([]byte("go 地鼠"), "地大"))
fmt.Println(bytes.LastIndexAny([]byte("go gopher"), "z,!."))
}
Output: 5 3 -1
func LastIndexByte ¶ added in v1.5.0
LastIndexByteは、cがs内で最後に出現するインデックスを返します。cがs内に存在しない場合は-1を返します。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
fmt.Println(bytes.LastIndexByte([]byte("go gopher"), byte('g')))
fmt.Println(bytes.LastIndexByte([]byte("go gopher"), byte('r')))
fmt.Println(bytes.LastIndexByte([]byte("go gopher"), byte('z')))
}
Output: 3 8 -1
func LastIndexFunc ¶
LastIndexFuncはsをUTF-8でエンコードされたコードポイントのシーケンスとして解釈します。 f(c)を満たす最後のUnicodeコードポイントのバイトインデックスを、f(c)を満たすものがない場合は-1を返します。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
"github.com/shogo82148/std/unicode"
)
func main() {
fmt.Println(bytes.LastIndexFunc([]byte("go gopher!"), unicode.IsLetter))
fmt.Println(bytes.LastIndexFunc([]byte("go gopher!"), unicode.IsPunct))
fmt.Println(bytes.LastIndexFunc([]byte("go gopher!"), unicode.IsNumber))
}
Output: 8 9 -1
func Lines ¶ added in v1.25.0
Lines returns an iterator over the newline-terminated lines in the byte slice s. The lines yielded by the iterator include their terminating newlines. If s is empty, the iterator yields no lines at all. If s does not end in a newline, the final yielded line will not end in a newline. It returns a single-use iterator.
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
text := []byte("Hello\nWorld\nGo Programming\n")
for line := range bytes.Lines(text) {
fmt.Printf("%q\n", line)
}
}
Output: "Hello\n" "World\n" "Go Programming\n"
func Map ¶
Map関数は、与えられたマッピング関数に基づいて、バイトスライスsのすべての文字が変更されたコピーを返します。 マッピング関数が負の値を返すと、文字は置換せずにバイトスライスから削除されます。 sと出力の文字はUTF-8エンコードされたコードポイントとして解釈されます。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
rot13 := func(r rune) rune {
switch {
case r >= 'A' && r <= 'Z':
return 'A' + (r-'A'+13)%26
case r >= 'a' && r <= 'z':
return 'a' + (r-'a'+13)%26
}
return r
}
fmt.Printf("%s\n", bytes.Map(rot13, []byte("'Twas brillig and the slithy gopher...")))
}
Output: 'Gjnf oevyyvt naq gur fyvgul tbcure...
func Repeat ¶
Repeat は、bのcount回のコピーからなる新しいバイトスライスを返します。
countが負数であるか、(len(b) * count)の結果がオーバーフローする場合、パニックが発生します。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
fmt.Printf("ba%s", bytes.Repeat([]byte("na"), 2))
}
Output: banana
func Replace ¶
Replaceは、スライスsの最初のn個の重ならない oldのインスタンスをnewで置き換えたスライスのコピーを返します。 oldが空の場合、スライスの先頭とUTF-8シーケンスの後に一致し、 kランスライスに対してk+1回の置換がされます。 nが負の場合、置換の数に制限はありません。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
fmt.Printf("%s\n", bytes.Replace([]byte("oink oink oink"), []byte("k"), []byte("ky"), 2))
fmt.Printf("%s\n", bytes.Replace([]byte("oink oink oink"), []byte("oink"), []byte("moo"), -1))
}
Output: oinky oinky oink moo moo moo
func ReplaceAll ¶ added in v1.12.0
ReplaceAllは、スライスsのすべての非重複インスタンスをoldからnewに置き換えたスライスのコピーを返します。 oldが空の場合、スライスの先頭とUTF-8シーケンスの後に一致し、kランスライスに対してk+1回の置換が行われます。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
fmt.Printf("%s\n", bytes.ReplaceAll([]byte("oink oink oink"), []byte("oink"), []byte("moo")))
}
Output: moo moo moo
func Runes ¶
RunesはUTF-8でエンコードされたコードポイントのシーケンスとしてsを解釈します。 sと同等のルーン(Unicodeのコードポイント)のスライスを返します。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
rs := bytes.Runes([]byte("go gopher"))
for _, r := range rs {
fmt.Printf("%#U\n", r)
}
}
Output: U+0067 'g' U+006F 'o' U+0020 ' ' U+0067 'g' U+006F 'o' U+0070 'p' U+0068 'h' U+0065 'e' U+0072 'r'
func Split ¶
Split関数は、sをsepで区切ったすべてのサブスライスから成るスライスを返します。 sepが空の場合、Split関数はUTF-8シーケンスごとに区切ります。 これは、SplitN関数にカウント-1を指定した場合と同等です。
最初の区切り文字で区切る場合は、Cut 関数を参照してください。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
fmt.Printf("%q\n", bytes.Split([]byte("a,b,c"), []byte(",")))
fmt.Printf("%q\n", bytes.Split([]byte("a man a plan a canal panama"), []byte("a ")))
fmt.Printf("%q\n", bytes.Split([]byte(" xyz "), []byte("")))
fmt.Printf("%q\n", bytes.Split([]byte(""), []byte("Bernardo O'Higgins")))
}
Output: ["a" "b" "c"] ["" "man " "plan " "canal panama"] [" " "x" "y" "z" " "] [""]
func SplitAfter ¶
SplitAfterは、sをsepの各インスタンスの後にスライスし、それらのサブスライスのスライスを返します。 sepが空の場合、UTF-8のシーケンスの後に分割します。 これは、countが-1のSplitAfterNと同等です。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
fmt.Printf("%q\n", bytes.SplitAfter([]byte("a,b,c"), []byte(",")))
}
Output: ["a," "b," "c"]
func SplitAfterN ¶
SplitAfterNはsをsepの各インスタンスの後ろでサブスライスに分割し、それらのサブスライスのスライスを返します。 sepが空である場合、SplitAfterNはUTF-8シーケンスの後ろで分割します。 countは返すサブスライスの数を決定します:
- n > 0:最大nのサブスライス;最後のサブスライスは分割されていない残りになります。
- n == 0:結果はnilです(サブスライスはゼロ個)
- n < 0:すべてのサブスライス
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
fmt.Printf("%q\n", bytes.SplitAfterN([]byte("a,b,c"), []byte(","), 2))
}
Output: ["a," "b,c"]
func SplitAfterSeq ¶ added in v1.25.0
SplitAfterSeq returns an iterator over subslices of s split after each instance of sep. The iterator yields the same subslices that would be returned by SplitAfter(s, sep), but without constructing a new slice containing the subslices. It returns a single-use iterator.
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
s := []byte("a,b,c,d")
for part := range bytes.SplitAfterSeq(s, []byte(",")) {
fmt.Printf("%q\n", part)
}
}
Output: "a," "b," "c," "d"
func SplitN ¶
SplitNは、sをsepで区切り、そのセパレーターの間のサブスライスのスライスを返します。 sepが空の場合、SplitNは各UTF-8シーケンスの後に分割します。 countは返すサブスライスの数を決定します:
- n> 0:最大でn個のサブスライス;最後のサブスライスは分割パートが含まれます。
- n == 0:結果はnilです(ゼロのサブスライス)
- n < 0:すべてのサブスライス
最初のセパレーターの周りで分割するには、Cut を参照してください。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
fmt.Printf("%q\n", bytes.SplitN([]byte("a,b,c"), []byte(","), 2))
z := bytes.SplitN([]byte("a,b,c"), []byte(","), 0)
fmt.Printf("%q (nil = %v)\n", z, z == nil)
}
Output: ["a" "b,c"] [] (nil = true)
func SplitSeq ¶ added in v1.25.0
SplitSeq returns an iterator over all subslices of s separated by sep. The iterator yields the same subslices that would be returned by Split(s, sep), but without constructing a new slice containing the subslices. It returns a single-use iterator.
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
s := []byte("a,b,c,d")
for part := range bytes.SplitSeq(s, []byte(",")) {
fmt.Printf("%q\n", part)
}
}
Output: "a" "b" "c" "d"
func Title
deprecated
TitleはUTF-8でエンコードされたバイト列sをUnicodeの文字として扱い、単語の先頭にあるすべての文字をタイトルケースにマッピングしたコピーを返します。
Deprecated: Titleが単語の境界を処理する際、Unicodeの句読点を適切に扱えません。golang.org/x/text/casesを代わりに使用してください。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
fmt.Printf("%s", bytes.Title([]byte("her royal highness")))
}
Output: Her Royal Highness
func ToLower ¶
ToLowerは、すべてのUnicodeの文字を小文字にマッピングしたバイトスライスsのコピーを返します。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
fmt.Printf("%s", bytes.ToLower([]byte("Gopher")))
}
Output: gopher
func ToLowerSpecial ¶
func ToLowerSpecial(c unicode.SpecialCase, s []byte) []byte
ToLowerSpecialはUTF-8エンコードされたバイト列sを扱い、ユニコードの文字をすべて小文字に変換し、特殊なケースのルールを優先します。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
"github.com/shogo82148/std/unicode"
)
func main() {
str := []byte("AHOJ VÝVOJÁRİ GOLANG")
totitle := bytes.ToLowerSpecial(unicode.AzeriCase, str)
fmt.Println("Original : " + string(str))
fmt.Println("ToLower : " + string(totitle))
}
Output: Original : AHOJ VÝVOJÁRİ GOLANG ToLower : ahoj vývojári golang
func ToTitle ¶
ToTitleはsをUTF-8でエンコードされたバイト列として扱い、すべてのUnicodeの文字をタイトルケースにマップしたコピーを返します。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
fmt.Printf("%s\n", bytes.ToTitle([]byte("loud noises")))
fmt.Printf("%s\n", bytes.ToTitle([]byte("хлеб")))
}
Output: LOUD NOISES ХЛЕБ
func ToTitleSpecial ¶
func ToTitleSpecial(c unicode.SpecialCase, s []byte) []byte
ToTitleSpecialはUTF-8でエンコードされたバイト列としてsを扱い、すべてのUnicode文字をタイトルケースにマッピングしたコピーを返します。特殊なケースのルールに優先します。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
"github.com/shogo82148/std/unicode"
)
func main() {
str := []byte("ahoj vývojári golang")
totitle := bytes.ToTitleSpecial(unicode.AzeriCase, str)
fmt.Println("Original : " + string(str))
fmt.Println("ToTitle : " + string(totitle))
}
Output: Original : ahoj vývojári golang ToTitle : AHOJ VÝVOJÁRİ GOLANG
func ToUpper ¶
ToUpperは、すべてのUnicode文字を大文字に変換したバイトスライスsのコピーを返します。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
fmt.Printf("%s", bytes.ToUpper([]byte("Gopher")))
}
Output: GOPHER
func ToUpperSpecial ¶
func ToUpperSpecial(c unicode.SpecialCase, s []byte) []byte
ToUpperSpecialはsをUTF-8エンコードされたバイトとして扱い、すべてのUnicodeの文字をその大文字に変換したコピーを返します。特殊な大文字変換ルールを優先します。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
"github.com/shogo82148/std/unicode"
)
func main() {
str := []byte("ahoj vývojári golang")
totitle := bytes.ToUpperSpecial(unicode.AzeriCase, str)
fmt.Println("Original : " + string(str))
fmt.Println("ToUpper : " + string(totitle))
}
Output: Original : ahoj vývojári golang ToUpper : AHOJ VÝVOJÁRİ GOLANG
func ToValidUTF8 ¶ added in v1.13.0
ToValidUTF8は、sをUTF-8でエンコードされたバイトとして処理し、各バイトの連続が不正なUTF-8を表す場合に、置換バイト(空の場合もあります)で置き換えられたコピーを返します。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
fmt.Printf("%s\n", bytes.ToValidUTF8([]byte("abc"), []byte("\uFFFD")))
fmt.Printf("%s\n", bytes.ToValidUTF8([]byte("a\xffb\xC0\xAFc\xff"), []byte("")))
fmt.Printf("%s\n", bytes.ToValidUTF8([]byte("\xed\xa0\x80"), []byte("abc")))
}
Output: abc abc abc
func Trim ¶
Trimは、cutsetに含まれるすべての先頭と末尾のUTF-8エンコードされたコードポイントをスライスして、sのサブスライスを返します。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
fmt.Printf("[%q]", bytes.Trim([]byte(" !!! Achtung! Achtung! !!! "), "! "))
}
Output: ["Achtung! Achtung"]
func TrimFunc ¶
TrimFunc は、前方および後方のすべての先頭と末尾をスライスして、f(c) で指定された条件を満たすすべての UTF-8 エンコードされたコードポイント c を除去して、s のサブスライスを返します。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
"github.com/shogo82148/std/unicode"
)
func main() {
fmt.Println(string(bytes.TrimFunc([]byte("go-gopher!"), unicode.IsLetter)))
fmt.Println(string(bytes.TrimFunc([]byte("\"go-gopher!\""), unicode.IsLetter)))
fmt.Println(string(bytes.TrimFunc([]byte("go-gopher!"), unicode.IsPunct)))
fmt.Println(string(bytes.TrimFunc([]byte("1234go-gopher!567"), unicode.IsNumber)))
}
Output: -gopher! "go-gopher!" go-gopher go-gopher!
func TrimLeft ¶
TrimLeftは、cutsetに含まれるすべての先行するUTF-8エンコードされたコードポイントを除去することによって、sの一部のサブスライスを返します。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
fmt.Print(string(bytes.TrimLeft([]byte("453gopher8257"), "0123456789")))
}
Output: gopher8257
func TrimLeftFunc ¶
TrimLeftFuncはUTF-8でエンコードされたバイト列sを処理し、f(c)を満たすすべての先頭のUTF-8エンコードされたコードポイントcを除いたsのサブスライスを返します。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
"github.com/shogo82148/std/unicode"
)
func main() {
fmt.Println(string(bytes.TrimLeftFunc([]byte("go-gopher"), unicode.IsLetter)))
fmt.Println(string(bytes.TrimLeftFunc([]byte("go-gopher!"), unicode.IsPunct)))
fmt.Println(string(bytes.TrimLeftFunc([]byte("1234go-gopher!567"), unicode.IsNumber)))
}
Output: -gopher go-gopher! go-gopher!567
func TrimPrefix ¶ added in v1.1.0
TrimPrefixは、指定されたプレフィックス文字列を先頭から除去したsを返します。 sがプレフィックスで始まらない場合、sは変更されずに返されます。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
var b = []byte("Goodbye,, world!")
b = bytes.TrimPrefix(b, []byte("Goodbye,"))
b = bytes.TrimPrefix(b, []byte("See ya,"))
fmt.Printf("Hello%s", b)
}
Output: Hello, world!
func TrimRight ¶
TrimRightは、cutsetに含まれるすべての末尾のUTF-8エンコードされたコードポイントを取り除いて、sの一部をサブスライスとして返します。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
fmt.Print(string(bytes.TrimRight([]byte("453gopher8257"), "0123456789")))
}
Output: 453gopher
func TrimRightFunc ¶
TrimRightFuncは、末尾にあるすべてのトレイリングUTF-8エンコードされたコードポイントcをスライスして、f(c)を満たすものを取り除いたsの部分スライスを返します。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
"github.com/shogo82148/std/unicode"
)
func main() {
fmt.Println(string(bytes.TrimRightFunc([]byte("go-gopher"), unicode.IsLetter)))
fmt.Println(string(bytes.TrimRightFunc([]byte("go-gopher!"), unicode.IsPunct)))
fmt.Println(string(bytes.TrimRightFunc([]byte("1234go-gopher!567"), unicode.IsNumber)))
}
Output: go- go-gopher 1234go-gopher!
func TrimSpace ¶
TrimSpaceは、Unicodeで定義されたように、sの先頭と末尾のすべての空白を取り除いた部分列を返します。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
fmt.Printf("%s", bytes.TrimSpace([]byte(" \t\n a lone gopher \n\t\r\n")))
}
Output: a lone gopher
func TrimSuffix ¶ added in v1.1.0
TrimSuffixは、指定された末尾の接尾辞文字列を除いたsを返します。 もしsが接尾辞で終わっていない場合はsは変更されずにそのまま返されます。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/os"
)
func main() {
var b = []byte("Hello, goodbye, etc!")
b = bytes.TrimSuffix(b, []byte("goodbye, etc!"))
b = bytes.TrimSuffix(b, []byte("gopher"))
b = append(b, bytes.TrimSuffix([]byte("world!"), []byte("x!"))...)
os.Stdout.Write(b)
}
Output: Hello, world!
Types ¶
type Buffer ¶
type Buffer struct {
// contains filtered or unexported fields
}
Bufferはバイトの可変サイズのバッファであり、 Buffer.Read と Buffer.Write のメソッドを持っています。 Bufferのゼロ値は、使い-readyになった空のバッファです。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
"github.com/shogo82148/std/os"
)
func main() {
var b bytes.Buffer // A Buffer needs no initialization.
b.Write([]byte("Hello "))
fmt.Fprintf(&b, "world!")
b.WriteTo(os.Stdout)
}
Output: Hello world!
Example (Reader) ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/encoding/base64"
"github.com/shogo82148/std/io"
"github.com/shogo82148/std/os"
)
func main() {
// A Buffer can turn a string or a []byte into an io.Reader.
buf := bytes.NewBufferString("R29waGVycyBydWxlIQ==")
dec := base64.NewDecoder(base64.StdEncoding, buf)
io.Copy(os.Stdout, dec)
}
Output: Gophers rule!
func NewBuffer ¶
NewBufferは、bufを初期コンテンツとして使用して新しい Buffer を作成および初期化します。 新しい Buffer は、bufを所有し、この呼び出しの後にbufを使用しないようにする必要があります。 NewBufferは、既存のデータを読むために Buffer を準備するためのものです。書き込み用の内部バッファの初期サイズを設定するためにも使用できます。そのためには、 bufは希望する容量を持つ必要がありますが、長さはゼロである必要があります。
ほとんどの場合、new(Buffer)(または単に Buffer 変数を宣言する)で Bufferを初期化するのに十分です。
func NewBufferString ¶
NewBufferStringは、文字列sを初期内容として使用して新しい Buffer を作成し、初期化します。既存の文字列を読むためのバッファを準備するために使用されます。
ほとんどの場合、new(Buffer)(または単に Buffer 変数を宣言する)でBufferを初期化するのに十分です。
func (*Buffer) AvailableBuffer ¶ added in v1.21.0
AvailableBufferはb.Available()の容量を持つ空のバッファを返します。 このバッファは追加され、直後の Buffer.Write 呼び出しに渡すことが想定されています。 バッファはbに対する次の書き込み操作までの間のみ有効です。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/os"
"github.com/shogo82148/std/strconv"
)
func main() {
var buf bytes.Buffer
for i := 0; i < 4; i++ {
b := buf.AvailableBuffer()
b = strconv.AppendInt(b, int64(i), 10)
b = append(b, ' ')
buf.Write(b)
}
os.Stdout.Write(buf.Bytes())
}
Output: 0 1 2 3
func (*Buffer) Bytes ¶
Bytesは、バッファの未読部分を保持する長さb.Len()のスライスを返します。 このスライスは、次のバッファの変更までしか有効ではありません(つまり、 Buffer.Read 、 Buffer.Write 、 Buffer.Reset 、または Buffer.Truncate などのメソッドの次の呼び出しまでのみ有効です)。 スライスは、次のバッファの変更まで少なくともバッファの内容をエイリアスしているため、 スライスへの直接の変更は将来の読み取り結果に影響を与えます。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/os"
)
func main() {
buf := bytes.Buffer{}
buf.Write([]byte{'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'})
os.Stdout.Write(buf.Bytes())
}
Output: hello world
func (*Buffer) Cap ¶ added in v1.5.0
Capはバッファの基礎となるバイトスライスの容量、つまりバッファのデータのために割り当てられた総スペースを返します。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
buf1 := bytes.NewBuffer(make([]byte, 10))
buf2 := bytes.NewBuffer(make([]byte, 0, 10))
fmt.Println(buf1.Cap())
fmt.Println(buf2.Cap())
}
Output: 10 10
func (*Buffer) Grow ¶ added in v1.1.0
Growは必要に応じてバッファの容量を増やし、残りのnバイトの空間を保証します。Grow(n)の後、バッファには少なくともnバイトを別の割り当てなしで書き込むことができます。 nが負数の場合、Growはパニックを引き起こします。 バッファを拡大できない場合、 ErrTooLarge でパニックを引き起こします。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
var b bytes.Buffer
b.Grow(64)
bb := b.Bytes()
b.Write([]byte("64 bytes or fewer"))
fmt.Printf("%q", bb[:b.Len()])
}
Output: "64 bytes or fewer"
func (*Buffer) Len ¶
Lenはバッファの未読部分のバイト数を返します。 b.Len() == len(b.Bytes())。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
var b bytes.Buffer
b.Grow(64)
b.Write([]byte("abcde"))
fmt.Printf("%d", b.Len())
}
Output: 5
func (*Buffer) Next ¶
Nextは、バッファから次のnバイトを含むスライスを返し、 バイトが Buffer.Read によって返された場合と同様にバッファを進めます。 バッファにnバイト未満のバイトがある場合、Nextはバッファ全体を返します。 スライスは、次の読み取りまたは書き込みメソッドの呼び出しまでの間のみ有効です。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
var b bytes.Buffer
b.Grow(64)
b.Write([]byte("abcde"))
fmt.Printf("%s\n", b.Next(2))
fmt.Printf("%s\n", b.Next(2))
fmt.Printf("%s", b.Next(2))
}
Output: ab cd e
func (*Buffer) Read ¶
Readは、バッファから次のlen(p)バイトを読み取るか、バッファが空になるまで読み取ります。返り値nは読み取られたバイト数です。バッファに返すデータがない場合、errは io.EOF です(len(p)がゼロの場合を除く);それ以外の場合、nilです。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
var b bytes.Buffer
b.Grow(64)
b.Write([]byte("abcde"))
rdbuf := make([]byte, 1)
n, err := b.Read(rdbuf)
if err != nil {
panic(err)
}
fmt.Println(n)
fmt.Println(b.String())
fmt.Println(string(rdbuf))
}
Output: 1 bcde a
func (*Buffer) ReadByte ¶
ReadByte はバッファから次のバイトを読み込んで返します。 バイトが利用できない場合は、エラー io.EOF を返します。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
var b bytes.Buffer
b.Grow(64)
b.Write([]byte("abcde"))
c, err := b.ReadByte()
if err != nil {
panic(err)
}
fmt.Println(c)
fmt.Println(b.String())
}
Output: 97 bcde
func (*Buffer) ReadBytes ¶
ReadBytesは入力の最初のdelimが現れるまで読み取り、 デリミタを含むデータを含むスライスを返します。 ReadBytesがデリミタを見つける前にエラーに遭遇した場合、 エラー自体(通常は io.EOF)とエラー前に読み取ったデータを返します。 返されたデータの末尾がdelimで終わっていない場合、 ReadBytesはerr != nilを返します。
func (*Buffer) ReadFrom ¶
ReadFromは、rからEOFまでデータを読み取り、バッファに追加していきます。必要に応じてバッファのサイズが拡大されます。返り値nは読み取られたバイト数です。読み取り中にio.EOF以外のエラーが発生した場合、それも返されます。バッファがあまりに大きくなると、ReadFromは ErrTooLarge でパニックを引き起こします。
func (*Buffer) ReadRune ¶
ReadRuneはバッファから次のUTF-8エンコードされた Unicodeコードポイントを読み取り、返します。 バイトが利用できない場合は、io.EOFというエラーが返されます。 バイトが不正なUTF-8エンコーディングの場合、1バイトを消費し、U+FFFD、1を返します。
func (*Buffer) ReadString ¶
ReadStringは入力の最初のデリミタが現れるまで読み取り、 デリミタを含むデータを含む文字列を返します。 ReadStringがデリミタを見つける前にエラーに遭遇する場合、 エラー自体(通常は io.EOF)とエラーが発生する前に読み取ったデータを返します。 ReadStringは、返されるデータがdelimで終わっていない場合、err!= nilを返します。
func (*Buffer) Reset ¶
func (b *Buffer) Reset()
Resetはバッファを空にリセットしますが、将来の書き込みのために基礎となるストレージは保持されます。 Resetは Buffer.Truncate(0)と同じです。
func (*Buffer) String ¶
Stringはバッファの未読部分の内容を文字列として返します。もし Buffer がnilポインタであれば、"<nil>"を返します。
より効率的に文字列を構築するには、strings.Builder 型を参照してください。
func (*Buffer) Truncate ¶
Truncateはバッファから最初のnバイト以外の未読データを削除し、同じ割り当てられたストレージを使用し続けます。 nが負数またはバッファの長さよりも大きい場合、パニックが発生します。
func (*Buffer) UnreadByte ¶
UnreadByteは、少なくとも1バイトを読み込んだ最後の成功した読み込み操作で返された最後のバイトを戻します。最後の読み込み以降に書き込みが発生した場合、最後の読み込みがエラーを返した場合、または読み込みが0バイトを読み込んだ場合、UnreadByteはエラーを返します。
func (*Buffer) UnreadRune ¶
UnreadRuneは Buffer.ReadRune によって返された最後のルーンを未読状態にします。 バッファ上の直近の読み込みや書き込み操作が Buffer.ReadRune の成功でない場合、UnreadRuneはエラーを返します。 (この点で、 Buffer.UnreadByte よりも厳格です。 Buffer.UnreadByte はすべての読み込み操作から最後のバイトを未読状態にします。)
func (*Buffer) Write ¶
Write はバッファーに p の内容を追加し、必要に応じてバッファーを拡張します。戻り値 n は p の長さであり、err は常に nil です。バッファーが大きすぎる場合、Write は ErrTooLarge とともにパニックを発生させます。
func (*Buffer) WriteByte ¶
WriteByteはバイトcをバッファに追加し、必要に応じてバッファを拡張します。 返されるエラーは常にnilですが、 bufio.Writer のWriteByteに合わせるために含まれています。 バッファが大きすぎる場合、WriteByteは ErrTooLarge でパニックします。
func (*Buffer) WriteRune ¶
WriteRuneはUnicodeコードポイントrのUTF-8エンコーディングをバッファに追加し、その長さと常にnilであるエラーを返します。エラーは常にnilですが、 bufio.Writer のWriteRuneとのマッチングのために含まれます。必要に応じてバッファは拡張されます。もしバッファがあまりにも大きくなった場合、WriteRuneは ErrTooLarge でパニックを起こします。
func (*Buffer) WriteString ¶
WriteStringは、必要に応じてバッファを拡張し、sの内容をバッファに追加します。戻り値nはsの長さであり、errは常にnilです。バッファが大きすぎる場合、WriteStringは ErrTooLarge とともにパニックを発生させます。
type Reader ¶
type Reader struct {
// contains filtered or unexported fields
}
Readerは io.Reader、io.ReaderAt、io.WriterTo、io.Seeker、io.ByteScanner、io.RuneScanner のインターフェースを実装し、 バイトスライスから読み取ります。 Buffer とは異なり、Readerは読み込み専用であり、シークをサポートします。 Readerのゼロ値は空のスライスのReaderのように動作します。
func (*Reader) Len ¶
Lenはスライスの未読部分のバイト数を返します。
Example ¶
package main
import (
"github.com/shogo82148/std/bytes"
"github.com/shogo82148/std/fmt"
)
func main() {
fmt.Println(bytes.NewReader([]byte("Hi!")).Len())
fmt.Println(bytes.NewReader([]byte("こんにちは!")).Len())
}
Output: 3 16
func (*Reader) ReadAt ¶
ReadAtは io.ReaderAt インターフェースを実装します。
func (*Reader) ReadByte ¶
ReadByteは io.ByteReader インターフェースを実装します。
func (*Reader) ReadRune ¶
ReadRuneは io.RuneReader インターフェースを実装します。
func (*Reader) Size ¶ added in v1.5.0
Size は元のバイトスライスの長さを返します。 Size は Reader.ReadAt を通じて読み取り可能なバイト数です。 Reader.Reset を除くすべてのメソッド呼び出しによって結果は変わりません。
func (*Reader) UnreadByte ¶
UnreadByteは io.ByteScanner インターフェースを実装する際に Reader.ReadByte を補完します。
func (*Reader) UnreadRune ¶
UnreadRuneは io.RuneScanner インターフェースの実装において Reader.ReadRune を補完します。