stringFormatter

package module
v1.6.1 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2025 License: Apache-2.0 Imports: 4 Imported by: 30

README

StringFormatter

  • A set of a high performance string tools that helps to build strings from templates and process text faster than with fmt!!!.
  • Allows to format code in appropriate style (Snake, Kebab, Camel) and case.
  • Slice printing is 50% faster with 8 items slice and 250% with 20 items slice

GitHub go.mod Go version (subdirectory of monorepo) GitHub code size in bytes GitHub issues GitHub Release Date GitHub release (latest by date)

1. Features

  1. Text formatting with template using traditional for C#, Python programmers style - {0}, {name} that faster then fmt does:
  2. Additional text utilities:
    • convert map to string using one of predefined formats (see text_utils.go)
  3. Code Style formatting utilities
    • convert snake/kebab/camel programming code to each other and vice versa (see stringstyle_formatter.go).
  4. StringFormatter aka sf is safe (SAST and tests were running automatically on push)
1. Text formatting from templates
1.1 Description

This is a GO module for template text formatting in syntax like in C# or/and Python using:

  • {n} , n here is a number to notes order of argument list to use i.e. {0}, {1}
  • {name} to notes arguments by name i.e. {name}, {last_name}, {address} and so on ...
1.2 Examples
1.2.1 Format by arg order

i.e. you have following template: "Hello {0}, we are greeting you here: {1}!"

if you call Format with args "manager" and "salesApp" :

formattedStr := stringFormatter.Format("Hello {0}, we are greeting you here: {1}!", "manager", "salesApp")

you get string "Hello manager, we are greeting you here: salesApp!"

1.2.2 Format by arg key

i.e. you have following template: "Hello {user} what are you doing here {app} ?"

if you call FormatComplex with args "vpupkin" and "mn_console" FormatComplex("Hello {user} what are you doing here {app} ?", map[string]any{"user":"vpupkin", "app":"mn_console"})

you get string "Hello vpupkin what are you doing here mn_console ?"

another example is:

strFormatResult = stringFormatter.FormatComplex(
	"Current app settings are: ipAddr: {ipaddr}, port: {port}, use ssl: {ssl}.", 
	map[string]any{"ipaddr":"127.0.0.1", "port":5432, "ssl":false},
)

