Documentation
¶
Overview ¶
Package bytes implements functions for the manipulation of byte slices. It is analogous to the facilities of the strings package.
Based on the bytes package, with fewer features.
Index ¶
- Constants
- Variables
- func Clone(a mem.Allocator, b []byte) []byte
- func Compare(a, b []byte) int
- func Contains(b, subslice []byte) bool
- func Count(s, sep []byte) int
- func Equal(a, b []byte) bool
- func HasPrefix(s, prefix []byte) bool
- func HasSuffix(s, suffix []byte) bool
- func Index(s, sep []byte) int
- func IndexByte(b []byte, c byte) int
- func Join(a mem.Allocator, s [][]byte, sep []byte) []byte
- func Map(a mem.Allocator, mapping RuneFunc, s []byte) []byte
- func Repeat(a mem.Allocator, b []byte, count int) []byte
- func Replace(a mem.Allocator, s, old, new []byte, n int) []byte
- func Runes(a mem.Allocator, s []byte) []rune
- func Split(a mem.Allocator, s, sep []byte) [][]byte
- func SplitN(a mem.Allocator, s, sep []byte, n int) [][]byte
- func String(a mem.Allocator, s []byte) string
- func ToLower(a mem.Allocator, s []byte) []byte
- func ToUpper(a mem.Allocator, s []byte) []byte
- func Trim(s []byte, cutset string) []byte
- func TrimFunc(s []byte, f RunePredicate) []byte
- func TrimLeft(s []byte, cutset string) []byte
- func TrimPrefix(s, prefix []byte) []byte
- func TrimRight(s []byte, cutset string) []byte
- func TrimSpace(s []byte) []byte
- func TrimSuffix(s, suffix []byte) []byte
- type Buffer
- func (b *Buffer) Available() int
- func (b *Buffer) Bytes() []byte
- func (b *Buffer) Cap() int
- func (b *Buffer) Free()
- func (b *Buffer) Grow(n int)
- func (b *Buffer) Len() int
- func (b *Buffer) Next(n int) []byte
- func (b *Buffer) Peek(n int) ([]byte, error)
- func (b *Buffer) Read(p []byte) (int, error)
- func (b *Buffer) ReadByte() (byte, error)
- func (b *Buffer) ReadBytes(delim byte) ([]byte, error)
- func (b *Buffer) ReadFrom(r io.Reader) (int64, error)
- func (b *Buffer) ReadRune() io.RuneSizeResult
- func (b *Buffer) ReadString(delim byte) (string, error)
- func (b *Buffer) Reset()
- func (b *Buffer) String() string
- func (b *Buffer) Write(p []byte) (int, error)
- func (b *Buffer) WriteByte(c byte) error
- func (b *Buffer) WriteRune(r rune) (int, error)
- func (b *Buffer) WriteString(s string) (int, error)
- func (b *Buffer) WriteTo(w io.Writer) (int64, error)
- type CutResult
- type Reader
- func (r *Reader) Len() int
- func (r *Reader) Read(b []byte) (int, error)
- func (r *Reader) ReadAt(b []byte, off int64) (int, error)
- func (r *Reader) ReadByte() (byte, error)
- func (r *Reader) ReadRune() io.RuneSizeResult
- 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) (int64, error)
- type RuneFunc
- type RunePredicate
Examples ¶
- Buffer
- Buffer (Reader)
- Buffer.Bytes
- Buffer.Cap
- Buffer.Grow
- Buffer.Len
- Buffer.Next
- Buffer.Read
- Buffer.ReadByte
- Clone
- Compare
- Compare (Search)
- Contains
- Count
- Cut
- Equal
- HasPrefix
- HasSuffix
- Index
- IndexByte
- Join
- Map
- Reader.Len
- Replace
- Runes
- Split
- SplitN
- ToLower
- ToUpper
- Trim
- TrimFunc
- TrimLeft
- TrimPrefix
- TrimRight
- TrimSpace
- TrimSuffix
Constants ¶
const MinRead = 512
MinRead is the minimum slice size passed to a Buffer.Read call by Buffer.ReadFrom. As long as the Buffer has at least MinRead bytes beyond what is required to hold the contents of r, Buffer.ReadFrom will not grow the underlying buffer.
Variables ¶
var ErrNegativeGrow = errors.New("bytes: negative grow")
ErrNegativeGrow means that a Buffer.Grow call was given a negative count.
Functions ¶
func Clone ¶
Clone returns a copy of b[:len(b)]. If the allocator is nil, uses the system allocator. The returned slice is allocated; the caller owns it.
Example ¶
package main
import (
"solod.dev/so/bytes"
"solod.dev/so/fmt"
)
func main() {
b := []byte("abc")
clone := bytes.Clone(nil, 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 returns an integer comparing two byte slices lexicographically. The result will be 0 if a == b, -1 if a < b, and +1 if a > b. A nil argument is equivalent to an empty slice.
Example ¶
package main
import (
"solod.dev/so/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
}
}
Output:
Example (Search) ¶
package main
import (
"slices"
"solod.dev/so/bytes"
)
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!
}
}
Output:
func Contains ¶
Contains reports whether subslice is within b.
Example ¶
package main
import (
"solod.dev/so/bytes"
"solod.dev/so/fmt"
)
func main() {
fmt.Printf("%t\n", bytes.Contains([]byte("seafood"), []byte("foo")))
fmt.Printf("%t\n", bytes.Contains([]byte("seafood"), []byte("bar")))
fmt.Printf("%t\n", bytes.Contains([]byte("seafood"), []byte("")))
fmt.Printf("%t\n", bytes.Contains([]byte(""), []byte("")))
}
Output: true false true true
func Count ¶
Count counts the number of non-overlapping instances of sep in s. If sep is an empty slice, Count returns 1 + the number of UTF-8-encoded code points in s.
Example ¶
package main
import (
"solod.dev/so/bytes"
"solod.dev/so/fmt"
)
func main() {
fmt.Printf("%d\n", bytes.Count([]byte("cheese"), []byte("e")))
fmt.Printf("%d\n", bytes.Count([]byte("five"), []byte(""))) // before & after each rune
}
Output: 3 5
func Equal ¶
Equal reports whether a and b are the same length and contain the same bytes. A nil argument is equivalent to an empty slice.
Example ¶
package main
import (
"solod.dev/so/bytes"
"solod.dev/so/fmt"
)
func main() {
fmt.Printf("%t\n", bytes.Equal([]byte("Go"), []byte("Go")))
fmt.Printf("%t\n", bytes.Equal([]byte("Go"), []byte("C++")))
}
Output: true false
func HasPrefix ¶
HasPrefix reports whether the byte slice s begins with prefix.
Example ¶
package main
import (
"solod.dev/so/bytes"
"solod.dev/so/fmt"
)
func main() {
fmt.Printf("%t\n", bytes.HasPrefix([]byte("Gopher"), []byte("Go")))
fmt.Printf("%t\n", bytes.HasPrefix([]byte("Gopher"), []byte("C")))
fmt.Printf("%t\n", bytes.HasPrefix([]byte("Gopher"), []byte("")))
}
Output: true false true
func HasSuffix ¶
HasSuffix reports whether the byte slice s ends with suffix.
Example ¶
package main
import (
"solod.dev/so/bytes"
"solod.dev/so/fmt"
)
func main() {
fmt.Printf("%t\n", bytes.HasSuffix([]byte("Amigo"), []byte("go")))
fmt.Printf("%t\n", bytes.HasSuffix([]byte("Amigo"), []byte("O")))
fmt.Printf("%t\n", bytes.HasSuffix([]byte("Amigo"), []byte("Ami")))
fmt.Printf("%t\n", bytes.HasSuffix([]byte("Amigo"), []byte("")))
}
Output: true false false true
func Index ¶
Index returns the index of the first instance of sep in s, or -1 if sep is not present in s.
Example ¶
package main
import (
"solod.dev/so/bytes"
"solod.dev/so/fmt"
)
func main() {
fmt.Printf("%d\n", bytes.Index([]byte("chicken"), []byte("ken")))
fmt.Printf("%d\n", bytes.Index([]byte("chicken"), []byte("dmr")))
}
Output: 4 -1
func IndexByte ¶
IndexByte returns the index of the first instance of c in b, or -1 if c is not present in b.
Example ¶
package main
import (
"solod.dev/so/bytes"
"solod.dev/so/fmt"
)
func main() {
fmt.Printf("%d\n", bytes.IndexByte([]byte("chicken"), byte('k')))
fmt.Printf("%d\n", bytes.IndexByte([]byte("chicken"), byte('g')))
}
Output: 4 -1
func Join ¶
Join concatenates the elements of s to create a new byte slice. The separator sep is placed between elements in the resulting slice. Panics if the result is too large to allocate.
If the allocator is nil, uses the system allocator. The returned slice is allocated; the caller owns it.
Example ¶
package main
import (
"solod.dev/so/bytes"
"solod.dev/so/fmt"
)
func main() {
s := [][]byte{[]byte("foo"), []byte("bar"), []byte("baz")}
fmt.Printf("%s", bytes.Join(nil, s, []byte(", ")))
}
Output: foo, bar, baz
func Map ¶
Map returns a copy of the byte slice s with all its characters modified according to the mapping function. If mapping returns a negative value, the character is dropped from the byte slice with no replacement. The characters in s and the output are interpreted as UTF-8-encoded code points.
If the allocator is nil, uses the system allocator. The returned slice is allocated; the caller owns it.
Example ¶
package main
import (
"solod.dev/so/bytes"
"solod.dev/so/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(nil, rot13, []byte("'Twas brillig and the slithy gopher...")))
}
Output: 'Gjnf oevyyvt naq gur fyvgul tbcure...
func Repeat ¶
Repeat returns a new byte slice consisting of count copies of b. It panics if count is negative or if the result of (len(b) * count) overflows.
If the allocator is nil, uses the system allocator. The returned slice is allocated; the caller owns it.
func Replace ¶
Replace returns a copy of the slice s with the first n non-overlapping instances of old replaced by new. If old is empty, it matches at the beginning of the slice and after each UTF-8 sequence, yielding up to k+1 replacements for a k-rune slice. If n < 0, there is no limit on the number of replacements.
If the allocator is nil, uses the system allocator. The returned slice is allocated; the caller owns it.
Example ¶
package main
import (
"solod.dev/so/bytes"
"solod.dev/so/fmt"
)
func main() {
old := []byte("oink oink oink")
fmt.Printf("%s\n", bytes.Replace(nil, old, []byte("k"), []byte("ky"), 2))
fmt.Printf("%s\n", bytes.Replace(nil, old, []byte("oink"), []byte("moo"), -1))
}
Output: oinky oinky oink moo moo moo
func Runes ¶
Runes interprets s as a sequence of UTF-8-encoded code points. It returns a slice of runes (Unicode code points) equivalent to s.
If the allocator is nil, uses the system allocator. The returned slice is allocated; the caller owns it.
Example ¶
package main
import (
"solod.dev/so/bytes"
"solod.dev/so/fmt"
)
func main() {
rs := bytes.Runes(nil, []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 slices s into all subslices separated by sep and returns a slice of the subslices between those separators. If sep is empty, Split splits after each UTF-8 sequence. It is equivalent to SplitN with a count of -1.
To split around the first instance of a separator, see Cut.
If the allocator is nil, uses the system allocator. The returned slice is allocated; the caller owns it. The subslices in the returned slice are views into the original slice s.
Example ¶
package main
import (
"solod.dev/so/bytes"
"solod.dev/so/fmt"
)
func main() {
fmt.Printf("%q\n", bytes.Split(nil, []byte("a,b,c"), []byte(",")))
fmt.Printf("%q\n", bytes.Split(nil, []byte("a man a plan a canal panama"), []byte("a ")))
fmt.Printf("%q\n", bytes.Split(nil, []byte(" xyz "), []byte("")))
fmt.Printf("%q\n", bytes.Split(nil, []byte(""), []byte("Bernardo O'Higgins")))
}
Output: ["a" "b" "c"] ["" "man " "plan " "canal panama"] [" " "x" "y" "z" " "] [""]
func SplitN ¶
SplitN slices s into subslices separated by sep and returns a slice of the subslices between those separators. If sep is empty, SplitN splits after each UTF-8 sequence. The count determines the number of subslices to return:
- n > 0: at most n subslices; the last subslice will be the unsplit remainder;
- n == 0: the result is nil (zero subslices);
- n < 0: all subslices.
To split around the first instance of a separator, see Cut.
If the allocator is nil, uses the system allocator. The returned slice is allocated; the caller owns it. The subslices in the returned slice are views into the original slice s.
Example ¶
package main
import (
"solod.dev/so/bytes"
"solod.dev/so/fmt"
)
func main() {
fmt.Printf("%q\n", bytes.SplitN(nil, []byte("a,b,c"), []byte(","), 2))
z := bytes.SplitN(nil, []byte("a,b,c"), []byte(","), 0)
fmt.Printf("%q (nil = %v)\n", z, z == nil)
}
Output: ["a" "b,c"] [] (nil = false)
func String ¶
String creates a string from a byte slice. If the allocator is nil, uses the system allocator. The returned string is allocated; the caller owns it.
func ToLower ¶
ToLower returns a copy of the byte slice s with all Unicode letters mapped to their lower case.
If the allocator is nil, uses the system allocator. The returned slice is allocated; the caller owns it.
Example ¶
package main
import (
"solod.dev/so/bytes"
"solod.dev/so/fmt"
)
func main() {
fmt.Printf("%s", bytes.ToLower(nil, []byte("Gopher")))
}
Output: gopher
func ToUpper ¶
ToUpper returns a copy of the byte slice s with all Unicode letters mapped to their upper case.
If the allocator is nil, uses the system allocator. The returned slice is allocated; the caller owns it.
Example ¶
package main
import (
"solod.dev/so/bytes"
"solod.dev/so/fmt"
)
func main() {
fmt.Printf("%s", bytes.ToUpper(nil, []byte("Gopher")))
}
Output: GOPHER
func Trim ¶
Trim returns a subslice of s by slicing off all leading and trailing UTF-8-encoded code points contained in cutset.
Example ¶
package main
import (
"solod.dev/so/bytes"
"solod.dev/so/fmt"
)
func main() {
fmt.Printf("[%q]", bytes.Trim([]byte(" !!! Achtung! Achtung! !!! "), "! "))
}
Output: ["Achtung! Achtung"]
func TrimFunc ¶
func TrimFunc(s []byte, f RunePredicate) []byte
TrimFunc returns a subslice of s by slicing off all leading and trailing UTF-8-encoded code points c that satisfy f(c).
Example ¶
package main
import (
"solod.dev/so/bytes"
"solod.dev/so/fmt"
"solod.dev/so/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("1234go-gopher!567"), unicode.IsDigit)))
}
Output: -gopher! "go-gopher!" go-gopher!
func TrimLeft ¶
TrimLeft returns a subslice of s by slicing off all leading UTF-8-encoded code points contained in cutset.
Example ¶
package main
import (
"solod.dev/so/bytes"
"solod.dev/so/fmt"
)
func main() {
fmt.Print(string(bytes.TrimLeft([]byte("453gopher8257"), "0123456789")))
}
Output: gopher8257
func TrimPrefix ¶
TrimPrefix returns s without the provided leading prefix string. If s doesn't start with prefix, s is returned unchanged.
Example ¶
package main
import (
"solod.dev/so/bytes"
"solod.dev/so/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 returns a subslice of s by slicing off all trailing UTF-8-encoded code points that are contained in cutset.
Example ¶
package main
import (
"solod.dev/so/bytes"
"solod.dev/so/fmt"
)
func main() {
fmt.Print(string(bytes.TrimRight([]byte("453gopher8257"), "0123456789")))
}
Output: 453gopher
func TrimSpace ¶
TrimSpace returns a subslice of s by slicing off all leading and trailing white space, as defined by Unicode.
Example ¶
package main
import (
"solod.dev/so/bytes"
"solod.dev/so/fmt"
)
func main() {
fmt.Printf("%s", bytes.TrimSpace([]byte(" \t\n a lone gopher \n\t\r\n")))
}
Output: a lone gopher
func TrimSuffix ¶
TrimSuffix returns s without the provided trailing suffix string. If s doesn't end with suffix, s is returned unchanged.
Example ¶
package main
import (
"os"
"solod.dev/so/bytes"
)
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
}
A Buffer is a variable-sized buffer of bytes with Buffer.Read and Buffer.Write methods. The zero value for Buffer is an empty buffer ready to use (with default allocator). A Buffer grows as needed when writing data, using the provided allocator. The caller is responsible for freeing the buffer's resources with Buffer.Free when done using it.
Example ¶
package main
import (
"os"
"solod.dev/so/bytes"
"solod.dev/so/fmt"
)
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 (
"encoding/base64"
"os"
"solod.dev/so/bytes"
"solod.dev/so/io"
)
func main() {
// A Buffer can turn a string or a []byte into an io.Reader.
buf := bytes.NewBufferString(nil, "R29waGVycyBydWxlIQ==")
dec := base64.NewDecoder(base64.StdEncoding, &buf)
io.Copy(os.Stdout, dec)
}
Output: Gophers rule!
func NewBuffer ¶
NewBuffer creates and initializes a new Buffer using buf as its initial contents. The new Buffer takes ownership of buf, and the caller should not use buf after this call. NewBuffer is intended to prepare a Buffer to read existing data. It can also be used to set the initial size of the internal buffer for writing. To do that, buf should have the desired capacity but a length of zero.
If buf was allocated with an allocator, the same allocator must be passed to NewBuffer so that Buffer.Free can release it correctly. Do not call Buffer.Free if buf was not heap-allocated.
Do not provide a stack-allocated buf if you intend to write to the buffer, as the buffer may need to grow and reallocate, which would cause free() on a stack pointer. Only use heap-allocated slices in this case.
If the allocator is nil, uses the system allocator.
func NewBufferString ¶
NewBufferString creates and initializes a new Buffer using string s as its initial contents. It is intended to prepare a buffer to read an existing string.
If s was allocated with an allocator, the same allocator must be passed to NewBuffer so that Buffer.Free can release it correctly. Do not call Buffer.Free if s was not heap-allocated.
Do not provide a stack-allocated s if you intend to write to the buffer, as the buffer may need to grow and reallocate, which would cause free() on a stack pointer. Only use heap-allocated strings in this case.
If the allocator is nil, uses the system allocator.
func (*Buffer) Bytes ¶
Bytes returns a slice of length b.Len() holding the unread portion of the buffer. The slice is valid for use only until the next buffer modification (that is, only until the next call to a method like Buffer.Read, Buffer.Write, Buffer.Reset. The slice aliases the buffer content at least until the next buffer modification, so immediate changes to the slice will affect the result of future reads.
Example ¶
package main
import (
"os"
"solod.dev/so/bytes"
)
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 ¶
Cap returns the capacity of the buffer's underlying byte slice, that is, the total space allocated for the buffer's data.
Example ¶
package main
import (
"solod.dev/so/bytes"
"solod.dev/so/fmt"
)
func main() {
buf1 := bytes.NewBuffer(nil, make([]byte, 10))
buf2 := bytes.NewBuffer(nil, make([]byte, 0, 10))
fmt.Printf("%d\n", buf1.Cap())
fmt.Printf("%d\n", buf2.Cap())
}
Output: 10 10
func (*Buffer) Free ¶
func (b *Buffer) Free()
Free frees the internal buffer and resets the buffer. After Free, the buffer can be reused with new writes.
func (*Buffer) Grow ¶
Grow grows the buffer's capacity, if necessary, to guarantee space for another n bytes. After Grow(n), at least n bytes can be written to the buffer without another allocation. Panics if n is negative or if the buffer cannot grow.
Example ¶
package main
import (
"solod.dev/so/bytes"
"solod.dev/so/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 returns the number of bytes of the unread portion of the buffer; b.Len() == len(b.Bytes()).
Example ¶
package main
import (
"solod.dev/so/bytes"
"solod.dev/so/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 returns a slice containing the next n bytes from the buffer, advancing the buffer as if the bytes had been returned by Buffer.Read. If there are fewer than n bytes in the buffer, Next returns the entire buffer. The slice is only valid until the next call to a read or write method.
Example ¶
package main
import (
"solod.dev/so/bytes"
"solod.dev/so/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) Peek ¶
Peek returns the next n bytes without advancing the buffer. If Peek returns fewer than n bytes, it also returns io.EOF. The slice is only valid until the next call to a read or write method. The slice aliases the buffer content at least until the next buffer modification, so immediate changes to the slice will affect the result of future reads.
func (*Buffer) Read ¶
Read reads the next len(p) bytes from the buffer or until the buffer is drained. The return value n is the number of bytes read. If the buffer has no data to return, err is io.EOF (unless len(p) is zero); otherwise it is nil.
Example ¶
package main
import (
"solod.dev/so/bytes"
"solod.dev/so/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.Printf("%d\n", n)
fmt.Println(b.String())
fmt.Println(string(rdbuf))
}
Output: 1 bcde a
func (*Buffer) ReadByte ¶
ReadByte reads and returns the next byte from the buffer. If no byte is available, it returns error io.EOF.
Example ¶
package main
import (
"solod.dev/so/bytes"
"solod.dev/so/fmt"
)
func main() {
var b bytes.Buffer
b.Grow(64)
b.Write([]byte("abcde"))
c, err := b.ReadByte()
if err != nil {
panic(err)
}
fmt.Printf("%d\n", c)
fmt.Println(b.String())
}
Output: 97 bcde
func (*Buffer) ReadBytes ¶
ReadBytes reads until the first occurrence of delim in the input, returning a slice containing the data up to and including the delimiter. If ReadBytes encounters an error before finding a delimiter, it returns the data read before the error and the error itself (often io.EOF). ReadBytes returns err != nil if and only if the returned data does not end in delim.
The returned slice is allocated; the caller owns it.
func (*Buffer) ReadFrom ¶
ReadFrom reads data from r until EOF and appends it to the buffer, growing the buffer as needed. The return value n is the number of bytes read. Any error except io.EOF encountered during the read is also returned. Panics if the buffer becomes too large.
func (*Buffer) ReadRune ¶
func (b *Buffer) ReadRune() io.RuneSizeResult
ReadRune reads and returns the next UTF-8-encoded Unicode code point from the buffer. If no bytes are available, the error returned is io.EOF. If the bytes are an erroneous UTF-8 encoding, it consumes one byte and returns U+FFFD, 1.
func (*Buffer) ReadString ¶
ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter. If ReadString encounters an error before finding a delimiter, it returns the data read before the error and the error itself (often io.EOF). ReadString returns err != nil if and only if the returned data does not end in delim.
The returned string is allocated; the caller owns it.
func (*Buffer) Reset ¶
func (b *Buffer) Reset()
Reset resets the buffer to be empty, but it retains the underlying storage for use by future writes.
func (*Buffer) String ¶
String returns the contents of the unread portion of the buffer as a string. If the Buffer is a nil pointer, it returns "<nil>". The string is valid for use only until the next buffer modification.
To build strings more efficiently, see the strings.Builder type.
func (*Buffer) Write ¶
Write appends the contents of p to the buffer, growing the buffer as needed. The return value n is the length of p; err is always nil. Panics if the buffer becomes too large.
func (*Buffer) WriteByte ¶
WriteByte appends the byte c to the buffer, growing the buffer as needed. The returned error is always nil, but is included to match bufio.Writer's WriteByte. Panics if the buffer becomes too large.
func (*Buffer) WriteRune ¶
WriteRune appends the UTF-8 encoding of Unicode code point r to the buffer, returning its length and an error, which is always nil but is included to match bufio.Writer's WriteRune. The buffer is grown as needed; if it becomes too large, WriteRune will panic.
func (*Buffer) WriteString ¶
WriteString appends the contents of s to the buffer, growing the buffer as needed. The return value n is the length of s; err is always nil. Panics if the buffer becomes too large.
func (*Buffer) WriteTo ¶
WriteTo writes data to w until the buffer is drained or an error occurs. The return value n is the number of bytes written; it always fits into an int, but it is int64 to match the io.WriterTo interface. Any error encountered during the write is also returned.
type CutResult ¶
CutResult is the result of a Cut operation.
func Cut ¶
Cut slices s around the first instance of sep, returning the text before and after sep. The found result reports whether sep appears in s. If sep does not appear in s, cut returns s, nil, false.
Cut returns slices of the original slice s, not copies.
Example ¶
package main
import (
"solod.dev/so/bytes"
"solod.dev/so/fmt"
)
func main() {
show := func(s, sep string) {
res := bytes.Cut([]byte(s), []byte(sep))
fmt.Printf("Cut(%q, %q) = %q, %q, %v\n", s, sep, res.Before, res.After, res.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
type Reader ¶
type Reader struct {
// contains filtered or unexported fields
}
A Reader implements the io.Reader, io.ReaderAt, io.WriterTo, io.Seeker, io.ByteScanner, and io.RuneScanner interfaces by reading from a byte slice. Unlike a Buffer, a Reader is read-only and supports seeking. The zero value for Reader operates like a Reader of an empty slice.
func (*Reader) Len ¶
Len returns the number of bytes of the unread portion of the slice.
Example ¶
package main
import (
"solod.dev/so/bytes"
"solod.dev/so/fmt"
)
func main() {
r1 := bytes.NewReader([]byte("Hi!"))
fmt.Printf("%d\n", r1.Len())
r2 := bytes.NewReader([]byte("こんにちは!"))
fmt.Printf("%d\n", r2.Len())
}
Output: 3 16
func (*Reader) ReadAt ¶
ReadAt implements the io.ReaderAt interface.
func (*Reader) ReadByte ¶
ReadByte implements the io.ByteReader interface.
func (*Reader) ReadRune ¶
func (r *Reader) ReadRune() io.RuneSizeResult
ReadRune implements the io.RuneReader interface.
func (*Reader) Size ¶
Size returns the original length of the underlying byte slice. Size is the number of bytes available for reading via Reader.ReadAt. The result is unaffected by any method calls except Reader.Reset.
func (*Reader) UnreadByte ¶
UnreadByte complements Reader.ReadByte in implementing the io.ByteScanner interface.
func (*Reader) UnreadRune ¶
UnreadRune complements Reader.ReadRune in implementing the io.RuneScanner interface.
type RuneFunc ¶
RuneFunc maps a rune to another rune. If mapping returns a negative value, the rune is dropped from the result.
type RunePredicate ¶
RunePredicate reports whether the rune satisfies a condition.