amuz.es/src/infra/goutils@v0.1.3/buf/bytebuf.go (about)

     1  package buf
     2  
     3  import (
     4  	"unicode/utf8"
     5  	"unsafe"
     6  )
     7  
     8  // ByteBuffer provides byte buffer, which can be used with fasthttp API
     9  // in order to minimize memory allocations.
    10  //
    11  // ByteBuffer may be used with functions appending data to the given []byte
    12  // slice. See example code for details.
    13  //
    14  // Use AcquireByteBuffer for obtaining an empty byte buffer.
    15  type ByteBuffer struct {
    16  	// B is a byte buffer to use in append-like workloads.
    17  	// See example code for details.
    18  	B []byte
    19  }
    20  
    21  
    22  func (b *ByteBuffer) WriteByte(c byte) error {
    23  	b.B = append(b.B, c)
    24  	return nil
    25  }
    26  
    27  // Write implements io.Writer - it appends p to ByteBuffer.B
    28  func (b *ByteBuffer) Write(p []byte) (int, error) {
    29  	b.B = append(b.B, p...)
    30  	return len(p), nil
    31  }
    32  
    33  // WriteString appends s to ByteBuffer.B
    34  func (b *ByteBuffer) WriteString(s string) (int, error) {
    35  	b.B = append(b.B, s...)
    36  	return len(s), nil
    37  }
    38  
    39  //(r rune) (n int, err error) {
    40  // WriteString appends s to ByteBuffer.B
    41  func (b *ByteBuffer) WriteRune(r rune) (n int, err error) {
    42  	if r < utf8.RuneSelf {
    43  		b.B = append(b.B, byte(r))
    44  		return 1, nil
    45  	}
    46  	curSize := len(b.B)
    47  	runCharBuf := b.B[curSize:curSize+utf8.UTFMax]
    48  	n = utf8.EncodeRune(runCharBuf, r)
    49  	b.B = b.B[:curSize+n]
    50  	return n, nil
    51  }
    52  
    53  // Set sets ByteBuffer.B to p
    54  func (b *ByteBuffer) Set(p []byte) {
    55  	b.B = append(b.B[:0], p...)
    56  }
    57  
    58  // SetString sets ByteBuffer.B to s
    59  func (b *ByteBuffer) SetString(s string) {
    60  	b.B = append(b.B[:0], s...)
    61  }
    62  
    63  // Reset makes ByteBuffer.B empty.
    64  func (b *ByteBuffer) Reset() {
    65  	b.B = b.B[:0]
    66  }
    67  
    68  // String returns the accumulated string.
    69  func (b *ByteBuffer) String() string {
    70  	return *(*string)(unsafe.Pointer(&b.B))
    71  }
    72  
    73  // Len returns the number of accumulated bytes; b.Len() == len(b.String()).
    74  func (b *ByteBuffer) Len() int { return len(b.B) }