bytes

package
v0.39.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 3, 2022 License: BSD-3-Clause Imports: 3 Imported by: 2

Documentation

Overview

Package bytes provide a library for working with byte or slice of bytes.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func AppendInt16

func AppendInt16(data []byte, v int16) []byte

AppendInt16 append an int16 value into slice of byte.

Example
for _, v := range []int16{math.MinInt16, 0xab, 0xabc, math.MaxInt16} {
	out := AppendInt16([]byte{}, v)
	fmt.Printf("%6d => %#04x => %#02v\n", v, v, out)
}
Output:

-32768 => -0x8000 => []byte{0x80, 0x00}
   171 => 0x00ab => []byte{0x00, 0xab}
  2748 => 0x0abc => []byte{0x0a, 0xbc}
 32767 => 0x7fff => []byte{0x7f, 0xff}

func AppendInt32

func AppendInt32(data []byte, v int32) []byte

AppendInt32 append an int32 value into slice of byte.

Example
for _, v := range []int32{math.MinInt32, 0xab, 0xabc, math.MaxInt32} {
	out := AppendInt32([]byte{}, v)
	fmt.Printf("%11d => %#x => %#v\n", v, v, out)
}
Output:

-2147483648 => -0x80000000 => []byte{0x80, 0x0, 0x0, 0x0}
        171 => 0xab => []byte{0x0, 0x0, 0x0, 0xab}
       2748 => 0xabc => []byte{0x0, 0x0, 0xa, 0xbc}
 2147483647 => 0x7fffffff => []byte{0x7f, 0xff, 0xff, 0xff}

func AppendUint16

func AppendUint16(data []byte, v uint16) []byte

AppendUint16 append an uint16 value into slice of byte.

Example
inputs := []uint16{0, 0xab, 0xabc, math.MaxInt16, math.MaxUint16}
for _, v := range inputs {
	out := AppendUint16([]byte{}, v)
	fmt.Printf("%5d => %#04x => %#02v\n", v, v, out)
}

v := inputs[4] + 1 // MaxUint16 + 1
out := AppendUint16([]byte{}, v)
fmt.Printf("%5d => %#04x => %#02v\n", v, v, out)
Output:

0 => 0x0000 => []byte{0x00, 0x00}
  171 => 0x00ab => []byte{0x00, 0xab}
 2748 => 0x0abc => []byte{0x0a, 0xbc}
32767 => 0x7fff => []byte{0x7f, 0xff}
65535 => 0xffff => []byte{0xff, 0xff}
    0 => 0x0000 => []byte{0x00, 0x00}

func AppendUint32

func AppendUint32(data []byte, v uint32) []byte

AppendUint32 append an uint32 value into slice of byte.

Example
inputs := []uint32{0, 0xab, 0xabc, math.MaxInt32, math.MaxUint32}
for _, v := range inputs {
	out := AppendUint32([]byte{}, v)
	fmt.Printf("%11d => %#x => %#v\n", v, v, out)
}

v := inputs[4] + 2 // MaxUint32 + 2
out := AppendUint32([]byte{}, v)
fmt.Printf("%11d => %#x => %#v\n", v, v, out)
Output:

0 => 0x0 => []byte{0x0, 0x0, 0x0, 0x0}
        171 => 0xab => []byte{0x0, 0x0, 0x0, 0xab}
       2748 => 0xabc => []byte{0x0, 0x0, 0xa, 0xbc}
 2147483647 => 0x7fffffff => []byte{0x7f, 0xff, 0xff, 0xff}
 4294967295 => 0xffffffff => []byte{0xff, 0xff, 0xff, 0xff}
          1 => 0x1 => []byte{0x0, 0x0, 0x0, 0x1}

func Concat added in v0.5.0

func Concat(args ...interface{}) (out []byte)

Concat merge one or more []byte or string in args into slice of byte. Any type that is not []byte or string in args will be ignored.

