github.com/observiq/carbon@v0.9.11-0.20200820160507-1b872e368a5e/operator/builtin/input/windows/buffer.go (about)

     1  // +build windows
     2  
     3  package windows
     4  
     5  import (
     6  	"bytes"
     7  	"fmt"
     8  
     9  	"golang.org/x/text/encoding/unicode"
    10  )
    11  
    12  // defaultBufferSize is the default size of the buffer.
    13  const defaultBufferSize = 16384
    14  
    15  // Buffer is a buffer of utf-16 bytes.
    16  type Buffer struct {
    17  	buffer []byte
    18  }
    19  
    20  // ReadBytes will read UTF-8 bytes from the buffer.
    21  func (b *Buffer) ReadBytes(offset uint32) ([]byte, error) {
    22  	utf16 := b.buffer[:offset]
    23  	utf8, err := unicode.UTF16(unicode.LittleEndian, unicode.UseBOM).NewDecoder().Bytes(utf16)
    24  	if err != nil {
    25  		return nil, fmt.Errorf("failed to convert buffer contents to utf8: %s", err)
    26  	}
    27  
    28  	return bytes.Trim(utf8, "\u0000"), nil
    29  }
    30  
    31  // ReadString will read a UTF-8 string from the buffer.
    32  func (b *Buffer) ReadString(offset uint32) (string, error) {
    33  	bytes, err := b.ReadBytes(offset)
    34  	if err != nil {
    35  		return "", err
    36  	}
    37  	return string(bytes), nil
    38  }
    39  
    40  // UpdateSize will update the size of the buffer.
    41  func (b *Buffer) UpdateSize(size uint32) {
    42  	b.buffer = make([]byte, size)
    43  }
    44  
    45  // Size will return the size of the buffer.
    46  func (b *Buffer) Size() uint32 {
    47  	return uint32(len(b.buffer))
    48  }
    49  
    50  // FirstByte will return a pointer to the first byte.
    51  func (b *Buffer) FirstByte() *byte {
    52  	return &b.buffer[0]
    53  }
    54  
    55  // NewBuffer creates a new buffer with the default buffer size
    56  func NewBuffer() Buffer {
    57  	return Buffer{
    58  		buffer: make([]byte, defaultBufferSize),
    59  	}
    60  }