a result will be: `"Current app settings are: ipAddr: 127.0.0.1, port: 5432, use ssl: false."``

1.2.3 Advanced arguments formatting

For more convenient lines formatting we should choose how arguments are representing in output text, stringFormatter supports following format options:

  1. Bin number formatting
    • {0:B}, 15 outputs -> 1111
    • {0:B8}, 15 outputs -> 00001111
  2. Hex number formatting
    • {0:X}, 250 outputs -> fa
    • {0:X4}, 250 outputs -> 00fa
  3. Oct number formatting
    • {0:o}, 11 outputs -> 14
  4. Float point number formatting
    • {0:E2}, 191.0478 outputs -> 1.91e+02
    • {0:F}, 10.4567890 outputs -> 10.456789
    • {0:F4}, 10.4567890 outputs -> 10.4568
    • {0:F8}, 10.4567890 outputs -> 10.45678900
  5. Percentage output
    • {0:P100}, 12 outputs -> 12%
  6. Lists
    • {0:L-}, [1,2,3] outputs -> 1-2-3
    • {0:L, }, [1,2,3] outputs -> 1, 2, 3
  7. Code
    • {0:c:snake}, myFunc outputs -> my_func
    • {0:c:Snake}, myFunc outputs -> My_func
    • {0:c:SNAKE}, read-timeout outputs -> READ_TIMEOUT
    • {0:c:camel}, my_variable outputs -> myVariable
    • {0:c:Camel}, my_variable outputs -> MyVariable
1.2.4 Benchmarks of the Format and FormatComplex functions

benchmark could be running using following commands from command line:

  • to see Format result - go test -bench=Format -benchmem -cpu 1
  • to see fmt result - go test -bench=Fmt -benchmem -cpu 1
2. Text utilities
2.1 Map to string utility

MapToString function allows to convert map with primitive key to string using format, including key and value, e.g.:

  • {key} => {value}
  • {key} : {value}
  • {value}

For example:

options := map[string]any{
	"connectTimeout": 1000,
	"useSsl":         true,
	"login":          "sa",
	"password":       "sa",
}

str := stringFormatter.MapToString(&options, "{key} : {value}", ", ")
// NOTE: order of key-value pairs is not guranteed though
// str will be something like:
"connectTimeout : 1000, useSsl : true, login : sa, password : sa"
2.2 Benchmarks of the MapToString function
  • to see MapToStr result - go test -bench=MapToStr -benchmem -cpu 1

MapToStr benchmarks

2.3 Slice to string utility

SliceToString - function that converts slice with passed separation between items to string.

slice := []any{100, "200", 300, "400", 500, 600, "700", 800, 1.09, "hello"}
separator := ","
result := stringFormatter.SliceToString(&slice, &separator)

SliceSameTypeToString - function that converts typed slice to line with separator

separator := ":"
numericSlice := []int{100, 200, 400, 800}
result := stringFormatter.SliceSameTypeToString(&numericSlice, &separator)
2.4 Benchmarks of the SliceToString function

sf is rather fast then fmt 2.5 times (250%) faster on slice with 20 items, see benchmark: SliceToStr benchmarks

3. Contributors

Documentation

Index

Constants

View Source
const (
	// KeyKey placeholder will be formatted to map key
	KeyKey = "key"
	// KeyValue placeholder will be formatted to map value
	KeyValue = "value"
)

Variables

This section is empty.

Functions

func Format

func Format(template string, args ...any) string

Format

Func that makes string formatting from template
* It differs from above function only by generic interface that allow to use only primitive data types:
* - integers (int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uin64)
* - floats (float32, float64)
* - boolean
* - string
* - complex
* - objects
* This function defines format automatically
* Parameters
*    - template - string that contains template
*    - args - values that are using for formatting with template
* Returns formatted string

func FormatComplex

func FormatComplex(template string, args map[string]any) string

FormatComplex

Function that format text using more complex templates contains string literals i.e "Hello {username} here is our application {appname}"
* Parameters
*    - template - string that contains template
*    - args - values (dictionary: string key - any value) that are using for formatting with template
* Returns formatted string

func GetFormattingStyleOptions added in v1.6.0

func GetFormattingStyleOptions(style string) (FormattingStyle, CaseSetting, CaseSetting)

GetFormattingStyleOptions function that defines formatting style, case of first char and result from string

*

func MapToString added in v1.1.0

func MapToString[
	K string | int | uint | int32 | int64 | uint32 | uint64,
	V any,
](data map[K]V, format string, separator string) string

MapToString - format map keys and values according to format, joining parts with separator. Format should contain key and value placeholders which will be used for formatting, e.g. "{key} : {value}", or "{value}", or "{key} => {value}". Parts order in resulting string is not guranteed.

func SetStyle added in v1.6.0

func SetStyle(text *string, style FormattingStyle, firstSymbol CaseSetting, textCase CaseSetting) string

SetStyle is a function that converts text with code to defined code style.

Set text like a code style to on from FormattingStyle (Camel, Snake, or Kebab)
* conversion of abbreviations like JSON, USB, and so on is going like a regular text
* for current version, therefore they these abbreviations could be in a different
* case after conversion.
* Case settings apply in the following order : 1 - textCase, 2 - firstSymbol.
* If you are not applying textCase to text converting from Camel to Snake or Kebab
* result is lower case styled text. textCase does not apply to Camel style.
* Parameters:
* - text - pointer to text
* - style - new code style
* - firstSymbol - case settings for first symbol
* - textCase - case settings for whole text except first symbol
* Returns : new string with formatted line

func SliceSameTypeToString added in v1.4.1

func SliceSameTypeToString[T any](data *[]T, separator *string) string

func SliceToString added in v1.4.0

func SliceToString(data *[]any, separator *string) string

SliceToString function that converts slice of any type items to string in format {item}{sep}{item}... TODO(UMV): probably add one more param to wrap item in quotes if necessary

Types

type CaseSetting added in v1.6.0

type CaseSetting int
const (
	ToUpper   CaseSetting = 1
	ToLower   CaseSetting = 2
	NoChanges CaseSetting = 3
)

type FormattingStyle added in v1.6.0

type FormattingStyle string
const (
	Camel FormattingStyle = "camel"
	Snake FormattingStyle = "snake"
	Kebab FormattingStyle = "kebab"
)

Jump to

Keyboard shortcuts

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