Example
fmt.Printf("%s\n", Concat())
fmt.Printf("%s\n", Concat([]byte{}))
fmt.Printf("%s\n", Concat([]byte{}, []byte("B")))
fmt.Printf("%s\n", Concat("with []int:", []int{1, 2}))
fmt.Printf("%s\n", Concat([]byte("bytes"), " and ", []byte("string")))
fmt.Printf("%s\n", Concat([]byte("A"), 1, []int{2}, []byte{}, []byte("C")))
Output:


B
with []int:
bytes and string
AC

func Copy

func Copy(src []byte) (dst []byte)

Copy slice of bytes from parameter.

Example
// Copying empty slice.
org := []byte{}
cp := Copy(org)
fmt.Printf("%d %q\n", len(cp), cp)

org = []byte("slice of life")
tmp := org
cp = Copy(org)
fmt.Printf("%d %q\n", len(cp), cp)
fmt.Printf("Original address == tmp address: %v\n", &org[0] == &tmp[0])
fmt.Printf("Original address == copy address: %v\n", &org[0] == &cp[0])
Output:

0 ""
13 "slice of life"
Original address == tmp address: true
Original address == copy address: false

func CutUntilToken

func CutUntilToken(text, token []byte, startAt int, checkEsc bool) (cut []byte, pos int, found bool)

CutUntilToken cut text until we found token.

If token found, it will return all bytes before token, position of byte after token, and true.

If no token found, it will return false.

