conv

package
v1.20.5 Latest Latest
Warning

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

Go to latest
Published: Dec 30, 2025 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package conv provides generic functions for type conversion and value transformation.

This package offers safe and unsafe conversion utilities between compatible types, including byte/string conversions, reference conversions, reflection-based operations, and string manipulation utilities.

Examples

// Convert bytes to string (zero-copy)
bytes := []byte{'h', 'e', 'l', 'l', 'o'}
str := conv.BytesToString[string](bytes)
fmt.Println(str) // Output: hello

// Convert string to readonly bytes
readonlyBytes := conv.StringToReadonlyBytes("hello")
// Note: modifying readonlyBytes will panic

// Convert to snake_case
snake := conv.SnakeString("UserID")
fmt.Println(snake) // "user_id"

// Convert to CamelCase
camel := conv.CamelString("user_id")
fmt.Println(camel) // "UserId"

Package conv provides generic functions for type conversion and value transformation.

This file contains string manipulation utilities including text formatting, case conversion, encoding conversion, and JSON marshaling.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func BytesToString

func BytesToString[STRING ~string](b []byte) STRING

BytesToString convert []byte type to ~string type.

func DecodeHTMLEntities added in v1.20.4

func DecodeHTMLEntities(str string, radix int) string

DecodeHTMLEntities converts HTML entity codes to UTF-8 characters.

The radix parameter specifies the numeric base (e.g., 10 for decimal, 16 for hexadecimal). Invalid entities are left unchanged.

Example:

str := `{"info":[["color","ᕸᖹ⁐&#7c;&#7eff;⁐"]]}`
result := DecodeHTMLEntities(str, 16)
// result: `{"info":[["color","咖啡色|绿色"]]}`

func DecodeUnicodeEscapes added in v1.20.4

func DecodeUnicodeEscapes(str string, radix int) string

DecodeUnicodeEscapes converts Unicode escape sequences (\uXXXX) to UTF-8 characters.

The radix parameter specifies the numeric base (e.g., 10 for decimal, 16 for hexadecimal). Invalid escape sequences are left unchanged. If a code point is longer than 4 characters, only the first 4 are processed.

Example:

str := `{"info":[["color","\u5496\u5561\u8272\u7c\u7eff\u8272"]]}`
result := DecodeUnicodeEscapes(str, 16)
// result: `{"info":[["color","咖啡色|绿色"]]}`

func Deref

func Deref[T any](t *T) T

Deref returns the value of the pointer type. NOTE:

If the value is nil, it will return the zero T.

func DerefImplType

func DerefImplType(v reflect.Value) reflect.Type

DerefImplType returns the underlying type of the value that implements the interface v.

Examples

```go
var iface interface{} = 42
val := reflect.ValueOf(iface)
typ := conv.DerefImplType(val) // returns int type
```

func DerefInterfaceValue

func DerefInterfaceValue(v reflect.Value) reflect.Value

DerefInterfaceValue returns the value of the underlying type that implements the interface v.

Examples

```go
var iface interface{} = 42
val := reflect.ValueOf(iface)
result := conv.DerefInterfaceValue(val) // returns value of 42
```

func DerefMap

func DerefMap[K comparable, V any](a map[K]*V) map[K]V

DerefMap convert map[K]*V to map[K]V. NOTE:

If a value is nil, it will be set to the zero V.

func DerefPtrValue

func DerefPtrValue(v reflect.Value) reflect.Value

DerefPtrValue returns the underlying non-pointer type value.

Examples

```go
x := 42
val := reflect.ValueOf(&x)
result := conv.DerefPtrValue(val) // returns value of 42
```

func DerefSlice

func DerefSlice[T any](a []*T) []T

DerefSlice convert []*T to []T. NOTE:

If an element is nil, it will be set to the zero T.

func DerefSliceValue

func DerefSliceValue(v reflect.Value) reflect.Value

DerefSliceValue convert []*T to []T.

Examples

```go
x, y := 1, 2
ptrSlice := []*int{&x, &y}
val := reflect.ValueOf(ptrSlice)
result := conv.DerefSliceValue(val) // returns []int{1, 2}
```

func DerefType

func DerefType(t reflect.Type) reflect.Type

DerefType dereference, get the underlying non-pointer type.

Examples

```go
typ := reflect.TypeOf((*int)(nil))
baseType := conv.DerefType(typ) // returns int type
```

func DerefValue

func DerefValue(v reflect.Value) reflect.Value

DerefValue dereference and unpack interface, get the underlying non-pointer and non-interface value.

Examples

```go
x := 42
val := reflect.ValueOf(&x)
result := conv.DerefValue(val) // returns value of 42
```

func Indent added in v1.20.4

func Indent(text, prefix string) string

Indent inserts the given prefix at the beginning of each line in the text.

If prefix is empty, the original text is returned unchanged. If text is empty, returns empty string. Empty lines (lines containing only newline) are not indented. The function preserves the trailing newline if present in the input.

Example:

result := Indent("line1\n\nline2", "  ")
// result: "  line1\n\n  line2"

func IsCompositionMethod added in v1.20.3

func IsCompositionMethod(method reflect.Method) bool

IsCompositionMethod determines whether the method is inherited from an anonymous field (composition). It checks if the method is auto-generated by Go's composition mechanism.

NOTE: This function relies on the "<autogenerated>" file marker used by Go's compiler for composition methods. This may not be reliable in all cases.

Examples

```go
type Base struct{}
func (Base) Method() {}

type Derived struct {
	Base // anonymous field
}

method, _ := reflect.TypeOf(Derived{}).MethodByName("Method")
if conv.IsCompositionMethod(method) {
	// Method is inherited from Base
}
```

func IsExportedName added in v1.20.3

func IsExportedName(name string) bool

IsExportedName checks if the name is exported (starts with uppercase letter).

Examples

```go
if conv.IsExportedName("MyFunction") {
	// Name is exported
}
```

func IsExportedOrBuiltinType added in v1.20.3

func IsExportedOrBuiltinType(t reflect.Type) bool

IsExportedOrBuiltinType checks if the type is exported or a builtin type. It dereferences pointer types before checking.

Examples

```go
typ := reflect.TypeOf(MyStruct{})
if conv.IsExportedOrBuiltinType(typ) {
	// Type is exported or builtin
}
```

func NormalizeWhitespace added in v1.20.4

func NormalizeWhitespace(str string) string

NormalizeWhitespace combines multiple consecutive whitespace characters into normalized form.

Rules (industry standard):

  • Multiple spaces -> single space
  • Multiple tabs -> single tab
  • 3+ newlines -> 2 newlines (paragraph separator)
  • 2 newlines after space/tab -> 1 newline (whitespace block normalization)
  • 2 newlines between content -> preserved (paragraph break)
  • Trailing spaces/tabs before newlines -> removed

Example:

input := "hello    world\n\n\ttest"
result := NormalizeWhitespace(input)
// result: "hello world\n\ttest"

func QuoteJSONString added in v1.20.4

func QuoteJSONString(str string, escapeHTML bool) []byte

QuoteJSONString converts a string to a JSON-encoded byte array.

The escapeHTML parameter controls whether HTML characters (<, >, &) are escaped. When true, these characters are escaped to prevent security issues when embedding JSON in HTML <script> tags.

Example:

str := `<>&{}""`
json1 := QuoteJSONString(str, true)
// json1: "\u003c\u003e\u0026{}\"\""
json2 := QuoteJSONString(str, false)
// json2: "<>&{}\"\""
Example
str := `<>&{}""`
fmt.Printf("%s\n", QuoteJSONString(str, true))
fmt.Printf("%s\n", QuoteJSONString(str, false))
Output:
"\u003c\u003e\u0026{}\"\""
"<>&{}\"\""

func Ref

func Ref[T any](t T) *T

Ref returns the address of the value.

func RefMap

func RefMap[K comparable, V any](a map[K]V) map[K]*V

RefMap convert map[K]V to map[K]*V.

func RefSlice

func RefSlice[T any](a []T) []*T

RefSlice convert []T to []*T.

func RefSliceValue

func RefSliceValue(v reflect.Value, ptrDepth int) reflect.Value

RefSliceValue convert []T to []*T, the ptrDepth is the count of '*'.

Examples

```go
slice := []int{1, 2}
val := reflect.ValueOf(slice)
result := conv.RefSliceValue(val, 1) // returns []*int{&1, &2}
```

func RefType

func RefType(t reflect.Type, ptrDepth int) reflect.Type

RefType convert T to *T, the ptrDepth is the count of '*'.

Examples

```go
typ := reflect.TypeOf(42)
ptrType := conv.RefType(typ, 1) // returns *int type
```

func RefValue

func RefValue(v reflect.Value, ptrDepth int) reflect.Value

RefValue convert T to *T, the ptrDepth is the count of '*'.

Examples

```go
val := reflect.ValueOf(42)
ptrVal := conv.RefValue(val, 1) // returns *int pointing to 42
```

func SafeAssert

func SafeAssert[T any](v any) T

SafeAssert asserts any value up to (zero)T.

func SafeAssertMap

func SafeAssertMap[K comparable, V any](a map[K]any) result.Result[map[K]V]

SafeAssertMap convert map[K]any to map[K]V.

func SafeAssertSlice

func SafeAssertSlice[T any](a []any) result.Result[[]T]

SafeAssertSlice convert []any to []T.

func ToAnyMap

func ToAnyMap[K comparable, V any](a map[K]V) map[K]any

ToAnyMap convert map[K]V to map[K]any.

func ToAnySlice

func ToAnySlice[T any](a []T) []any

ToAnySlice convert []T to []any.

func ToCamelCase added in v1.20.4

func ToCamelCase(str string) string

ToCamelCase converts a string to CamelCase format.

Examples:

  • "xx_yy" -> "XxYy"
  • "user_id" -> "UserId"
  • "tcp_rpc" -> "TcpRpc"
  • "user_id_123" -> "UserId123" (underscores before numbers are removed)
  • "a__b__c" -> "A__B__C" (multiple underscores are preserved)

func ToPascalCase added in v1.20.4

func ToPascalCase(name string) string

ToPascalCase converts a string to PascalCase format with support for common initialisms.

Common initialisms like "ID", "RPC", "TCP" are preserved in uppercase.

Examples:

  • "xx_yy" -> "XxYy"
  • "user_id" -> "UserID"
  • "tcp_rpc" -> "TCPRPC"
  • "wake_rpc" -> "WakeRPC"

func ToSnakeCase added in v1.20.4

func ToSnakeCase(str string) string

ToSnakeCase converts a string to snake_case format.

Examples:

  • "XxYy" -> "xx_yy"
  • "UserID" -> "user_id"
  • "TCP_RPC" -> "tcp_rpc"

func TypeName added in v1.20.3

func TypeName(obj any) string

TypeName gets the type name of the object. For functions, it returns the function name from runtime. For other types, it returns the type string representation.

Examples

```go
name := conv.TypeName(42)           // "int"
name := conv.TypeName(&MyStruct{})  // "*conv.MyStruct"
```

func UnsafeAssertMap

func UnsafeAssertMap[K comparable, V any](a map[K]any) map[K]V

UnsafeAssertMap convert map[K]any to map[K]V.

func UnsafeAssertSlice

func UnsafeAssertSlice[T any](a []any) []T

UnsafeAssertSlice convert []any to []T.

func UnsafeConvert

func UnsafeConvert[T any, U any](t T) U

UnsafeConvert convert a value to another type.

func Zero

func Zero[T any]() T

Zero returns the zero value of the type.

Types

type ReadonlyBytes

type ReadonlyBytes = []byte

func StringToReadonlyBytes

func StringToReadonlyBytes[STRING ~string](s STRING) ReadonlyBytes

StringToReadonlyBytes convert ~string to unsafe read-only []byte. NOTE:

panic if modify the member value of the ReadonlyBytes.

Jump to

Keyboard shortcuts

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