Overview
builtin
is a module that is implicitly imported by every V program.
It implements the builtin V types array
, string
, map
.
It also implements builtin functions like println
, eprintln
, malloc
,
panic
, print_backtrace
.
The autogenerated documentation for builtin
functions is lacking, so for these
functions, please refer to the
official V documentation.
Aliases
This section is empty.
Constants
si_g32_code = '0xfe0e'
The consts here are utilities for the compiler's "auto_str_methods.v".
They are used to substitute old _STR calls.
FIXME: this const is not released from memory => use a precalculated string const for now.
si_s_code = "0x" + int(StrIntpType.si_s).hex() // code for a simple string.
si_g64_code = '0xfe0f'
The consts here are utilities for the compiler's "auto_str_methods.v".
They are used to substitute old _STR calls.
FIXME: this const is not released from memory => use a precalculated string const for now.
si_s_code = "0x" + int(StrIntpType.si_s).hex() // code for a simple string.
wp_sys___wnothread = u64(0x20000000) // don't wait on children of other threads in this group
wp_sys___wall = u64(0x40000000) // wait on all children, regardless of type
wp_sys___wclone = u64(0x80000000) // wait only on non-sigchld children
Sum types
This section is empty.
Functions
used by Android for (e)println to output to the Android log system / logcat
fn JS.Array.prototype.constructor([]any) JS.Array
fn JS.Promise.prototype.constructor(JS.Any) JS.Promise
return a C-API error message matching to errnum
compare_strings returns -1
if a < b
, 1
if a > b
else 0
.
compare_strings returns -1
if a < b
, 1
if a > b
else 0
.
cstring_to_vstring creates a new V string copy of the C style string, pointed by s
. This function is most likely what you want to use when working with C style pointers to 0 terminated strings (i.e. char*
).
It is recomended to use it, unless you do understand the implications of tos/tos2/tos3/tos4/tos5 in terms of memory management and interactions with -autofree and [manualfree]
.
It will panic, if the pointer s
is 0.
fn eprintln(s string)
eprintln prints a message with a line end, to stderr. Both stderr and stdout are flushed.
error returns a default error instance containing the error given in message
.
Example:
if ouch { return error('an error occurred') }
error returns a default error instance containing the error given in message
.
Example:
if ouch { return error('an error occurred') }
error_with_code returns a default error instance containing the given message
and error code
.
Example:
if ouch { return error_with_code('an error occurred', 1) }
error_with_code returns a default error instance containing the given message
and error code
.
Example:
if ouch { return error_with_code('an error occurred', 1) }
fn exit(code int)
fn exit(c int)
Exits the process in node, and halts execution in the browser because process.exit
is undefined. Workaround for not having a 'real' way to exit in the browser.
fn exit(code int)
fn free(ptr voidptr)
free allows for manually freeing memory allocated at the address ptr
.
currently does not free any memory.
fn free(ptr voidptr)
free allows for manually freeing memory allocated at the address ptr
.
However, this is a no-op on JS backend
fn gc_check_leaks()
provide an empty function when manual memory management is used to simplify leak detection
fn gc_check_leaks()
for leak detection it is advisable to do explicit garbage collections
fn get_str_intp_u32_format(fmt_type StrIntpType, in_width int, in_precision int, in_tail_zeros bool, in_sign bool, in_pad_ch byte, in_base int, in_upper_case bool) u32
convert from data format to compact u32
fn get_str_intp_u64_format(fmt_type StrIntpType, in_width int, in_precision int, in_tail_zeros bool, in_sign bool, in_pad_ch byte, in_base int, in_upper_case bool) u64
convert from data format to compact u64
isnil returns true if an object is nil (only for C objects).
isnil returns true if an object is nil (only for C objects).
fn js_node_process() JS.node_process
hack to access process properties
malloc_uncollectable dynamically allocates a n
bytes block of memory on the heap, which will NOT be garbage-collected (but its contents will).
memdup dynamically allocates a sz
bytes block of memory on the heap memdup then copies the contents of src
into the allocated space and returns a pointer to the newly allocated space.
memdup_uncollectable dynamically allocates a sz
bytes block of memory on the heap, which will NOT be garbage-collected (but its contents will).
memdup_uncollectable then copies the contents of src
into the allocated space and returns a pointer to the newly allocated space.
fn panic(s string)
panic prints a nice error message, then exits the process with exit code of 1.
It also shows a backtrace on most platforms.
panic with a C-API error message matching errnum
fn panic_lasterr(base string)
panic with an error message generated from WinAPI's LastError
fn panic_option_not_set(s string)
panic_option_not_set is called by V, when you use option error propagation in your main function.
It ends the program with a panic.
fn panic_result_not_set(s string)
panic_result_not_set is called by V, when you use result error propagation in your main function It ends the program with a panic.
fn print(s string)
fn print(s string)
fn print_backtrace()
print_backtrace shows a backtrace of the current call stack on stdout
race returns returns a promise that fulfills or rejects as soon as one of the promises in an iterable fulfills or rejects, with the value or reason from that promise.
reject
fn promise_resolve[T](result T) Promise[T]
resolve
realloc_data resizes the memory block pointed by old_data
to new_size
bytes. old_data
must be a pointer to an existing memory block, previously allocated with malloc
, v_calloc
or vcalloc
, of size old_data
.
realloc_data returns a pointer to the new location of the block.
Note: if you know the old data size, it is preferable to call realloc_data
, instead of v_realloc
, at least during development, because realloc_data
can make debugging easier, when you compile your program with -d debug_realloc
.
fn str_intp(data_len int, input_base &StrIntpData) string
interpolation function
replace %% with the in_str
string_from_wide creates a V string, encoded in UTF-8, given a windows style string encoded in UTF-16.
string_from_wide2 creates a V string, encoded in UTF-8, given a windows style string, encoded in UTF-16. It is more efficient, compared to string_from_wide, but it requires you to know the input string length, and to pass it as the second argument.
33 sys_dup2 unsigned int oldfd unsigned int newfd
9 sys_mmap unsigned long addr unsigned long len unsigned long prot unsigned long flags unsigned long fd unsigned long off
0 sys_read unsigned int fd char *buf size_t count
247 sys_waitid int which pid_t upid struct siginfo *infop int options struct rusage *ru
1 sys_write unsigned int fd, const char *buf, size_t count
Same as tos
, but calculates the length. Called by string(bytes)
casts.
Used only internally.
tos2 creates a V string, given a C style pointer to a 0 terminated block.
Note: the memory block pointed by s is reused, not copied!
It will calculate the length first, thus it is more costly than tos
.
It will panic, when the pointer s
is 0.
It is the same as tos3
, but for &byte pointers, avoiding callsite casts.
See also tos_clone
.
tos3 creates a V string, given a C style pointer to a 0 terminated block.
Note: the memory block pointed by s is reused, not copied!
It will calculate the length first, so it is more costly than tos.
It will panic, when the pointer s
is 0.
It is the same as tos2
, but for &char pointers, avoiding callsite casts.
See also tos_clone
.
tos4 creates a V string, given a C style pointer to a 0 terminated block.
Note: the memory block pointed by s is reused, not copied!
It will calculate the length first, so it is more costly than tos.
It returns '', when given a 0 pointer s
, it does NOT panic.
It is the same as tos5
, but for &byte pointers, avoiding callsite casts.
See also tos_clone
.
tos5 creates a V string, given a C style pointer to a 0 terminated block.
Note: the memory block pointed by s is reused, not copied!
It will calculate the length first, so it is more costly than tos.
It returns '', when given a 0 pointer s
, it does NOT panic.
It is the same as tos4
, but for &char pointers, avoiding callsite casts.
See also tos_clone
.
tos_clone creates a new V string copy of the C style string, pointed by s
.
See also cstring_to_vstring (it is the same as it, the only difference is, that tos_clone expects &byte
, while cstring_to_vstring expects &char).
It will panic, if the pointer s
is 0.
utf8_str_len returns the number of runes contained in the string.
Calculate string length for formatting, i.e. number of "characters" This is simplified implementation. if you need specification compliant width, use utf8.east_asian.display_width.
special versions of the above that allocate memory which is not scanned for pointers (but is collected) when the Boehm garbage collection is used
vmemcmp compares the first n bytes (each interpreted as unsigned char) of the memory areas s1 and s2. It returns an integer less than, equal to, or greater than zero, if the first n bytes of s1 is found, respectively, to be less than, to match, or be greater than the first n bytes of s2.
For a nonzero return value, the sign is determined by the sign of the difference between the first pair of bytes (interpreted as unsigned char) that differ in s1 and s2.
If n is zero, the return value is zero.
Do NOT use vmemcmp to compare security critical data, such as cryptographic secrets, because the required CPU time depends on the number of equal bytes.
You should use a function that performs comparisons in constant time for this.
vmemcpy copies n bytes from memory area src to memory area dest.
The memory areas CAN overlap. vmemcpy returns a pointer to dest
.
vmemcpy copies n bytes from memory area src to memory area dest.
The memory areas MUST NOT OVERLAP. Use vmemmove, if the memory areas do overlap. vmemcpy returns a pointer to dest
.
vmemmove copies n bytes from memory area src to memory area dest.
The memory areas CAN overlap. vmemmove returns a pointer to dest
.
vmemmove copies n bytes from memory area src
to memory area dest
.
The memory areas MAY overlap: copying takes place as though the bytes in src
are first copied into a temporary array that does not overlap src
or dest
, and the bytes are then copied from the temporary array to dest
. vmemmove returns a pointer to dest
.
vmemset fills the first n
bytes of the memory area pointed to by s
, with the constant byte c
. It returns a pointer to the memory area s
.
vmemset fills the first n
bytes of the memory area pointed to by s
, with the constant byte c
. It returns a pointer to the memory area s
.
vstrlen returns the V length of the C string s
(0 terminator is not counted).
The C string is expected to be a &byte pointer.
vstrlen_char returns the V length of the C string s
(0 terminator is not counted).
The C string is expected to be a &char pointer.
fn winapi_lasterr_str() string
return an error message generated from WinAPI's LastError
fn winapi_lasterr_str() string
These functions are Windows specific - provide dummys for *nix
str returns a string representation of an array of strings
Example:
['a', 'b', 'c'].str() // => "['a', 'b', 'c']".
hex returns a string with the hexadecimal representation of the byte elements of the array.
clone clones the byte array, and returns the newly created copy.
bytestr produces a string from all the bytes in the array.
Note: the returned string will have .len equal to the array.len, even when some of the array bytes were 0
.
If you want to get a V string, that contains only the bytes till the first 0
byte, use tos_clone(&u8(array.data))
instead.
byterune attempts to decode a sequence of bytes from utf8 to utf32 and return the result as a rune it will produce an error if there are more than four bytes in the array.
string converts a rune array to a string
fn (mut s &[]string) sort_ignore_case()
sort_ignore_case sorts the string array using case insesitive comparing.
fn (mut s &[]string) sort_by_len()
sort_by_len sorts the the string array by each string's .len
length.
join joins a string array into a string using sep
separator.
Example:
assert ['Hello','V'].join(' ') == 'Hello V'
join joins a string array into a string using a \n
newline delimiter.
convert array of utf8 bytes to single utf32 value will error if more than 4 bytes are submitted
hex returns a string with the hexadecimal representation of the byte elements of the array.
fn (mut s &[]string) sort_ignore_case()
sort_ignore_case sorts the string array using case insesitive comparing.
fn (mut s &[]string) sort_by_len()
sort_by_len sorts the the string array by each string's .len
length.
Structs
pub struct array {
pub:
element_size int // size in bytes of one element in the array.
pub mut:
data voidptr
offset int // in bytes (should be `usize`), to avoid copying data while making slices, unless it starts changing
len int // length of the array in elements.
cap int // capacity of the array in elements.
flags ArrayFlags
}
array is a struct, used for denoting all array types in V.
.data
is a void pointer to the backing heap memory block, which avoids using generics and thus without generating extra code for every type.
Private function. Increases the cap
of an array to the required value by copying the data to a new memory location (creating a clone) unless a.cap
is already large enough.
repeat returns a new array with the given array elements repeated given times.
cgen
will replace this with an apropriate call to repeat_to_depth
This is a dummy placeholder that will be overridden by cgen
with an appropriate call to repeat_to_depth
. However the checker
needs it here.
repeat_to_depth is an unsafe version of repeat
that handles multi-dimensional arrays.
It is unsafe
to call directly because depth
is not checked
insert inserts a value in the array at index i
and increases the index of subsequent elements by 1.
This function is type-aware and can insert items of the same or lower dimensionality as the original array. That is, if the original array is []int
, then the insert val
may be int
or []int
. If the original array is [][]int
, then val
may be []int
or [][]int
. Consider the examples.
Example:
mut a := [1, 2, 4] a.insert(2, 3) // a now is [1, 2, 3, 4] mut b := [3, 4] b.insert(0, [1, 2]) // b now is [1, 2, 3, 4] mut c := [[3, 4]] c.insert(0, [1, 2]) // c now is [[1, 2], [3, 4]]
insert_many is used internally to implement inserting many values into an the array beginning at i
.
prepend prepends one or more elements to an array.
It is shorthand for .insert(0, val)
prepend_many prepends another array to this array.
NOTE: prepend
is probably all you need.
NOTE: This code is never called in all of vlib
delete deletes array element at index i
.
This is exactly the same as calling .delete_many(i, 1)
.
NOTE: This function does NOT operate in-place. Internally, it creates a copy of the array, skipping over the element at i
, and then points the original variable to the new memory location.
Example:
mut a := ['0', '1', '2', '3', '4', '5'] a.delete(1) // a is now ['0', '2', '3', '4', '5']
delete_many deletes size
elements beginning with index i
NOTE: This function does NOT operate in-place. Internally, it creates a copy of the array, skipping over size
elements starting at i
, and then points the original variable to the new memory location.
Example:
mut a := [1, 2, 3, 4, 5, 6, 7, 8, 9] b := a[..9] // creates a <code>[slice](/standard_library/builtin.html#array_slice)</code> of `a`, not a clone a.delete_many(4, 3) // replaces `a` with a modified clone dump(a) // a: [1, 2, 3, 4, 8, 9] // `a` is now different dump(b) // b: [1, 2, 3, 4, 5, 6, 7, 8, 9] // `b` is still the same
fn (mut a &array) clear()
clear clears the array without deallocating the allocated data.
It does it by setting the array length to 0
Example:
a.clear() // `a.len` is now 0
drop advances the array past the first num
elements whilst preserving spare capacity.
If num
is greater than len
the array will be emptied.
Example:
mut a := [1,2] a << 3 a.drop(2) assert a == [3] assert a.cap > a.len
we manually inline this for single operations for performance without -prod
Private function. Used to implement array[] operator.
Private function. Used to implement x = a[i] or { ... }
pop returns the last element of the array, and removes it.
If the array
is empty, this will panic.
NOTE: this function reduces the length of the given array, but arrays sliced from this one will not change. They still retain their "view" of the underlying memory.
Example:
mut a := [1, 2, 3, 4, 5, 6, 7, 8, 9] b := a[..9] // creates a "view" into the same memory c := a.pop() // c == 9 a[1] = 5 dump(a) // a: [1, 5, 3, 4, 5, 6, 7, 8] dump(b) // b: [1, 5, 3, 4, 5, 6, 7, 8, 9]
fn (mut a &array) delete_last()
delete_last efficiently deletes the last element of the array.
It does it simply by reducing the length of the array by 1.
If the array is empty, this will panic.
See also: trim
slice returns an array using the same buffer as original array but starting from the start
element and ending with the element before the end
element of the original array with the length and capacity set to the number of the elements in the slice.
It will remain tied to the same memory location until the length increases (copy on grow) or clone
is called on it.
If start
and end
are invalid this function will panic.
Alternative: Slices can also be made with [start..end] notation Alternative: slice_ni
will always return an array.
slice_ni returns an array using the same buffer as original array but starting from the start
element and ending with the element before the end
element of the original array.
This function can use negative indexes a.slice_ni(-3, a.len)
that get the last 3 elements of the array otherwise it return an empty array.
This function always return a valid array.
used internally for [2..4]
clone_static_to_depth() returns an independent copy of a given array.
Unlike clone_to_depth
it has a value receiver and is used internally for slice-clone expressions like a[2..4].clone()
and in -autofree generated code.
clone returns an independent copy of a given array.
this will be overwritten by cgen
with an apropriate call to clone_to_depth
However the checker
needs it here.
recursively clone given array - unsafe
when called directly because depth is not checked
we manually inline this for single operations for performance without -prod
Private function. Used to implement assignment to the array element.
push_many implements the functionality for pushing another array.
val
is array.data and user facing usage is a << [1,2,3]
fn (mut a &array) reverse_in_place()
reverse_in_place reverses existing array data, modifying original array.
reverse returns a new array with the elements of the original array in reverse order.
filter creates a new array with all elements that pass the test.
Ignore the function signature. filter
does not take an actual callback. Rather, it takes an it
expression.
Certain array functions (filter
any
all
) support a simplified domain-specific-language by the backend compiler to make these operations more idiomatic to V. These functions are described here, but their implementation is compiler specific.
Each function takes a boolean test expression as its single argument.
These test expressions may use it
as a pointer to a single element at a time.
Example:
array.filter(it < 5) // create an array of elements less than 5
Example:
array.filter(it % 2 == 1) // create an array of only odd elements
Example:
array.filter(it.name[0] == `A`) // create an array of elements whose `name` field starts with 'A'
any tests whether at least one element in the array passes the test.
Ignore the function signature. any
does not take an actual callback. Rather, it takes an it
expression.
It returns true
if it finds an element passing the test. Otherwise, it returns false
. It doesn't modify the array.
Example:
array.any(it % 2 == 1) // will return true if any element is odd
Example:
array.any(it.name == 'Bob') // will yield `true` if any element has `.name == 'Bob'
all tests whether all elements in the array pass the test.
Ignore the function signature. all
does not take an actual callback. Rather, it takes an it
expression.
It returns false
if any element fails the test. Otherwise, it returns true
. It doesn't modify the array.
Example:
array.all(it % 2 == 1) // will return true if every element is odd
map creates a new array populated with the results of calling a provided function on every element in the calling array.
It also accepts an it
expression.
Example:
words := ['hello', 'world'] r1 := words.map(it.to_upper()) assert r1 == ['HELLO', 'WORLD'] // map can also accept anonymous functions r2 := words.map(fn (w string) string { return w.to_upper() }) assert r2 == ['HELLO', 'WORLD']
sort sorts the array in place.
Ignore the function signature. Passing a callback to sort
is not supported for now. Consider using the sort_with_compare
method if you need it.
sort can take a boolean test expression as its single argument.
The expression uses 2 'magic' variables a
and b
as pointers to the two elements being compared.
Example:
array.sort() // will sort the array in ascending order
Example:
array.sort(b < a) // will sort the array in decending order
Example:
array.sort(b.name < a.name) // will sort descending by the .name field
sort_with_compare sorts the array in-place using the results of the given function to determine sort order.
The function should return one of three values:
-1
whena
should come beforeb
(a < b
)1
whenb
should come beforea
(b < a
)0
when the order cannot be determined (a == b
)
Example:
fn main() { mut a := ['hi', '1', '5', '3'] a.sort_with_compare(fn (a &string, b &string) int { if a < b { return -1 } if a > b { return 1 } return 0 }) assert a == ['1', '3', '5', 'hi'] }
index returns the first index at which a given element can be found in the array or -1
if the value is not found.
grow_cap grows the array's capacity by amount
elements.
Internally, it does this by copying the entire array to a new memory location (creating a clone).
grow_len ensures that an array has a.len + amount of length Internally, it does this by copying the entire array to a new memory location (creating a clone) unless the array.cap is already large enough.
pointers returns a new array, where each element is the address of the corresponding element in the array.
Private function. Doubles array capacity if needed.
version of repeat
that handles multi dimensional arrays unsafe
to call directly because depth
is not checked
insert inserts a value in the array at index i
insert_many inserts many values into the array from index i
.
prepend prepends one value to the array.
prepend_many prepends another array to this array.
pop returns the last element of the array, and removes it.
clone_static_to_depth_noscan
returns an independent copy of a given array.
Unlike clone_to_depth_noscan
it has a value receiver and is used internally for slice-clone expressions like a[2..4].clone()
and in -autofree generated code.
recursively clone given array - unsafe
when called directly because depth is not checked
push_many implements the functionality for pushing another array.
val
is array.data and user facing usage is a << [1,2,3]
reverse returns a new array with the elements of the original array in reverse order.
grow_cap grows the array's capacity by amount
elements.
grow_len ensures that an array has a.len + amount of length
trim trims the array length to "index" without modifying the allocated data. If "index" is greater than len nothing will be changed.
last returns the last element of the array.
delete deletes array element at index i
.
delete_many deletes size
elements beginning with index i
prepend prepends one value to the array.
prepend_many prepends another array to this array.
reduce executes a given reducer function on each element of the array, resulting in a single output value.
fn (mut a &array) delete_last()
delete_last effectively removes last element of an array.
todo: once (a []u8) will work rewrite this
Private function. Used to implement array[] operator
Private function. Used to implement assignment to the array element.
array.repeat returns new array with the given array elements repeated nr_repeat
times
pub struct VAssertMetaInfo {
pub:
fpath string // the source file path of the assertion
line_nr int // the line number of the assertion
fn_name string // the function name in which the assertion is
src string // the actual source line of the assertion
op string // the operation of the assertion, i.e. '==', '<', 'call', etc ...
llabel string // the left side of the infix expressions as source
rlabel string // the right side of the infix expressions as source
lvalue string // the stringified *actual value* of the left side of a failed assertion
rvalue string // the stringified *actual value* of the right side of a failed assertion
message string // the value of the `message` from `assert cond, message`
has_msg bool // false for assertions like `assert cond`, true for `assert cond, 'oh no'`
}
VAssertMetaInfo is used during assertions. An instance of it is filled in by compile time generated code, when an assertion fails.
fn (ami &VAssertMetaInfo) free()
free frees the memory occupied by the assertion meta data. It is called automatically by the code, that V's test framework generates, after all other callbacks have been called.
MethodArgs holds type information for function and/or method arguments.
pub struct FunctionData {
pub:
name string
attrs []string
args []MethodArgs
return_type int
typ int
}
FunctionData holds information about a parsed function.
pub struct FieldData {
pub:
name string // the name of the field f
typ int // the internal TypeID of the field f,
unaliased_typ int // if f's type was an alias of int, this will be TypeID(int)
//
attrs []string // the attributes of the field f
is_pub bool // f is in a `pub:` section
is_mut bool // f is in a `mut:` section
//
is_shared bool // `f shared Abc`
is_atomic bool // `f atomic int` , TODO
is_option bool // `f ?string` , TODO
//
is_array bool // `f []string` , TODO
is_map bool // `f map[string]int` , TODO
is_chan bool // `f chan int` , TODO
is_enum bool // `f Enum` where Enum is an enum
is_struct bool // `f Abc` where Abc is a struct , TODO
is_alias bool // `f MyInt` where `type MyInt = int`, TODO
//
indirections u8 // 0 for `f int`, 1 for `f &int`, 2 for `f &&int` , TODO
}
FieldData holds information about a field. Fields reside on structs.
pub struct StructAttribute {
pub:
name string
has_arg bool
arg string
kind AttributeKind
}
pub struct SymbolInfo {
pub mut:
f_size_of_struct u32 // must be 88 to be recognised by SymFromAddr
f_type_index u32 // Type Index of symbol
f_reserved [2]u64
f_index u32
f_size u32
f_mod_base u64 // Base Address of module comtaining this symbol
f_flags u32
f_value u64 // Value of symbol, ValuePresent should be 1
f_address u64 // Address of symbol including base address of module
f_register u32 // register holding value or pointer to value
f_scope u32 // scope of the symbol
f_tag u32 // pdb classification
f_name_len u32 // Actual length of name
f_max_name_len u32 // must be manually set
f_name u8 // must be calloc(f_max_name_len)
}
SymbolInfo is used by print_backtrace_skipping_top_frames_msvc
pub struct SymbolInfoContainer {
pub mut:
syminfo SymbolInfo
f_name_rest [254]char
}
pub struct Line64 {
pub mut:
f_size_of_struct u32
f_key voidptr
f_line_number u32
f_file_name &u8 = unsafe { nil }
f_address u64
}
pub struct map {
// Number of bytes of a key
key_bytes int
// Number of bytes of a value
value_bytes int
mut:
// Highest even index in the hashtable
even_index u32
// Number of cached hashbits left for rehashing
cached_hashbits u8
// Used for right-shifting out used hashbits
shift u8
// Array storing key-values (ordered)
key_values DenseArray
// Pointer to meta-data:
// - Odd indices store kv_index.
// - Even indices store probe_count and hashbits.
metas &u32
// Extra metas that allows for no ranging when incrementing
// index in the hashmap
extra_metas u32
has_string_keys bool
hash_fn MapHashFn
key_eq_fn MapEqFn
clone_fn MapCloneFn
free_fn MapFreeFn
pub mut:
// Number of key-values currently in the hashmap
len int
}
fn new_map(key_bytes int, value_bytes int, hash_fn fn (voidptr) u64, key_eq_fn fn (voidptr, voidptr) bool, clone_fn fn (voidptr, voidptr), free_fn fn (voidptr)) map
as_strings returns the contents of the map as map[string]string
to_inline_toml returns the contents of the map as an inline table encoded TOML string
.
fn (mut m &map) clear()
clear clears the map without deallocating the allocated data.
It does it by setting the map length to 0
Example:
a.clear() // `a.len` and `a.key_values.len` is now 0
Insert new element to the map. The element is inserted if its key is not equivalent to the key of any other element already in the container.
If the key already exists, its value is changed to the value of the new element.
fn (mut m &map) rehash()
A rehash is the reconstruction of the hash table:
All the elements in the container are rearranged according to their hash value into the newly sized key-value container.
Rehashes are performed when the load_factor is going to surpass the max_load_factor in an operation.
reserve memory for the map meta data
This method works like rehash. However, instead of rehashing the key completely, it uses the bits cached in metas
.
This method is used for assignment operators. If the argument-key does not exist in the map, it's added to the map along with the zero/default value.
If the key exists, its respective value is returned.
If key
matches the key of an element in the container, the method returns a reference to its mapped value.
If not, a zero/default value is returned.
If key
matches the key of an element in the container, the method returns a reference to its mapped value.
If not, a zero pointer is returned.
This is used in x := m['key'] or { ... }
Checks whether a particular key exists in the map.
Removes the mapping of a particular key from the map.
fn (m &map) free()
Removes the mapping of a particular key from the map.
arr() converts the map into an array of DocNode
.
str returns the JSON string representation of the map[string]Any
type.
This implementation does proactive insertion, meaning that splits are done top-down and not bottom-up.
pub struct string {
pub:
str &u8 = 0 // points to a C style 0 terminated string of bytes.
len int // the length of the .str field, excluding the ending 0 byte. It is always equal to strlen(.str).
// NB string.is_lit is an enumeration of the following:
// .is_lit == 0 => a fresh string, should be freed by autofree
// .is_lit == 1 => a literal string from .rodata, should NOT be freed
// .is_lit == -98761234 => already freed string, protects against double frees.
// ---------> ^^^^^^^^^ calling free on these is a bug.
// Any other value means that the string has been corrupted.
mut:
is_lit int
}
runes returns an array of all the utf runes in the string s
which is useful if you want random access to them
len_utf8 returns the number of runes contained in the string s
.
clone_static returns an independent copy of a given array.
It should be used only in -autofree generated code.
replace_once replaces the first occurence of rep
with the string passed in with
.
replace replaces all occurences of rep
with the string passed in with
.
replace_each replaces all occurences of the string pairs given in vals
.
Example:
assert 'ABCD'.replace_each(['B','C/','C','D','D','C']) == 'AC/DC'
replace_char replaces all occurences of the character rep
multiple occurences of the character passed in with
with respect to repeat
.
Example:
assert '\tHello!'.replace_char(`\t`,` `,8) == ' Hello!'
normalize_tabs replaces all tab characters with tab_len
amount of spaces
Example:
assert '\t\tpop rax\t; pop rax'.normalize_tabs(2) == ' pop rax ; pop rax'
bool returns true
if the string equals the word "true" it will return false
otherwise.
int returns the value of the string as an integer '1'.int() == 1
.
i64 returns the value of the string as i64 '1'.i64() == i64(1)
.
i8 returns the value of the string as i8 '1'.i8() == i8(1)
.
i16 returns the value of the string as i16 '1'.i16() == i16(1)
.
f32 returns the value of the string as f32 '1.0'.f32() == f32(1)
.
f64 returns the value of the string as f64 '1.0'.f64() == f64(1)
.
u8 returns the value of the string as u8 '1'.u8() == u8(1)
.
u16 returns the value of the string as u16 '1'.u16() == u16(1)
.
u32 returns the value of the string as u32 '1'.u32() == u32(1)
.
u64 returns the value of the string as u64 '1'.u64() == u64(1)
.
parse_uint is like parse_int
but for unsigned numbers
This method directly exposes the parse_uint
function from strconv
as a method on string
. For more advanced features, consider calling strconv.common_parse_uint
directly.
parse_int interprets a string s in the given base (0, 2 to 36) and bit size (0 to 64) and returns the corresponding value i.
If the base argument is 0, the true base is implied by the string's prefix: 2 for "0b", 8 for "0" or "0o", 16 for "0x", and 10 otherwise.
Also, for argument base 0 only, underscore characters are permitted as defined by the Go syntax for integer literals.
The bitSize argument specifies the integer type that the result must fit into. Bit sizes 0, 8, 16, 32, and 64 correspond to int, int8, int16, int32, and int64.
If bitSize is below 0 or above 64, an error is returned.
This method directly exposes the parse_int
function from strconv
as a method on string
. For more advanced features, consider calling strconv.common_parse_int
directly.
compare returns -1 if s
< a
, 0 if s
== a
, and 1 if s
> a
rsplit_any splits the string to an array by any of the delim
chars in reverse order.
Example:
"first row\nsecond row".rsplit_any(" \n") == ['row', 'second', 'row', 'first']
Split a string using the chars in the delimiter string as delimiters chars.
If the delimiter string is empty then rsplit
is used.
split splits the string to an array by delim
.
Example:
assert 'A B C'.split(' ') == ['A','B','C']
If delim
is empty the string is split by it's characters.
Example:
assert 'DEF'.split('') == ['D','E','F']
rsplit splits the string to an array by delim
in reverse order.
Example:
assert 'A B C'.rsplit(' ') == ['C','B','A']
If delim
is empty the string is split by it's characters.
Example:
assert 'DEF'.rsplit('') == ['F','E','D']
split_once devides string into pair of string by delim
.
Example:
path, ext := 'file.ts.dts'.splice_once('.')? assert path == 'file' assert ext == 'ts.dts'
Note that rsplit_once returns splitted string string as first part of pair, and returns remaining as second part of pair.
rsplit_once devides string into pair of string by delim
.
Example:
path, ext := 'file.ts.dts'.splice_once('.')? assert path == 'file.ts' assert ext == 'dts'
Note that rsplit_once returns remaining string as first part of pair, and returns splitted string as second part of pair.
split_nth splits the string based on the passed delim
substring.
It returns the first Nth parts. When N=0, return all the splits.
The last returned element has the remainder of the string, even if the remainder contains more delim
substrings.
rsplit_nth splits the string based on the passed delim
substring in revese order.
It returns the first Nth parts. When N=0, return all the splits.
The last returned element has the remainder of the string, even if the remainder contains more delim
substrings.
split_into_lines splits the string by newline characters.
newlines are stripped.
\r
(MacOS), \n
(POSIX), and \r\n
(WinOS) line endings are all supported (including mixed line endings).
NOTE: algorithm is "greedy", consuming '\r\n' as a single line ending with higher priority than '\r' and '\n' as multiple endings
used internally for [2..4]
substr returns the string between index positions start
and end
.
Example:
assert 'ABCD'.substr(1,3) == 'BC'
version of substr
that is used in a[start..end] or {
return an error when the index is out of range
substr_ni returns the string between index positions start
and end
allowing negative indexes This function always return a valid string.
index returns the position of the first character of the input string.
It will return -1
if the input string can't be found.
index returns the position of the first character of the input string.
It will return none
if the input string can't be found.
index_kmp does KMP search.
index_any returns the position of any of the characters in the input string - if found.
last_index returns the position of the last occurence of the input string.
last_index returns the position of the last occurence of the input string.
index_after returns the position of the input string, starting search from start
position.
index_u8 returns the index of byte c
if found in the string.
index_u8 returns -1 if the byte can not be found.
last_index_byte returns the index of the last occurence of byte c
if found in the string.
last_index_byte returns -1 if the byte is not found.
contains_u8 returns true
if the string contains the byte value x
.
See also: string.index_u8
, to get the index of the byte as well.
contains returns true
if the string contains substr
.
See also: string.index
contains_any returns true
if the string contains any chars in chars
.
contains_only returns true
, if the string contains only the characters in chars
.
contains_any_substr returns true
if the string contains any of the strings in substrs
.
starts_with returns true
if the string starts with p
.
ends_with returns true
if the string ends with p
.
to_lower returns the string in all lowercase characters.
TODO only works with ASCII
is_lower returns true
if all characters in the string is lowercase.
Example:
assert 'hello developer'.is_lower() == true
to_upper returns the string in all uppercase characters.
Example:
assert 'Hello V'.to_upper() == 'HELLO V'
is_upper returns true
if all characters in the string is uppercase.
See also: byte.is_capital
Example:
assert 'HELLO V'.is_upper() == true
capitalize returns the string with the first character capitalized.
Example:
assert 'hello'.capitalize() == 'Hello'
is_capital returns true
, if the first character in the string s
, is a capital letter, and the rest are NOT.
Example:
assert 'Hello'.is_capital() == true
Example:
assert 'HelloWorld'.is_capital() == false
starts_with_capital returns true
, if the first character in the string s
, is a capital letter, even if the rest are not.
Example:
assert 'Hello'.starts_with_capital() == true
Example:
assert 'Hello. World.'.starts_with_capital() == true
title returns the string with each word capitalized.
Example:
assert 'hello v developer'.title() == 'Hello V Developer'
is_title returns true if all words of the string are capitalized.
Example:
assert 'Hello V Developer'.is_title() == true
find_between returns the string found between start
string and end
string.
Example:
assert 'hey [man] how you doin'.find_between('[', ']') == 'man'
trim_space strips any of
, \n
, \t
, \v
, \f
, \r
from the start and end of the string.
Example:
assert ' Hello V '.trim_space() == 'Hello V'
trim strips any of the characters given in cutset
from the start and end of the string.
Example:
assert ' ffHello V ffff'.trim(' f') == 'Hello V'
trim_indexes gets the new start and end indicies of a string when any of the characters given in cutset
were stripped from the start and end of the string. Should be used as an input to substr
. If the string contains only the characters in cutset
, both values returned are zero.
Example:
left, right := '-hi-'.trim_indexes('-')
trim_left strips any of the characters given in cutset
from the left of the string.
Example:
assert 'd Hello V developer'.trim_left(' d') == 'Hello V developer'
trim_right strips any of the characters given in cutset
from the right of the string.
Example:
assert ' Hello V d'.trim_right(' d') == ' Hello V'
trim_string_left strips str
from the start of the string.
Example:
assert 'WorldHello V'.trim_string_left('World') == 'Hello V'
trim_string_right strips str
from the end of the string.
Example:
assert 'Hello VWorld'.trim_string_right('World') == 'Hello V'
trim_prefix strips str
from the start of the string.
Example:
assert 'WorldHello V'.trim_prefix('World') == 'Hello V'
trim_suffix strips str
from the end of the string.
Example:
assert 'Hello VWorld'.trim_suffix('World') == 'Hello V'
version of at
that is used in a[i] or {
return an error when the index is out of range
before returns the contents before sub
in the string.
If the substring is not found, it returns the full input string.
Example:
assert '23:34:45.234'.before('.') == '23:34:45'
Example:
assert 'abcd'.before('.') == 'abcd'
TODO: deprecate and remove either .before or .all_before
all_before returns the contents before sub
in the string.
If the substring is not found, it returns the full input string.
Example:
assert '23:34:45.234'.all_before('.') == '23:34:45'
Example:
assert 'abcd'.all_before('.') == 'abcd'
all_before_last returns the contents before the last occurence of sub
in the string.
If the substring is not found, it returns the full input string.
Example:
assert '23:34:45.234'.all_before_last(':') == '23:34'
Example:
assert 'abcd'.all_before_last('.') == 'abcd'
all_after returns the contents after sub
in the string.
If the substring is not found, it returns the full input string.
Example:
assert '23:34:45.234'.all_after('.') == '234'
Example:
assert 'abcd'.all_after('z') == 'abcd'
all_after_last returns the contents after the last occurence of sub
in the string.
If the substring is not found, it returns the full input string.
Example:
assert '23:34:45.234'.all_after_last(':') == '45.234'
Example:
assert 'abcd'.all_after_last('z') == 'abcd'
all_after_first returns the contents after the first occurence of sub
in the string.
If the substring is not found, it returns the full input string.
Example:
assert '23:34:45.234'.all_after_first(':') == '34:45.234'
Example:
assert 'abcd'.all_after_first('z') == 'abcd'
after returns the contents after the last occurence of sub
in the string.
If the substring is not found, it returns the full input string.
Example:
assert '23:34:45.234'.after(':') == '45.234'
Example:
assert 'abcd'.after('z') == 'abcd'
TODO: deprecate either .all_after_last or .after
after_char returns the contents after the first occurence of sub
character in the string.
If the substring is not found, it returns the full input string.
Example:
assert '23:34:45.234'.after_char(`:`) == '34:45.234'
Example:
assert 'abcd'.after_char(`:`) == 'abcd'
limit returns a portion of the string, starting at 0
and extending for a given number of characters afterward.
'hello'.limit(2) => 'he' 'hi'.limit(10) => 'hi'
bytes returns the string converted to a byte array.
fields returns a string array of the string split by \t
and
Example:
assert '\t\tv = v'.fields() == ['v', '=', 'v']
Example:
assert ' sss ssss'.fields() == ['sss', 'ssss']
strip_margin allows multi-line strings to be formatted in a way that removes white-space before a delimeter. by default |
is used.
Note: the delimiter has to be a byte at this time. That means surrounding the value in ``.
See also: string.trim_indent()
Example:
st := 'Hello there, | this is a string, | Everything before the first | is removed'.strip_margin() assert st == 'Hello there, this is a string, Everything before the first | is removed'
strip_margin_custom does the same as strip_margin
but will use del
as delimiter instead of |
trim_indent detects a common minimal indent of all the input lines, removes it from every line and also removes the first and the last lines if they are blank (notice difference blank vs empty).
Note that blank lines do not affect the detected indent level.
In case if there are non-blank lines with no leading whitespace characters (no indent at all) then the common indent is 0, and therefore this function doesn't change the indentation.
Example:
st := ' Hello there, this is a string, all the leading indents are removed and also the first and the last lines if they are blank '.trim_indent() assert st == 'Hello there, this is a string, all the leading indents are removed and also the first and the last lines if they are blank'
indent_width returns the number of spaces or tabs at the beginning of the string.
Example:
assert ' v'.indent_width() == 2
Example:
assert '\t\tv'.indent_width() == 2
is_blank returns true if the string is empty or contains only white-space.
Example:
assert ' '.is_blank()
Example:
assert '\t'.is_blank()
Example:
assert 'v'.is_blank() == false
match_glob matches the string, with a Unix shell-style wildcard pattern.
Note: wildcard patterns are NOT the same as regular expressions.
They are much simpler, and do not allow backtracking, captures, etc.
The special characters used in shell-style wildcards are:
*
- matches everything ?
- matches any single character [seq]
- matches any of the characters in the sequence [^seq]
- matches any character that is NOT in the sequence Any other character in pattern
, is matched 1:1 to the corresponding character in name
, including / and .
You can wrap the meta-characters in brackets too, i.e. [?]
matches ?
in the string, and [*]
matches *
in the string.
Example:
assert 'ABCD'.match_glob('AB*')
Example:
assert 'ABCD'.match_glob('*D')
Example:
assert 'ABCD'.match_glob('*B*')
Example:
assert !'ABCD'.match_glob('AB')
is_ascii returns true if all characters belong to the US-ASCII set ([
..~
])
to_wide returns a pointer to an UTF-16 version of the string receiver.
In V, strings are encoded using UTF-8 internally, but on windows most APIs, that accept strings, need them to be in UTF-16 encoding.
The returned pointer of .to_wide(), has a type of &u16, and is suitable for passing to Windows APIs that expect LPWSTR or wchar_t* parameters.
See also MultiByteToWideChar ( https://learn.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-multibytetowidechar )
Convert utf8 to utf32 the original implementation did not check for valid utf8 in the string, and could result in values greater than the utf32 spec it has been replaced by utf8_to_utf32
which has an option return type.
this function is left for backward compatibility it is used in vlib/builtin/string.v, and also in vlib/v/gen/c/cgen.v
why does this exist?
fn (s &string) free()
unnecessary in the JS backend, implemented for api parity.
int returns the value of the string as an integer '1'.int() == 1
.
i64 returns the value of the string as i64 '1'.i64() == i64(1)
.
i8 returns the value of the string as i8 '1'.i8() == i8(1)
.
i16 returns the value of the string as i16 '1'.i16() == i16(1)
.
f32 returns the value of the string as f32 '1.0'.f32() == f32(1)
.
f64 returns the value of the string as f64 '1.0'.f64() == f64(1)
.
u16 returns the value of the string as u16 '1'.u16() == u16(1)
.
u32 returns the value of the string as u32 '1'.u32() == u32(1)
.
u64 returns the value of the string as u64 '1'.u64() == u64(1)
.
trim_right strips any of the characters given in cutset
from the right of the string.
Example:
assert ' Hello V d'.trim_right(' d') == ' Hello V'
trim_left strips any of the characters given in cutset
from the left of the string.
Example:
assert 'd Hello V developer'.trim_left(' d') == 'Hello V developer'
trim_string_left strips str
from the start of the string.
Example:
assert 'WorldHello V'.trim_string_left('World') == 'Hello V'
trim_string_right strips str
from the end of the string.
Example:
assert 'Hello VWorld'.trim_string_right('World') == 'Hello V'
#fn (string) trim_prefix
JavaScriptdeprecated:use s.trim_string_left(x) insteaddeprecated_after:2022-01-19
trim_prefix strips str
from the start of the string.
Example:
assert 'WorldHello V'.trim_prefix('World') == 'Hello V'
#fn (string) trim_suffix
JavaScriptdeprecated:use s.trim_string_right(x) insteaddeprecated_after:2022-01-19
trim_suffix strips str
from the end of the string.
Example:
assert 'Hello VWorld'.trim_suffix('World') == 'Hello V'
TODO: check if that behaves the same as V's own string.replace(old_sub,new_sub):
TODO: Make these functions actually work.
strip_margin allows multi-line strings to be formatted in a way that removes white-space before a delimeter. by default |
is used.
Note: the delimiter has to be a byte at this time. That means surrounding the value in ``.
Example:
st := 'Hello there, |this is a string, | Everything before the first | is removed'.strip_margin() Returns:
Hello there, this is a string, Everything before the first | is removed
strip_margin_custom does the same as strip_margin
but will use del
as delimiter instead of |
split_nth splits the string based on the passed delim
substring.
It returns the first Nth parts. When N=0, return all the splits.
The last returned element has the remainder of the string, even if the remainder contains more delim
substrings.
replace_each replaces all occurences of the string pairs given in vals
.
Example:
assert 'ABCD'.replace_each(['B','C/','C','D','D','C']) == 'AC/DC'
last_index returns the position of the last occurence of the input string.
last_index returns the position of the last occurence of the input string.
replace_once replaces the first occurence of rep
with the string passed in with
.
index_any returns the position of any of the characters in the input string - if found.
limit returns a portion of the string, starting at 0
and extending for a given number of characters afterward.
'hello'.limit(2) => 'he' 'hi'.limit(10) => 'hi'
is_title returns true if all words of the string is capitalized.
Example:
assert 'Hello V Developer'.is_title() == true
is_capital returns true
, if the first character in the string s
, is a capital letter, and the rest are NOT.
Example:
assert 'Hello'.is_capital() == true
Example:
assert 'HelloWorld'.is_capital() == false
starts_with_capital returns true
, if the first character in the string s
, is a capital letter, even if the rest are not.
Example:
assert 'Hello'.starts_with_capital() == true
Example:
assert 'Hello. World.'.starts_with_capital() == true
is_upper returns true
if all characters in the string is uppercase.
Example:
assert 'HELLO V'.is_upper() == true
is_upper returns true
if all characters in the string is uppercase.
Example:
assert 'HELLO V'.is_upper() == true
index returns the position of the first character of the input string.
It will return none
if the input string can't be found.
pub union StrIntpMem {
pub mut:
d_c u32
d_u8 byte
d_i8 i8
d_u16 u16
d_i16 i16
d_u32 u32
d_i32 int
d_u64 u64
d_i64 i64
d_f32 f32
d_f64 f64
d_s string
d_p voidptr
d_vp voidptr
}
Union data used by StrIntpData
storing struct used by cgen
pub struct StrIntpData {
pub:
str string
// fmt u64 // expanded version for future use, 64 bit
fmt u32
d StrIntpMem
}
NOTE: LOW LEVEL struct storing struct passed to V in the C code
fn (data &StrIntpData) process_str_intp_data(mut sb &strings.Builder)
convert from struct to formated string
str returns the Option type: ok, none, or error
pub struct JS.node_process {
pub:
arch string
argsv []string
env []string
platform string
version string
// TODO: add all properties
}
pub struct Promise[T] {
mut:
promise JS.Promise [noinit]
}
The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
catch method returns a Promise and deals with rejected cases only.
runes returns an array of all the utf runes in the string s
which is useful if you want random access to them
len_utf8 returns the number of runes contained in the string s
.
clone_static returns an independent copy of a given array.
It should be used only in -autofree generated code.
replace_once replaces the first occurence of rep
with the string passed in with
.
replace replaces all occurences of rep
with the string passed in with
.
replace_each replaces all occurences of the string pairs given in vals
.
Example:
assert 'ABCD'.replace_each(['B','C/','C','D','D','C']) == 'AC/DC'
replace_char replaces all occurences of the character rep
multiple occurences of the character passed in with
with respect to repeat
.
Example:
assert '\tHello!'.replace_char(`\t`,` `,8) == ' Hello!'
normalize_tabs replaces all tab characters with tab_len
amount of spaces
Example:
assert '\t\tpop rax\t; pop rax'.normalize_tabs(2) == ' pop rax ; pop rax'
bool returns true
if the string equals the word "true" it will return false
otherwise.
int returns the value of the string as an integer '1'.int() == 1
.
i64 returns the value of the string as i64 '1'.i64() == i64(1)
.
i8 returns the value of the string as i8 '1'.i8() == i8(1)
.
i16 returns the value of the string as i16 '1'.i16() == i16(1)
.
f32 returns the value of the string as f32 '1.0'.f32() == f32(1)
.
f64 returns the value of the string as f64 '1.0'.f64() == f64(1)
.
u8 returns the value of the string as u8 '1'.u8() == u8(1)
.
u16 returns the value of the string as u16 '1'.u16() == u16(1)
.
u32 returns the value of the string as u32 '1'.u32() == u32(1)
.
u64 returns the value of the string as u64 '1'.u64() == u64(1)
.
parse_uint is like parse_int
but for unsigned numbers
This method directly exposes the parse_uint
function from strconv
as a method on string
. For more advanced features, consider calling strconv.common_parse_uint
directly.
parse_int interprets a string s in the given base (0, 2 to 36) and bit size (0 to 64) and returns the corresponding value i.
If the base argument is 0, the true base is implied by the string's prefix: 2 for "0b", 8 for "0" or "0o", 16 for "0x", and 10 otherwise.
Also, for argument base 0 only, underscore characters are permitted as defined by the Go syntax for integer literals.
The bitSize argument specifies the integer type that the result must fit into. Bit sizes 0, 8, 16, 32, and 64 correspond to int, int8, int16, int32, and int64.
If bitSize is below 0 or above 64, an error is returned.
This method directly exposes the parse_int
function from strconv
as a method on string
. For more advanced features, consider calling strconv.common_parse_int
directly.
compare returns -1 if s
< a
, 0 if s
== a
, and 1 if s
> a
rsplit_any splits the string to an array by any of the delim
chars in reverse order.
Example:
"first row\nsecond row".rsplit_any(" \n") == ['row', 'second', 'row', 'first']
Split a string using the chars in the delimiter string as delimiters chars.
If the delimiter string is empty then rsplit
is used.
split splits the string to an array by delim
.
Example:
assert 'A B C'.split(' ') == ['A','B','C']
If delim
is empty the string is split by it's characters.
Example:
assert 'DEF'.split('') == ['D','E','F']
rsplit splits the string to an array by delim
in reverse order.
Example:
assert 'A B C'.rsplit(' ') == ['C','B','A']
If delim
is empty the string is split by it's characters.
Example:
assert 'DEF'.rsplit('') == ['F','E','D']
split_once devides string into pair of string by delim
.
Example:
path, ext := 'file.ts.dts'.splice_once('.')? assert path == 'file' assert ext == 'ts.dts'
Note that rsplit_once returns splitted string string as first part of pair, and returns remaining as second part of pair.
rsplit_once devides string into pair of string by delim
.
Example:
path, ext := 'file.ts.dts'.splice_once('.')? assert path == 'file.ts' assert ext == 'dts'
Note that rsplit_once returns remaining string as first part of pair, and returns splitted string as second part of pair.
split_nth splits the string based on the passed delim
substring.
It returns the first Nth parts. When N=0, return all the splits.
The last returned element has the remainder of the string, even if the remainder contains more delim
substrings.
rsplit_nth splits the string based on the passed delim
substring in revese order.
It returns the first Nth parts. When N=0, return all the splits.
The last returned element has the remainder of the string, even if the remainder contains more delim
substrings.
split_into_lines splits the string by newline characters.
newlines are stripped.
\r
(MacOS), \n
(POSIX), and \r\n
(WinOS) line endings are all supported (including mixed line endings).
NOTE: algorithm is "greedy", consuming '\r\n' as a single line ending with higher priority than '\r' and '\n' as multiple endings
used internally for [2..4]
substr returns the string between index positions start
and end
.
Example:
assert 'ABCD'.substr(1,3) == 'BC'
version of substr
that is used in a[start..end] or {
return an error when the index is out of range
substr_ni returns the string between index positions start
and end
allowing negative indexes This function always return a valid string.
index returns the position of the first character of the input string.
It will return -1
if the input string can't be found.
index returns the position of the first character of the input string.
It will return none
if the input string can't be found.
index_kmp does KMP search.
index_any returns the position of any of the characters in the input string - if found.
last_index returns the position of the last occurence of the input string.
last_index returns the position of the last occurence of the input string.
index_after returns the position of the input string, starting search from start
position.
index_u8 returns the index of byte c
if found in the string.
index_u8 returns -1 if the byte can not be found.
last_index_byte returns the index of the last occurence of byte c
if found in the string.
last_index_byte returns -1 if the byte is not found.
contains_u8 returns true
if the string contains the byte value x
.
See also: string.index_u8
, to get the index of the byte as well.
contains returns true
if the string contains substr
.
See also: string.index
contains_any returns true
if the string contains any chars in chars
.
contains_only returns true
, if the string contains only the characters in chars
.
contains_any_substr returns true
if the string contains any of the strings in substrs
.
starts_with returns true
if the string starts with p
.
ends_with returns true
if the string ends with p
.
to_lower returns the string in all lowercase characters.
TODO only works with ASCII
is_lower returns true
if all characters in the string is lowercase.
Example:
assert 'hello developer'.is_lower() == true
to_upper returns the string in all uppercase characters.
Example:
assert 'Hello V'.to_upper() == 'HELLO V'
is_upper returns true
if all characters in the string is uppercase.
See also: byte.is_capital
Example:
assert 'HELLO V'.is_upper() == true
capitalize returns the string with the first character capitalized.
Example:
assert 'hello'.capitalize() == 'Hello'
is_capital returns true
, if the first character in the string s
, is a capital letter, and the rest are NOT.
Example:
assert 'Hello'.is_capital() == true
Example:
assert 'HelloWorld'.is_capital() == false
starts_with_capital returns true
, if the first character in the string s
, is a capital letter, even if the rest are not.
Example:
assert 'Hello'.starts_with_capital() == true
Example:
assert 'Hello. World.'.starts_with_capital() == true
title returns the string with each word capitalized.
Example:
assert 'hello v developer'.title() == 'Hello V Developer'
is_title returns true if all words of the string are capitalized.
Example:
assert 'Hello V Developer'.is_title() == true
find_between returns the string found between start
string and end
string.
Example:
assert 'hey [man] how you doin'.find_between('[', ']') == 'man'
trim_space strips any of
, \n
, \t
, \v
, \f
, \r
from the start and end of the string.
Example:
assert ' Hello V '.trim_space() == 'Hello V'
trim strips any of the characters given in cutset
from the start and end of the string.
Example:
assert ' ffHello V ffff'.trim(' f') == 'Hello V'
trim_indexes gets the new start and end indicies of a string when any of the characters given in cutset
were stripped from the start and end of the string. Should be used as an input to substr
. If the string contains only the characters in cutset
, both values returned are zero.
Example:
left, right := '-hi-'.trim_indexes('-')
trim_left strips any of the characters given in cutset
from the left of the string.
Example:
assert 'd Hello V developer'.trim_left(' d') == 'Hello V developer'
trim_right strips any of the characters given in cutset
from the right of the string.
Example:
assert ' Hello V d'.trim_right(' d') == ' Hello V'
trim_string_left strips str
from the start of the string.
Example:
assert 'WorldHello V'.trim_string_left('World') == 'Hello V'
trim_string_right strips str
from the end of the string.
Example:
assert 'Hello VWorld'.trim_string_right('World') == 'Hello V'
trim_prefix strips str
from the start of the string.
Example:
assert 'WorldHello V'.trim_prefix('World') == 'Hello V'
trim_suffix strips str
from the end of the string.
Example:
assert 'Hello VWorld'.trim_suffix('World') == 'Hello V'
version of at
that is used in a[i] or {
return an error when the index is out of range
before returns the contents before sub
in the string.
If the substring is not found, it returns the full input string.
Example:
assert '23:34:45.234'.before('.') == '23:34:45'
Example:
assert 'abcd'.before('.') == 'abcd'
TODO: deprecate and remove either .before or .all_before
all_before returns the contents before sub
in the string.
If the substring is not found, it returns the full input string.
Example:
assert '23:34:45.234'.all_before('.') == '23:34:45'
Example:
assert 'abcd'.all_before('.') == 'abcd'
all_before_last returns the contents before the last occurence of sub
in the string.
If the substring is not found, it returns the full input string.
Example:
assert '23:34:45.234'.all_before_last(':') == '23:34'
Example:
assert 'abcd'.all_before_last('.') == 'abcd'
all_after returns the contents after sub
in the string.
If the substring is not found, it returns the full input string.
Example:
assert '23:34:45.234'.all_after('.') == '234'
Example:
assert 'abcd'.all_after('z') == 'abcd'
all_after_last returns the contents after the last occurence of sub
in the string.
If the substring is not found, it returns the full input string.
Example:
assert '23:34:45.234'.all_after_last(':') == '45.234'
Example:
assert 'abcd'.all_after_last('z') == 'abcd'
all_after_first returns the contents after the first occurence of sub
in the string.
If the substring is not found, it returns the full input string.
Example:
assert '23:34:45.234'.all_after_first(':') == '34:45.234'
Example:
assert 'abcd'.all_after_first('z') == 'abcd'
after returns the contents after the last occurence of sub
in the string.
If the substring is not found, it returns the full input string.
Example:
assert '23:34:45.234'.after(':') == '45.234'
Example:
assert 'abcd'.after('z') == 'abcd'
TODO: deprecate either .all_after_last or .after
after_char returns the contents after the first occurence of sub
character in the string.
If the substring is not found, it returns the full input string.
Example:
assert '23:34:45.234'.after_char(`:`) == '34:45.234'
Example:
assert 'abcd'.after_char(`:`) == 'abcd'
limit returns a portion of the string, starting at 0
and extending for a given number of characters afterward.
'hello'.limit(2) => 'he' 'hi'.limit(10) => 'hi'
bytes returns the string converted to a byte array.
fields returns a string array of the string split by \t
and
Example:
assert '\t\tv = v'.fields() == ['v', '=', 'v']
Example:
assert ' sss ssss'.fields() == ['sss', 'ssss']
strip_margin allows multi-line strings to be formatted in a way that removes white-space before a delimeter. by default |
is used.
Note: the delimiter has to be a byte at this time. That means surrounding the value in ``.
See also: string.trim_indent()
Example:
st := 'Hello there, | this is a string, | Everything before the first | is removed'.strip_margin() assert st == 'Hello there, this is a string, Everything before the first | is removed'
strip_margin_custom does the same as strip_margin
but will use del
as delimiter instead of |
trim_indent detects a common minimal indent of all the input lines, removes it from every line and also removes the first and the last lines if they are blank (notice difference blank vs empty).
Note that blank lines do not affect the detected indent level.
In case if there are non-blank lines with no leading whitespace characters (no indent at all) then the common indent is 0, and therefore this function doesn't change the indentation.
Example:
st := ' Hello there, this is a string, all the leading indents are removed and also the first and the last lines if they are blank '.trim_indent() assert st == 'Hello there, this is a string, all the leading indents are removed and also the first and the last lines if they are blank'
indent_width returns the number of spaces or tabs at the beginning of the string.
Example:
assert ' v'.indent_width() == 2
Example:
assert '\t\tv'.indent_width() == 2
is_blank returns true if the string is empty or contains only white-space.
Example:
assert ' '.is_blank()
Example:
assert '\t'.is_blank()
Example:
assert 'v'.is_blank() == false
match_glob matches the string, with a Unix shell-style wildcard pattern.
Note: wildcard patterns are NOT the same as regular expressions.
They are much simpler, and do not allow backtracking, captures, etc.
The special characters used in shell-style wildcards are:
*
- matches everything ?
- matches any single character [seq]
- matches any of the characters in the sequence [^seq]
- matches any character that is NOT in the sequence Any other character in pattern
, is matched 1:1 to the corresponding character in name
, including / and .
You can wrap the meta-characters in brackets too, i.e. [?]
matches ?
in the string, and [*]
matches *
in the string.
Example:
assert 'ABCD'.match_glob('AB*')
Example:
assert 'ABCD'.match_glob('*D')
Example:
assert 'ABCD'.match_glob('*B*')
Example:
assert !'ABCD'.match_glob('AB')
is_ascii returns true if all characters belong to the US-ASCII set ([
..~
])
to_wide returns a pointer to an UTF-16 version of the string receiver.
In V, strings are encoded using UTF-8 internally, but on windows most APIs, that accept strings, need them to be in UTF-16 encoding.
The returned pointer of .to_wide(), has a type of &u16, and is suitable for passing to Windows APIs that expect LPWSTR or wchar_t* parameters.
See also MultiByteToWideChar ( https://learn.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-multibytetowidechar )
Convert utf8 to utf32 the original implementation did not check for valid utf8 in the string, and could result in values greater than the utf32 spec it has been replaced by utf8_to_utf32
which has an option return type.
this function is left for backward compatibility it is used in vlib/builtin/string.v, and also in vlib/v/gen/c/cgen.v
why does this exist?
fn (s &string) free()
unnecessary in the JS backend, implemented for api parity.
int returns the value of the string as an integer '1'.int() == 1
.
i64 returns the value of the string as i64 '1'.i64() == i64(1)
.
i8 returns the value of the string as i8 '1'.i8() == i8(1)
.
i16 returns the value of the string as i16 '1'.i16() == i16(1)
.
f32 returns the value of the string as f32 '1.0'.f32() == f32(1)
.
f64 returns the value of the string as f64 '1.0'.f64() == f64(1)
.
u16 returns the value of the string as u16 '1'.u16() == u16(1)
.
u32 returns the value of the string as u32 '1'.u32() == u32(1)
.
u64 returns the value of the string as u64 '1'.u64() == u64(1)
.
trim_right strips any of the characters given in cutset
from the right of the string.
Example:
assert ' Hello V d'.trim_right(' d') == ' Hello V'
trim_left strips any of the characters given in cutset
from the left of the string.
Example:
assert 'd Hello V developer'.trim_left(' d') == 'Hello V developer'
trim_string_left strips str
from the start of the string.
Example:
assert 'WorldHello V'.trim_string_left('World') == 'Hello V'
trim_string_right strips str
from the end of the string.
Example:
assert 'Hello VWorld'.trim_string_right('World') == 'Hello V'
#fn (string) trim_prefix
JavaScriptdeprecated:use s.trim_string_left(x) insteaddeprecated_after:2022-01-19
trim_prefix strips str
from the start of the string.
Example:
assert 'WorldHello V'.trim_prefix('World') == 'Hello V'
#fn (string) trim_suffix
JavaScriptdeprecated:use s.trim_string_right(x) insteaddeprecated_after:2022-01-19
trim_suffix strips str
from the end of the string.
Example:
assert 'Hello VWorld'.trim_suffix('World') == 'Hello V'
TODO: check if that behaves the same as V's own string.replace(old_sub,new_sub):
TODO: Make these functions actually work.
strip_margin allows multi-line strings to be formatted in a way that removes white-space before a delimeter. by default |
is used.
Note: the delimiter has to be a byte at this time. That means surrounding the value in ``.
Example:
st := 'Hello there, |this is a string, | Everything before the first | is removed'.strip_margin() Returns:
Hello there, this is a string, Everything before the first | is removed
strip_margin_custom does the same as strip_margin
but will use del
as delimiter instead of |
split_nth splits the string based on the passed delim
substring.
It returns the first Nth parts. When N=0, return all the splits.
The last returned element has the remainder of the string, even if the remainder contains more delim
substrings.
replace_each replaces all occurences of the string pairs given in vals
.
Example:
assert 'ABCD'.replace_each(['B','C/','C','D','D','C']) == 'AC/DC'
last_index returns the position of the last occurence of the input string.
last_index returns the position of the last occurence of the input string.
replace_once replaces the first occurence of rep
with the string passed in with
.
index_any returns the position of any of the characters in the input string - if found.
limit returns a portion of the string, starting at 0
and extending for a given number of characters afterward.
'hello'.limit(2) => 'he' 'hi'.limit(10) => 'hi'
is_title returns true if all words of the string is capitalized.
Example:
assert 'Hello V Developer'.is_title() == true
is_capital returns true
, if the first character in the string s
, is a capital letter, and the rest are NOT.
Example:
assert 'Hello'.is_capital() == true
Example:
assert 'HelloWorld'.is_capital() == false
starts_with_capital returns true
, if the first character in the string s
, is a capital letter, even if the rest are not.
Example:
assert 'Hello'.starts_with_capital() == true
Example:
assert 'Hello. World.'.starts_with_capital() == true
is_upper returns true
if all characters in the string is uppercase.
Example:
assert 'HELLO V'.is_upper() == true
is_upper returns true
if all characters in the string is uppercase.
Example:
assert 'HELLO V'.is_upper() == true
index returns the position of the first character of the input string.
It will return none
if the input string can't be found.
Private function. Increases the cap
of an array to the required value by copying the data to a new memory location (creating a clone) unless a.cap
is already large enough.
repeat returns a new array with the given array elements repeated given times.
cgen
will replace this with an apropriate call to repeat_to_depth
This is a dummy placeholder that will be overridden by cgen
with an appropriate call to repeat_to_depth
. However the checker
needs it here.
repeat_to_depth is an unsafe version of repeat
that handles multi-dimensional arrays.
It is unsafe
to call directly because depth
is not checked
insert inserts a value in the array at index i
and increases the index of subsequent elements by 1.
This function is type-aware and can insert items of the same or lower dimensionality as the original array. That is, if the original array is []int
, then the insert val
may be int
or []int
. If the original array is [][]int
, then val
may be []int
or [][]int
. Consider the examples.
Example:
mut a := [1, 2, 4] a.insert(2, 3) // a now is [1, 2, 3, 4] mut b := [3, 4] b.insert(0, [1, 2]) // b now is [1, 2, 3, 4] mut c := [[3, 4]] c.insert(0, [1, 2]) // c now is [[1, 2], [3, 4]]
insert_many is used internally to implement inserting many values into an the array beginning at i
.
prepend prepends one or more elements to an array.
It is shorthand for .insert(0, val)
prepend_many prepends another array to this array.
NOTE: prepend
is probably all you need.
NOTE: This code is never called in all of vlib
delete deletes array element at index i
.
This is exactly the same as calling .delete_many(i, 1)
.
NOTE: This function does NOT operate in-place. Internally, it creates a copy of the array, skipping over the element at i
, and then points the original variable to the new memory location.
Example:
mut a := ['0', '1', '2', '3', '4', '5'] a.delete(1) // a is now ['0', '2', '3', '4', '5']
delete_many deletes size
elements beginning with index i
NOTE: This function does NOT operate in-place. Internally, it creates a copy of the array, skipping over size
elements starting at i
, and then points the original variable to the new memory location.
Example:
mut a := [1, 2, 3, 4, 5, 6, 7, 8, 9] b := a[..9] // creates a <code>[slice](/standard_library/builtin.html#array_slice)</code> of `a`, not a clone a.delete_many(4, 3) // replaces `a` with a modified clone dump(a) // a: [1, 2, 3, 4, 8, 9] // `a` is now different dump(b) // b: [1, 2, 3, 4, 5, 6, 7, 8, 9] // `b` is still the same
fn (mut a &array) clear()
clear clears the array without deallocating the allocated data.
It does it by setting the array length to 0
Example:
a.clear() // `a.len` is now 0
drop advances the array past the first num
elements whilst preserving spare capacity.
If num
is greater than len
the array will be emptied.
Example:
mut a := [1,2] a << 3 a.drop(2) assert a == [3] assert a.cap > a.len
we manually inline this for single operations for performance without -prod
Private function. Used to implement array[] operator.
Private function. Used to implement x = a[i] or { ... }
pop returns the last element of the array, and removes it.
If the array
is empty, this will panic.
NOTE: this function reduces the length of the given array, but arrays sliced from this one will not change. They still retain their "view" of the underlying memory.
Example:
mut a := [1, 2, 3, 4, 5, 6, 7, 8, 9] b := a[..9] // creates a "view" into the same memory c := a.pop() // c == 9 a[1] = 5 dump(a) // a: [1, 5, 3, 4, 5, 6, 7, 8] dump(b) // b: [1, 5, 3, 4, 5, 6, 7, 8, 9]
fn (mut a &array) delete_last()
delete_last efficiently deletes the last element of the array.
It does it simply by reducing the length of the array by 1.
If the array is empty, this will panic.
See also: trim
slice returns an array using the same buffer as original array but starting from the start
element and ending with the element before the end
element of the original array with the length and capacity set to the number of the elements in the slice.
It will remain tied to the same memory location until the length increases (copy on grow) or clone
is called on it.
If start
and end
are invalid this function will panic.
Alternative: Slices can also be made with [start..end] notation Alternative: slice_ni
will always return an array.
slice_ni returns an array using the same buffer as original array but starting from the start
element and ending with the element before the end
element of the original array.
This function can use negative indexes a.slice_ni(-3, a.len)
that get the last 3 elements of the array otherwise it return an empty array.
This function always return a valid array.
used internally for [2..4]
clone_static_to_depth() returns an independent copy of a given array.
Unlike clone_to_depth
it has a value receiver and is used internally for slice-clone expressions like a[2..4].clone()
and in -autofree generated code.
clone returns an independent copy of a given array.
this will be overwritten by cgen
with an apropriate call to clone_to_depth
However the checker
needs it here.
recursively clone given array - unsafe
when called directly because depth is not checked
we manually inline this for single operations for performance without -prod
Private function. Used to implement assignment to the array element.
push_many implements the functionality for pushing another array.
val
is array.data and user facing usage is a << [1,2,3]
fn (mut a &array) reverse_in_place()
reverse_in_place reverses existing array data, modifying original array.
reverse returns a new array with the elements of the original array in reverse order.
filter creates a new array with all elements that pass the test.
Ignore the function signature. filter
does not take an actual callback. Rather, it takes an it
expression.
Certain array functions (filter
any
all
) support a simplified domain-specific-language by the backend compiler to make these operations more idiomatic to V. These functions are described here, but their implementation is compiler specific.
Each function takes a boolean test expression as its single argument.
These test expressions may use it
as a pointer to a single element at a time.
Example:
array.filter(it < 5) // create an array of elements less than 5
Example:
array.filter(it % 2 == 1) // create an array of only odd elements
Example:
array.filter(it.name[0] == `A`) // create an array of elements whose `name` field starts with 'A'
any tests whether at least one element in the array passes the test.
Ignore the function signature. any
does not take an actual callback. Rather, it takes an it
expression.
It returns true
if it finds an element passing the test. Otherwise, it returns false
. It doesn't modify the array.
Example:
array.any(it % 2 == 1) // will return true if any element is odd
Example:
array.any(it.name == 'Bob') // will yield `true` if any element has `.name == 'Bob'
all tests whether all elements in the array pass the test.
Ignore the function signature. all
does not take an actual callback. Rather, it takes an it
expression.
It returns false
if any element fails the test. Otherwise, it returns true
. It doesn't modify the array.
Example:
array.all(it % 2 == 1) // will return true if every element is odd
map creates a new array populated with the results of calling a provided function on every element in the calling array.
It also accepts an it
expression.
Example:
words := ['hello', 'world'] r1 := words.map(it.to_upper()) assert r1 == ['HELLO', 'WORLD'] // map can also accept anonymous functions r2 := words.map(fn (w string) string { return w.to_upper() }) assert r2 == ['HELLO', 'WORLD']
sort sorts the array in place.
Ignore the function signature. Passing a callback to sort
is not supported for now. Consider using the sort_with_compare
method if you need it.
sort can take a boolean test expression as its single argument.
The expression uses 2 'magic' variables a
and b
as pointers to the two elements being compared.
Example:
array.sort() // will sort the array in ascending order
Example:
array.sort(b < a) // will sort the array in decending order
Example:
array.sort(b.name < a.name) // will sort descending by the .name field
sort_with_compare sorts the array in-place using the results of the given function to determine sort order.
The function should return one of three values:
-1
whena
should come beforeb
(a < b
)1
whenb
should come beforea
(b < a
)0
when the order cannot be determined (a == b
)
Example:
fn main() { mut a := ['hi', '1', '5', '3'] a.sort_with_compare(fn (a &string, b &string) int { if a < b { return -1 } if a > b { return 1 } return 0 }) assert a == ['1', '3', '5', 'hi'] }
index returns the first index at which a given element can be found in the array or -1
if the value is not found.
grow_cap grows the array's capacity by amount
elements.
Internally, it does this by copying the entire array to a new memory location (creating a clone).
grow_len ensures that an array has a.len + amount of length Internally, it does this by copying the entire array to a new memory location (creating a clone) unless the array.cap is already large enough.
pointers returns a new array, where each element is the address of the corresponding element in the array.
Private function. Doubles array capacity if needed.
version of repeat
that handles multi dimensional arrays unsafe
to call directly because depth
is not checked
insert inserts a value in the array at index i
insert_many inserts many values into the array from index i
.
prepend prepends one value to the array.
prepend_many prepends another array to this array.
pop returns the last element of the array, and removes it.
clone_static_to_depth_noscan
returns an independent copy of a given array.
Unlike clone_to_depth_noscan
it has a value receiver and is used internally for slice-clone expressions like a[2..4].clone()
and in -autofree generated code.
recursively clone given array - unsafe
when called directly because depth is not checked
push_many implements the functionality for pushing another array.
val
is array.data and user facing usage is a << [1,2,3]
reverse returns a new array with the elements of the original array in reverse order.
grow_cap grows the array's capacity by amount
elements.
grow_len ensures that an array has a.len + amount of length
trim trims the array length to "index" without modifying the allocated data. If "index" is greater than len nothing will be changed.
last returns the last element of the array.
delete deletes array element at index i
.
delete_many deletes size
elements beginning with index i
prepend prepends one value to the array.
prepend_many prepends another array to this array.
reduce executes a given reducer function on each element of the array, resulting in a single output value.
fn (mut a &array) delete_last()
delete_last effectively removes last element of an array.
todo: once (a []u8) will work rewrite this
Private function. Used to implement array[] operator
Private function. Used to implement assignment to the array element.
array.repeat returns new array with the given array elements repeated nr_repeat
times
runes returns an array of all the utf runes in the string s
which is useful if you want random access to them
len_utf8 returns the number of runes contained in the string s
.
clone_static returns an independent copy of a given array.
It should be used only in -autofree generated code.
replace_once replaces the first occurence of rep
with the string passed in with
.
replace replaces all occurences of rep
with the string passed in with
.
replace_each replaces all occurences of the string pairs given in vals
.
Example:
assert 'ABCD'.replace_each(['B','C/','C','D','D','C']) == 'AC/DC'
replace_char replaces all occurences of the character rep
multiple occurences of the character passed in with
with respect to repeat
.
Example:
assert '\tHello!'.replace_char(`\t`,` `,8) == ' Hello!'
normalize_tabs replaces all tab characters with tab_len
amount of spaces
Example:
assert '\t\tpop rax\t; pop rax'.normalize_tabs(2) == ' pop rax ; pop rax'
bool returns true
if the string equals the word "true" it will return false
otherwise.
int returns the value of the string as an integer '1'.int() == 1
.
i64 returns the value of the string as i64 '1'.i64() == i64(1)
.
i8 returns the value of the string as i8 '1'.i8() == i8(1)
.
i16 returns the value of the string as i16 '1'.i16() == i16(1)
.
f32 returns the value of the string as f32 '1.0'.f32() == f32(1)
.
f64 returns the value of the string as f64 '1.0'.f64() == f64(1)
.
u8 returns the value of the string as u8 '1'.u8() == u8(1)
.
u16 returns the value of the string as u16 '1'.u16() == u16(1)
.
u32 returns the value of the string as u32 '1'.u32() == u32(1)
.
u64 returns the value of the string as u64 '1'.u64() == u64(1)
.
parse_uint is like parse_int
but for unsigned numbers
This method directly exposes the parse_uint
function from strconv
as a method on string
. For more advanced features, consider calling strconv.common_parse_uint
directly.
parse_int interprets a string s in the given base (0, 2 to 36) and bit size (0 to 64) and returns the corresponding value i.
If the base argument is 0, the true base is implied by the string's prefix: 2 for "0b", 8 for "0" or "0o", 16 for "0x", and 10 otherwise.
Also, for argument base 0 only, underscore characters are permitted as defined by the Go syntax for integer literals.
The bitSize argument specifies the integer type that the result must fit into. Bit sizes 0, 8, 16, 32, and 64 correspond to int, int8, int16, int32, and int64.
If bitSize is below 0 or above 64, an error is returned.
This method directly exposes the parse_int
function from strconv
as a method on string
. For more advanced features, consider calling strconv.common_parse_int
directly.
compare returns -1 if s
< a
, 0 if s
== a
, and 1 if s
> a
rsplit_any splits the string to an array by any of the delim
chars in reverse order.
Example:
"first row\nsecond row".rsplit_any(" \n") == ['row', 'second', 'row', 'first']
Split a string using the chars in the delimiter string as delimiters chars.
If the delimiter string is empty then rsplit
is used.
split splits the string to an array by delim
.
Example:
assert 'A B C'.split(' ') == ['A','B','C']
If delim
is empty the string is split by it's characters.
Example:
assert 'DEF'.split('') == ['D','E','F']
rsplit splits the string to an array by delim
in reverse order.
Example:
assert 'A B C'.rsplit(' ') == ['C','B','A']
If delim
is empty the string is split by it's characters.
Example:
assert 'DEF'.rsplit('') == ['F','E','D']
split_once devides string into pair of string by delim
.
Example:
path, ext := 'file.ts.dts'.splice_once('.')? assert path == 'file' assert ext == 'ts.dts'
Note that rsplit_once returns splitted string string as first part of pair, and returns remaining as second part of pair.
rsplit_once devides string into pair of string by delim
.
Example:
path, ext := 'file.ts.dts'.splice_once('.')? assert path == 'file.ts' assert ext == 'dts'
Note that rsplit_once returns remaining string as first part of pair, and returns splitted string as second part of pair.
split_nth splits the string based on the passed delim
substring.
It returns the first Nth parts. When N=0, return all the splits.
The last returned element has the remainder of the string, even if the remainder contains more delim
substrings.
rsplit_nth splits the string based on the passed delim
substring in revese order.
It returns the first Nth parts. When N=0, return all the splits.
The last returned element has the remainder of the string, even if the remainder contains more delim
substrings.
split_into_lines splits the string by newline characters.
newlines are stripped.
\r
(MacOS), \n
(POSIX), and \r\n
(WinOS) line endings are all supported (including mixed line endings).
NOTE: algorithm is "greedy", consuming '\r\n' as a single line ending with higher priority than '\r' and '\n' as multiple endings
used internally for [2..4]
substr returns the string between index positions start
and end
.
Example:
assert 'ABCD'.substr(1,3) == 'BC'
version of substr
that is used in a[start..end] or {
return an error when the index is out of range
substr_ni returns the string between index positions start
and end
allowing negative indexes This function always return a valid string.
index returns the position of the first character of the input string.
It will return -1
if the input string can't be found.
index returns the position of the first character of the input string.
It will return none
if the input string can't be found.
index_kmp does KMP search.
index_any returns the position of any of the characters in the input string - if found.
last_index returns the position of the last occurence of the input string.
last_index returns the position of the last occurence of the input string.
index_after returns the position of the input string, starting search from start
position.
index_u8 returns the index of byte c
if found in the string.
index_u8 returns -1 if the byte can not be found.
last_index_byte returns the index of the last occurence of byte c
if found in the string.
last_index_byte returns -1 if the byte is not found.
contains_u8 returns true
if the string contains the byte value x
.
See also: string.index_u8
, to get the index of the byte as well.
contains returns true
if the string contains substr
.
See also: string.index
contains_any returns true
if the string contains any chars in chars
.
contains_only returns true
, if the string contains only the characters in chars
.
contains_any_substr returns true
if the string contains any of the strings in substrs
.
starts_with returns true
if the string starts with p
.
ends_with returns true
if the string ends with p
.
The consts here are utilities for the compiler's "auto_str_methods.v".
They are used to substitute old _STR calls.
FIXME: this const is not released from memory => use a precalculated string const for now.
si_s_code = "0x" + int(StrIntpType.si_s).hex() // code for a simple string.