If checkEsc is true, token that is prefixed with escaped character ('\') will be skipped, the escape character will be removed.

Example
text := []byte(`\\abc \def \deg`)

cut, pos, found := CutUntilToken(text, nil, 0, false)
fmt.Printf("'%s' %d %t\n", cut, pos, found)

cut, pos, found = CutUntilToken(text, []byte("def"), 0, false)
fmt.Printf("'%s' %d %t\n", cut, pos, found)

cut, pos, found = CutUntilToken(text, []byte("def"), 0, true)
fmt.Printf("'%s' %d %t\n", cut, pos, found)

cut, pos, found = CutUntilToken(text, []byte("ef"), -1, true)
fmt.Printf("'%s' %d %t\n", cut, pos, found)

cut, pos, found = CutUntilToken(text, []byte("hi"), 0, true)
fmt.Printf("'%s' %d %t\n", cut, pos, found)
Output:

'\\abc \def \deg' -1 false
'\\abc \' 10 true
'\abc def \deg' 15 false
'\abc \d' 10 true
'\abc \def \deg' 15 false

func EncloseRemove

func EncloseRemove(text, leftToken, rightToken []byte) (cut []byte, found bool)

EncloseRemove given a text, find the leftToken and rightToken and cut the content in between them and return it with status true. Keep doing it until no more leftToken and rightToken found.

If no leftToken or rightToken is found, it will return text as is and false.

Example
text := []byte(`[[ A ]]-[[ B ]] C`)

got, isCut := EncloseRemove(text, []byte("[["), []byte("]]"))
fmt.Printf("'%s' %t\n", got, isCut)

got, isCut = EncloseRemove(text, []byte("[["), []byte("}}"))
fmt.Printf("'%s' %t\n", got, isCut)

text = []byte(`// Copyright 2016-2018 "Shulhan <ms@kilabit.info>". All rights reserved.`)

got, isCut = EncloseRemove(text, []byte("<"), []byte(">"))
fmt.Printf("'%s' %t\n", got, isCut)

got, isCut = EncloseRemove(text, []byte(`"`), []byte(`"`))
fmt.Printf("'%s' %t\n", got, isCut)

got, isCut = EncloseRemove(text, []byte(`/`), []byte(`/`))
fmt.Printf("'%s' %t\n", got, isCut)

text = []byte(`/* TEST */`)

got, isCut = EncloseRemove(text, []byte(`/*`), []byte(`*/`))
fmt.Printf("'%s' %t\n", got, isCut)
Output:

'- C' true
'[[ A ]]-[[ B ]] C' false
'// Copyright 2016-2018 "Shulhan ". All rights reserved.' true
'// Copyright 2016-2018 . All rights reserved.' true
' Copyright 2016-2018 "Shulhan <ms@kilabit.info>". All rights reserved.' true
'' true

func EncloseToken

func EncloseToken(text, token, leftcap, rightcap []byte) (
	newtext []byte,
	found bool,
)

EncloseToken find "token" in "text" and enclose it with bytes from "leftcap" and "rightcap". If at least one token found, it will return modified text with true status. If no token is found, it will return the same text with false status.

Example
text := []byte(`// Copyright 2016-2018 "Shulhan <ms@kilabit.info>". All rights reserved.`)

got, isChanged := EncloseToken(text, []byte(`"`), []byte(`\`), []byte(`_`))
fmt.Printf("%t '%s'\n", isChanged, got)

got, isChanged = EncloseToken(text, []byte(`_`), []byte(`-`), []byte(`-`))
fmt.Printf("%t '%s'\n", isChanged, got)

got, isChanged = EncloseToken(text, []byte(`/`), []byte(`\`), nil)
fmt.Printf("%t '%s'\n", isChanged, got)

got, isChanged = EncloseToken(text, []byte(`<`), []byte(`<`), []byte(` `))
fmt.Printf("%t '%s'\n", isChanged, got)
Output:

true '// Copyright 2016-2018 \"_Shulhan <ms@kilabit.info>\"_. All rights reserved.'
false '// Copyright 2016-2018 "Shulhan <ms@kilabit.info>". All rights reserved.'
true '\/\/ Copyright 2016-2018 "Shulhan <ms@kilabit.info>". All rights reserved.'
true '// Copyright 2016-2018 "Shulhan << ms@kilabit.info>". All rights reserved.'

func InReplace

func InReplace(text, allowed []byte, c byte) []byte

InReplace replace any characters in "text" that is not in "allowed" with character "c". The replacement occur inside the "text" backing storage, which means the passed "text" will changes and returned.

Example
text := InReplace([]byte{}, []byte(ascii.LettersNumber), '_')
fmt.Printf("%q\n", text)

text = InReplace([]byte("/a/b/c"), []byte(ascii.LettersNumber), '_')
fmt.Printf("%q\n", text)

_ = InReplace(text, []byte(ascii.LettersNumber), '/')
fmt.Printf("%q\n", text)
Output:

""
"_a_b_c"
"/a/b/c"

func Indexes added in v0.10.1

func Indexes(text, token []byte) (idxs []int)

Indexes returns the index of the all instance of "token" in "text", or nil if no "token" found.

Example
fmt.Println(Indexes([]byte(""), []byte("moo")))
fmt.Println(Indexes([]byte("moo moomoo"), []byte{}))
fmt.Println(Indexes([]byte("moo moomoo"), []byte("moo")))
Output:

[]
[]
[0 4 7]

func IsTokenAt

func IsTokenAt(text, token []byte, p int) bool

IsTokenAt return true if `text` at index `p` match with `token`, otherwise it will return false. Empty token always return false.

Example
text := []byte("Hello, world")
tokenWorld := []byte("world")
tokenWorlds := []byte("worlds")
tokenEmpty := []byte{}

fmt.Printf("%t\n", IsTokenAt(text, tokenEmpty, 6))
fmt.Printf("%t\n", IsTokenAt(text, tokenWorld, -1))
fmt.Printf("%t\n", IsTokenAt(text, tokenWorld, 6))
fmt.Printf("%t\n", IsTokenAt(text, tokenWorld, 7))
fmt.Printf("%t\n", IsTokenAt(text, tokenWorld, 8))
fmt.Printf("%t\n", IsTokenAt(text, tokenWorlds, 8))
Output:

false
false
false
true
false
false

func MergeSpaces added in v0.16.0

func MergeSpaces(in []byte) (out []byte)

MergeSpaces convert sequences of white spaces into single space ' '.

Example
fmt.Printf("%s\n", MergeSpaces([]byte("")))
fmt.Printf("%s\n", MergeSpaces([]byte(" \t\v\r\n\r\n\fa \t\v\r\n\r\n\f")))
Output:


 a

func PrintHex

func PrintHex(title string, data []byte, col int)

PrintHex will print each byte in slice as hexadecimal value into N column length.

Example
title := "PrintHex"
data := []byte("Hello, world !")
PrintHex(title, data, 5)
Output:

PrintHex
   0 - 48 65 6C 6C 6F || H e l l o
   5 - 2C 20 77 6F 72 || , . w o r
  10 - 6C 64 20 21    || l d . !

func ReadHexByte

func ReadHexByte(data []byte, x int) (b byte, ok bool)

ReadHexByte read two hexadecimal characters from "data" start from index "x" and convert them to byte. It will return the byte and true if its read exactly two hexadecimal characters, otherwise it will return 0 and false.

Example
fmt.Println(ReadHexByte([]byte{}, 0))
fmt.Println(ReadHexByte([]byte("x0"), 0))
fmt.Println(ReadHexByte([]byte("00"), 0))
fmt.Println(ReadHexByte([]byte("01"), 0))
fmt.Println(ReadHexByte([]byte("10"), 0))
fmt.Println(ReadHexByte([]byte("1A"), 0))
fmt.Println(ReadHexByte([]byte("1a"), 0))
fmt.Println(ReadHexByte([]byte("1a"), -1))
Output:

0 false
0 false
0 true
1 true
16 true
26 true
26 true
0 false

func ReadInt16

func ReadInt16(data []byte, x uint) (v int16)

ReadInt16 read int16 value from "data" start at index "x". It will return 0 if "x" is out of range.

Example
fmt.Println(ReadInt16([]byte{0x01, 0x02, 0x03, 0x04}, 3)) // x is out of range.
fmt.Println(ReadInt16([]byte{0x01, 0x02, 0x03, 0x04}, 0)) // 0x0102
fmt.Println(ReadInt16([]byte{0x01, 0x02, 0xf0, 0x04}, 2)) // 0xf004
Output:

0
258
-4092

func ReadInt32

func ReadInt32(data []byte, x uint) (v int32)

ReadInt32 read int32 value from "data" start at index "x". It will return 0 if "x" is out of range.

Example
fmt.Println(ReadInt32([]byte{0x01, 0x02, 0x03, 0x04}, 1)) // x is out of range.
fmt.Println(ReadInt32([]byte{0x01, 0x02, 0x03, 0x04}, 0)) // 0x01020304
fmt.Println(ReadInt32([]byte{0xf1, 0x02, 0x03, 0x04}, 0)) // 0xf1020304
Output:

0
16909060
-251526396

func ReadUint16

func ReadUint16(data []byte, x uint) (v uint16)

ReadUint16 read uint16 value from "data" start at index "x". If x is out of range, it will return 0.

Example
fmt.Println(ReadUint16([]byte{0x01, 0x02, 0xf0, 0x04}, 3)) // x is out of range.
fmt.Println(ReadUint16([]byte{0x01, 0x02, 0xf0, 0x04}, 0)) // 0x0102
fmt.Println(ReadUint16([]byte{0x01, 0x02, 0xf0, 0x04}, 2)) // 0xf004
Output:

0
258
61444

func ReadUint32

func ReadUint32(data []byte, x uint) (v uint32)

ReadUint32 read uint32 value from "data" start at index "x". If x is out of range, it will return 0.

Example
fmt.Println(ReadUint32([]byte{0x01, 0x02, 0x03, 0x04}, 1)) // x is out of range.
fmt.Println(ReadUint32([]byte{0x01, 0x02, 0x03, 0x04}, 0)) // 0x01020304
fmt.Println(ReadUint32([]byte{0xf1, 0x02, 0x03, 0x04}, 0)) // 0xf1020304
Output:

0
16909060
4043440900

func SkipAfterToken

func SkipAfterToken(text, token []byte, startAt int, checkEsc bool) (int, bool)

SkipAfterToken skip all bytes until matched "token" is found and return the index after the token and boolean true.

If "checkEsc" is true, token that is prefixed with escaped character '\' will be considered as non-match token.

If no token found it will return -1 and boolean false.

Example
text := []byte(`abc \def ghi`)

fmt.Println(SkipAfterToken(text, []byte("def"), -1, false))
fmt.Println(SkipAfterToken(text, []byte("def"), 0, true))
fmt.Println(SkipAfterToken(text, []byte("deg"), 0, false))
fmt.Println(SkipAfterToken(text, []byte("deg"), 0, true))
fmt.Println(SkipAfterToken(text, []byte("ef"), 0, true))
fmt.Println(SkipAfterToken(text, []byte("hi"), 0, true))
Output:

8 true
-1 false
-1 false
-1 false
8 true
12 true

func SnippetByIndexes added in v0.10.1

func SnippetByIndexes(s []byte, indexes []int, sniplen int) (snippets [][]byte)

SnippetByIndexes take snippet in between of each index with minimum snippet length. The sniplen is the length before and after index, not the length of all snippet.

Example
s := []byte("// Copyright 2018, Shulhan <ms@kilabit.info>. All rights reserved.")
indexes := []int{3, 20, len(s) - 4}

snippets := SnippetByIndexes(s, indexes, 5)
for _, snip := range snippets {
	fmt.Printf("%s\n", snip)
}
Output:

// Copyr
18, Shulha
reserved.

func TokenFind

func TokenFind(text, token []byte, startat int) (at int)

TokenFind return the first index of matched token in text, start at custom index. If "startat" parameter is less than 0, then it will be set to 0. If token is empty or no token found it will return -1.

Example
text := []byte("// Copyright 2018, Shulhan <ms@kilabit.info>. All rights reserved.")

fmt.Println(TokenFind(text, []byte{}, 0))
fmt.Println(TokenFind(text, []byte("right"), -1))
fmt.Println(TokenFind(text, []byte("."), 0))
fmt.Println(TokenFind(text, []byte("."), 42))
fmt.Println(TokenFind(text, []byte("."), 48))
fmt.Println(TokenFind(text, []byte("d."), 0))
Output:

-1
7
38
44
65
64

func WordIndexes added in v0.10.1

func WordIndexes(s []byte, word []byte) (idxs []int)

WordIndexes returns the index of the all instance of word in s as long as word is separated by space or at the beginning or end of s.

Example
text := []byte("moo moomoo moo")

fmt.Println(WordIndexes(text, []byte("mo")))
fmt.Println(WordIndexes(text, []byte("moo")))
fmt.Println(WordIndexes(text, []byte("mooo")))
Output:

[]
[0 11]
[]

func WriteUint16

func WriteUint16(data []byte, x uint, v uint16)

WriteUint16 write uint16 value "v" into "data" start at position "x". If x is out range, the data will not change.

Example
data := []byte("Hello, world!")

var v uint16

v = 'h' << 8
v |= 'E'

WriteUint16(data, uint(len(data)-1), v) // Index out of range
fmt.Println(string(data))

WriteUint16(data, 0, v)
fmt.Println(string(data))
Output:

Hello, world!
hEllo, world!

func WriteUint32

func WriteUint32(data []byte, x uint, v uint32)

WriteUint32 write uint32 value into "data" start at position "x". If x is out range, the data will not change.

Example
data := []byte("Hello, world!")

var v uint32

v = 'h' << 24
v |= 'E' << 16
v |= 'L' << 8
v |= 'L'

WriteUint32(data, uint(len(data)-1), v) // Index out of range
fmt.Println(string(data))

WriteUint32(data, 0, v)
fmt.Println(string(data))

WriteUint32(data, 7, v)
fmt.Println(string(data))
Output:

Hello, world!
hELLo, world!
hELLo, hELLd!

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL