Movatterモバイル変換


[0]ホーム

URL:


exbytes

package
v1.3.2Latest Latest
Warning

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

Go to latest
Published: Feb 23, 2021 License:MITImports:3Imported by:12

Details

Repository

github.com/thinkeridea/go-extend

Links

Documentation

Overview

Package exbytes 收集常规的 []byte 操作,作为 go 标准库 bytes 的扩展。避免重复编写 []byte 相关操作代码,集中在一起更有利于优化代码,保证代码质量。

这个包会使用一些特殊的操作来减少内存开销,已获得更好的程序性能。

我也会在这个包重写 标准库 bytes 里面的一些方法,以适用于不同场景的性能优化。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

funcReplace

func Replace(s, old, new []byte, nint) []byte

Replace 思路来源于 bytes.Replace,bytes.Replace 总是返回 s 的副本,有些场景源数据生命周期非常短,且可以原地替换,如果这么实现可以减少极大的内存分配。

len(old) >= len(new) 会执行原地替换,这回浪费一部分空间,但是会减少内存分配,建议输入生命周期较短的数据, len(old) < len(new) 会调用 bytes.Replace 并返回一个替换后的副本。

最佳实践是使用 Replace 的结果覆盖源变量,避免再次对源数据引用,导致访问过时的数据,并且数据内容错乱,如下:

var s []bytes = exbytes.Replace(s, []byte(" "), []byte(""), -1)

关于字符串可以结合 exstrings.UnsafeToBytes 来实现,要避免常量字符串和字面量字符串,否者会产生运行时错误。

funcReverseadded inv1.0.1

func Reverse(s []byte)

Reverse 原地反转 []byte

funcSubadded inv1.1.0

func Sub(p []byte, start, lengthint) []byte

Sub 是 exutf8.RuneSub 的别名,提供字符数量截取字节数组的方法,针对多字节字符安全高效的截取如果 start 是非负数,返回的字符串将从 string 的 start 位置开始,从 0 开始计算。例如,在字符串 “abcdef” 中,在位置 0 的字符是 “a”,位置 2 的字符串是 “c” 等等。如果 start 是负数,返回的字符串将从 string 结尾处向前数第 start 个字符开始。如果 string 的长度小于 start,将返回空字符串。

如果提供了正数的 length,返回的字符串将从 start 处开始最多包括 length 个字符(取决于 string 的长度)。如果提供了负数的 length,那么 string 末尾处的 length 个字符将会被省略(若 start 是负数则从字符串尾部算起)。如果 start 不在这段文本中,那么将返回空字符串。如果提供了值为 0 的 length,返回的子字符串将从 start 位置开始直到字符串结尾。

funcToString

func ToString(s []byte)string

ToString 把 []byte 转换为 string 没有多余的内存开销。

使用该方法需要了解到 []byte 将和 string 公用一块内存, 修改 []byte 的数据将导致 string 发生变化,这打破了字符串不可以修改的特性,如果你恰恰需要这么做,可能非常的有用。要保证字符串不可变的特性,就必须保证 []byte 不会发生变化,或者立即消费 string,往往这个非常的有用, 比如我们需要打印日志:

b := []byte("hello word")log.Println(ToString(b))

尽快的消耗掉 string 是个好主意, 也可以遗忘掉 []byte 后面不在使用这个, 而只使用 string。

比较好的例子是 exstrings.UnsafePad 系列函数,在函数内部使用 []byte 作为字符串缓冲区,返回字符串通过该方法转换。

Types

This section is empty.

Source Files

View all Source files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp