compiler: deprecate isize and usize in favor of int and uint (#31113)

This commit is contained in:
Alexander Medvednikov authored and GitHub committed 2026-10-25 14:43:23 +03:00
1 parent 1f4d705322
commit fca9fad345
521 files changed
+3549 -2805

No files matched your search

+3 -1
View File
@@ -258,7 +258,9 @@ BOOTSTRAP_VFLAGS := $(BOOTSTRAP_CCOMPILER_VFLAG) $(if $(strip $(BOOTSTRAP_CFLAGS
all: latest_vc latest_tcc latest_legacy
ifdef WIN32
$(CC) $(CPPFLAGS) $(BOOTSTRAP_VC_CC_CFLAGS) $(VC_BOOTSTRAP_DEFINE) -std=c99 -municode -w -o v1$(EXE_EXT) $(VC)/$(VCFILE) $(LDFLAGS) -lws2_32 -lbcrypt || cmd/tools/cc_compilation_failed_windows.sh
powershell -NoProfile -ExecutionPolicy Bypass -File "$(VROOT)/cmd/tools/vc_compat_uint.ps1" -Source "$(VC)/$(VCFILE)" -Destination "$(VC)/v_win_compat.c"
$(CC) $(CPPFLAGS) $(BOOTSTRAP_VC_CC_CFLAGS) $(VC_BOOTSTRAP_DEFINE) -std=c99 -municode -w -o v1$(EXE_EXT) "$(VC)/v_win_compat.c" $(LDFLAGS) -lws2_32 -lbcrypt || cmd/tools/cc_compilation_failed_windows.sh
$(RM) "$(VC)/v_win_compat.c"
./v1$(EXE_EXT) -no-parallel -o v2$(EXE_EXT) $(BOOTSTRAP_GC_VFLAG) $(VFLAGS) $(BOOTSTRAP_VC_VFLAGS) cmd/v
./v2$(EXE_EXT) -o $(VEXE)$(EXE_EXT) $(BOOTSTRAP_GC_VFLAG) $(VFLAGS) $(BOOTSTRAP_VFLAGS) cmd/v
$(RM) v1$(EXE_EXT)
+4 -2
View File
@@ -98,10 +98,12 @@ That should be it, and you should find your V executable at `[path to V repo]/v`
On Unix-like systems, `make` and the `v self` bootstrap fallback stream compatibility fixes
for older `vc/v.c` snapshots to the C compiler. These match the peak RSS helper's return type
to `i64` and guard Linux-only `prctl` code. The snapshot stays unchanged on disk.
to `i64`, guard Linux-only `prctl` code, and teach pre-`uint` compilers the new integer
spelling and allocator signatures. The snapshot stays unchanged on disk.
The compatibility filter uses the system `sh`; Bash is not required.
On Windows, `makev.bat` generates the first compiler stage as C and links it directly.
On Windows, builds use PowerShell to prepare a temporary snapshot with the same integer
compatibility fixes. `makev.bat` generates the first compiler stage as C and links it directly.
This also works with older bootstrap snapshots whose process-spawn code is broken.
Direct TCC links add the installed bundle's `thirdparty\tcc\lib\openlibm.o`, when present,
for C99 math functions such as `remainder`. Each bundle ships this object for its own compiler,
+9
View File
@@ -29,6 +29,15 @@ def routine(name: str) -> str:
class BootstrapConfigurationTests(unittest.TestCase):
def test_bootstrap_prepares_a_temporary_uint_compatible_snapshot(self):
build = routine("build")
self.assertIn('vc_compat_uint.ps1" -Source "%V_C_FILE%"', build)
self.assertIn('if !ERRORLEVEL! NEQ 0 goto :error', build)
self.assertLess(build.index("vc_compat_uint.ps1"), build.index("echo Building V..."))
self.assertIn('set "V_C_FILE=%vc_dir%\\v_win_compat.c"', build)
for name in ("success", "error"):
self.assertIn('call :try_delete "%vc_dir%\\v_win_compat.c"', routine(name))
def test_all_portable_bootstraps_select_v1(self):
self.assertIn(
"set VC_BOOTSTRAP_DEFINE=-DCUSTOM_DEFINE_v1_fallback\n", SOURCE
+26
View File
@@ -1,4 +1,30 @@
# Keep the downloaded snapshot intact and stream compatibility fixes to the C compiler.
# Only the pre-uint compiler needs its primitive spelling updated. Check the
# compiler's type-ID declaration, not arbitrary strings or C qualifier IDs.
BEGIN {
while ((getline line < ARGV[1]) > 0) {
if (line ~ /^u32 flat__source_type_usize;$/) legacy_uint = 1
if (line ~ /^u32 flat__source_type_uint;$/) native_uint = 1
if (line ~ /^_SL\([^,]+, "(u8\* malloc_noscan\(ptrdiff_t n\);|void\* memdup\(void\* src, ptrdiff_t sz\);|void\* memdup_align\(void\* src, ptrdiff_t sz, ptrdiff_t alignment\);)",/) {
id = line
sub(/^_SL\(/, "", id)
sub(/,.*/, "", id)
allocator_prototypes[id] = 1
}
}
close(ARGV[1])
}
legacy_uint && !native_uint {
gsub(/"usize", 5/, "\"uint\", 4")
# The migrated allocator declarations use int. Rewrite their codegen calls
# using the selected target type, without changing the snapshot's own ABI.
for (id in allocator_prototypes) {
sub("c__FlatGen__writeln\\(g, " id "\\);",
"c__FlatGen__writeln(g, string__replace(" id ", (string){(u8*)\"ptrdiff_t\", 9, 1}, g->int_ct));")
}
}
# Older portable snapshots return long long here but declare the function as i64.
# On Linux, i64 is int64_t (long), which conflicts even though both types are 64-bit.
/^(V_PEAK_RSS_SCOPE|static|static inline) long long v3_bench_peak_rss_kb\(void\)[ \t]*\{/ {
+40
View File
@@ -190,3 +190,43 @@ fn test_vc_compat_links_libraries_after_the_streamed_source() ! {
ran := os.exec([executable])
assert ran.exit_code == 0, ran.output
}
fn test_vc_compat_bridges_only_snapshots_without_native_uint() ! {
root := os.join_path(os.vtmp_dir(), 'vc_compat_uint_${os.getpid()}')
os.mkdir_all(root)!
defer { os.rmdir_all(root) or {} }
source := os.join_path(root, 'snapshot with spaces.c')
output := os.join_path(root, 'filtered.c')
// C qualifier metadata already mentioned uint in old snapshots. It does
// not mean the compiler recognizes it as a V primitive.
legacy := 'u32 flat__source_type_usize;\nu32 types__qualify_source_type_uint;\n_SL(name, "usize", 5);\nconst string casts[] = {(string){"usize", 5, 1}};\nu8* malloc_noscan(ptrdiff_t n);\n_SL(alloc, "u8* malloc_noscan(ptrdiff_t n);", 31);\n_SL(copy, "void* memdup(void* src, ptrdiff_t sz);", 38);\n_SL(align, "void* memdup_align(void* src, ptrdiff_t sz, ptrdiff_t alignment);", 65);\nc__FlatGen__writeln(g, alloc);\nc__FlatGen__writeln(g, copy);\nc__FlatGen__writeln(g, align);\nconst char* embedded = "\\\"usize\\\", 5";\n'
bytes := [u8(0xff), u8(0xfe)].bytestr()
for declarations in ['', 'u32 flat__source_type_uint;\n'] {
original := declarations + legacy + 'const char* binary = "${bytes}";\n'
os.write_file(source, original)!
mut filtered := ''
$if windows {
checked := os.exec(['powershell', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File',
os.join_path(@VEXEROOT, 'cmd', 'tools', 'vc_compat_uint.ps1'), '-Source', source,
'-Destination', output])
assert checked.exit_code == 0, checked.output
filtered = os.read_file(output)!
} $else {
_ = output
checked := os.exec(['env', 'LC_ALL=C', 'awk', '-f',
os.join_path(@VEXEROOT, 'cmd', 'tools', 'vc_compat.awk'), source])
assert checked.exit_code == 0, checked.output
filtered = checked.output
}
expected := if declarations == '' {
original.replace('"usize", 5', '"uint", 4')
.replace('c__FlatGen__writeln(g, alloc);', 'c__FlatGen__writeln(g, string__replace(alloc, (string){(u8*)"ptrdiff_t", 9, 1}, g->int_ct));')
.replace('c__FlatGen__writeln(g, copy);', 'c__FlatGen__writeln(g, string__replace(copy, (string){(u8*)"ptrdiff_t", 9, 1}, g->int_ct));')
.replace('c__FlatGen__writeln(g, align);', 'c__FlatGen__writeln(g, string__replace(align, (string){(u8*)"ptrdiff_t", 9, 1}, g->int_ct));')
} else {
original
}
assert filtered == expected
assert os.read_file(source)! == original
}
}
+21
View File
@@ -0,0 +1,21 @@
# Keep downloaded snapshots intact, including string literals with non-UTF-8 bytes.
param(
[Parameter(Mandatory = $true)][string]$Source,
[Parameter(Mandatory = $true)][string]$Destination
)
$ErrorActionPreference = 'Stop'
$encoding = [Text.Encoding]::GetEncoding(28591)
$text = [IO.File]::ReadAllText($Source, $encoding)
if ($text -match '(?m)^u32 flat__source_type_usize;\r?$' -and
$text -notmatch '(?m)^u32 flat__source_type_uint;\r?$') {
$text = $text.Replace('"usize", 5', '"uint", 4')
# Rewrite codegen calls using the selected target's integer type. The
# snapshot's interned strings and its own allocator ABI remain unchanged.
$prototypes = '(?m)^_SL\(([^,]+), "(?:u8\* malloc_noscan\(ptrdiff_t n\);|void\* memdup\(void\* src, ptrdiff_t sz\);|void\* memdup_align\(void\* src, ptrdiff_t sz, ptrdiff_t alignment\);)",'
foreach ($match in [regex]::Matches($text, $prototypes)) {
$id = $match.Groups[1].Value
$text = $text.Replace("c__FlatGen__writeln(g, $id);",
('c__FlatGen__writeln(g, string__replace(' + $id + ', (string){(u8*)"ptrdiff_t", 9, 1}, g->int_ct));'))
}
}
[IO.File]::WriteAllText($Destination, $text, $encoding)
+1 -1
View File
@@ -44,7 +44,7 @@ fn test_file_for(source string) string {
fn zero_value_for(typ string) ?string {
t := typ.trim_space()
if t in ['int', 'i8', 'i16', 'i32', 'i64', 'u8', 'u16', 'u32', 'u64', 'byte', 'rune', 'isize',
'usize'] {
'uint', 'usize'] {
return '0'
}
if t in ['f32', 'f64'] {
+2 -2
View File
@@ -1214,11 +1214,11 @@ fn test_fmt_preserves_legacy_dollar_builtins_with_v3() {
}
fn test_fmt_preserves_bodyless_function_prefixes_with_v3() {
source := 'fn plain(value usize) usize\nfn C.c_call(value int) int\nfn JS.js_call(value int) int\n'
source := 'fn plain(value uint) uint\nfn C.c_call(value int) int\nfn JS.js_call(value int) int\n'
res, formatted := run_vfmt_write('bodyless_function_prefixes', source, '')
assert res.exit_code == 0, res.output
assert formatted.contains('fn plain(value usize) usize'), formatted
assert formatted.contains('fn plain(value uint) uint'), formatted
assert formatted.contains('fn C.c_call(value int) int'), formatted
assert formatted.contains('fn JS.js_call(value int) int'), formatted
assert !formatted.contains('fn C.plain'), formatted
+1 -1
View File
@@ -226,7 +226,7 @@ pub fn map_entry_read_fn_name(v_name string, field string) string {
pub fn zero_value(v_type string) string {
return match v_type {
'i8', 'i16', 'int', 'i32', 'i64', 'u8', 'u16', 'u32', 'u64', 'isize',
'usize', 'rune' {
'uint', 'usize', 'rune' {
'${v_type}(0)'
}
'f32' { 'f32(0)' }
+1 -1
View File
@@ -106,7 +106,7 @@ fn test_zero_value() {
assert zero_value('int') == 'int(0)'
assert zero_value('i32') == 'i32(0)'
assert zero_value('u64') == 'u64(0)'
assert zero_value('usize') == 'usize(0)'
assert zero_value('uint') == 'uint(0)'
assert zero_value('rune') == 'rune(0)'
assert zero_value('f32') == 'f32(0)'
assert zero_value('f64') == 'f64(0)'
+2 -2
View File
@@ -641,8 +641,8 @@ fn repl_literal_is_negated(line string, start int) bool {
// repl_literal_carries_its_type reports whether the literal is already the argument of a
// conversion, since the type that conversion names is the one that governs.
fn repl_literal_carries_its_type(line string, start int) bool {
names := ['u8', 'u16', 'u32', 'u64', 'u128', 'i8', 'i16', 'i32', 'i64', 'i128', 'int', 'usize',
'isize', 'rune', 'char', 'f32', 'f64']
names := ['u8', 'u16', 'u32', 'u64', 'u128', 'i8', 'i16', 'i32', 'i64', 'i128', 'int', 'uint',
'usize', 'isize', 'rune', 'char', 'f32', 'f64']
mut k := start - 1
for k >= 0 && line[k] == ` ` {
k--
+16 -1
View File
@@ -707,10 +707,25 @@ fn bootstrap_self_build(vroot string, args []string, final_binary string) ! {
os.rm(bootstrap_v1) or {}
os.rm(bootstrap_v2) or {}
}
vc_source := os.join_path(vroot, 'vc', if os.user_os() == 'windows' { 'v_win.c' } else { 'v.c' })
mut vc_source := os.join_path(vroot, 'vc', if os.user_os() == 'windows' {
'v_win.c'
} else {
'v.c'
})
if !os.exists(vc_source) {
return error('bootstrap fallback failed: `${vc_source}` is missing')
}
compat_source := os.join_path(vroot, 'vc', 'v_self_compat.c')
defer {
if os.user_os() == 'windows' {
os.rm(compat_source) or {}
}
}
if os.user_os() == 'windows' {
filter := os.join_path(vroot, 'cmd', 'tools', 'vc_compat_uint.ps1')
run_cmd('powershell -NoProfile -ExecutionPolicy Bypass -File ${os.quoted_path(filter)} -Source ${os.quoted_path(vc_source)} -Destination ${os.quoted_path(compat_source)}')!
vc_source = compat_source
}
cc := os.getenv_opt('CC') or {
if os.user_os() == 'windows' { 'gcc' } else { 'cc' }
}
+11 -12
View File
@@ -22,18 +22,17 @@
V `char`, `&char`, or `charptr` when you need to match C `char`, `char*`,
or `char**`.
* A V `isize` is equivalent to C `ssize_t`.
It is a signed integer, and `isize` is guaranteed to be at least 16 bits.
It is 32 bit on 32 bit platforms, and 64 bits on 64 bit ones.
* A V `int` is a platform-width signed integer: 32 bits on 32-bit targets and
64 bits on 64-bit targets.
* A V `usize` is equivalent to C `size_t`.
It is an unsigned integer, and `usize` is guaranteed to be at least 16 bits.
It is 32 bit on 32 bit platforms, and 64 bits on 64 bit ones.
* A V `uint` is a platform-width unsigned integer, equivalent to C `size_t` or `uintptr_t`.
It is 32 bits on 32-bit targets and 64 bits on 64-bit targets.
* A V `int` is currently equivalent to C `int`, or `int64_t`.
There are plans to make it equivalent to `isize`, so if you want to write C
library wrappers, it is better to describe your `fn C.` parameters using `i32`
instead of using `int`.
`isize` and `usize` are deprecated. Use `int` and `uint`, respectively.
For C library wrappers, use `i32` for C `int` parameters, fields, and return values.
Plain `int` in a `fn C.` signature retains the C `int` ABI for compatibility.
Use `C.ptrdiff_t` for signed pointer-width parameters and return values, including C
`intptr_t`, `ptrdiff_t`, and `ssize_t`. It is an alias of V `int` that preserves the C ABI.
## Representing pointers in C and V:
@@ -49,7 +48,7 @@ unsigned char func_name(int * p, index int);
... then you can represent its function signature in V like this:
```v ignore
fn C.func_name(p &int, index i32) u8
fn C.func_name(p &i32, index i32) u8
```
For a C output parameter, pass the address of the variable or struct field that C should update.
@@ -71,7 +70,7 @@ in a `.c.v` file, and mark a C typedef with `@[typedef]`. For example,
```v ignore
@[typedef]
struct C.Foo {
x int
x i32
}
```
+1 -1
View File
@@ -13,7 +13,7 @@ runtime even for literal output. Native execution must be validated on each
platform; generating C for a target alone does not verify its runtime ABI.
The compiler's string literals can contain the text of includes for other generated programs.
The C backend emits libc prototypes from bodyless V declarations such as
`fn C.strlen(const_s &char) usize`. Without system headers, this includes the bindings that a
`fn C.strlen(const_s &char) uint`. Without system headers, this includes the bindings that a
program declares itself, such as `fn C.getpgrp() int` or a Win32 function in Windows C,
which nothing else would declare. Runtime bindings are marked used so cached modules
retain their prototypes. Native backends retain C declarations without rooting same-named
+11 -6
View File
@@ -718,15 +718,15 @@ bool
string
i8 i16 int i64 i128
i8 i16 i32 i64 i128
u8 u16 u32 u64 u128
int, uint // platform-width signed and unsigned integers
rune // represents a Unicode code point
f32 f64
isize, usize // platform-dependent, the size is how many bytes it takes to reference any location in memory
voidptr // this one is mostly used for [C interoperability](#v-and-c)
```
@@ -734,6 +734,11 @@ voidptr // this one is mostly used for [C interoperability](#v-and-c)
> `int` is a platform-width signed integer: 64 bits on 64-bit targets and 32 bits on 32-bit
> targets. Use `i32` or `i64` when you need a fixed width.
> Integer literal casts to `int` are checked against the target platform's width.
> `uint` has the same width and is unsigned.
`isize` and `usize` are deprecated. Replace `isize` with `int` and `usize` with `uint`.
Use `uint` for pointer addresses and C `size_t` values to preserve
the full unsigned range. Existing spellings still compile with deprecation warnings.
### 128-bit integers
@@ -5037,7 +5042,7 @@ They are just a convenient way to write `i.some_function()` instead of
a convenience for writing `s.xyz()` instead of `xyz(s)`.
An immediate read-only interface method call on a smart-casted value can return
a scalar, including `char`, `rune`, `isize`, `usize`, or an enum.
a scalar, including `char`, `rune`, `int`, `uint`, or an enum.
Receiver methods are also available through embedded interfaces. A mutable receiver method
updates the underlying concrete object's mutable fields, including when called through an
@@ -9367,7 +9372,7 @@ V supports the following compile time types:
- `$enum` => matches [Enums](#enums).
- `$float` => matches `f32`, `f64` and float literals.
- `$function` => matches [Function Types](#function-types).
- `$int` => matches `int`, `i8`, `i16`, `i32`, `i64`, `u8`, `u16`, `u32`, `u64`, `isize`, `usize`
- `$int` => matches `int`, `i8`, `i16`, `i32`, `i64`, `u8`, `u16`, `u32`, `u64`, `uint`
and integer literals.
- `$interface` => matches [Interfaces](#interfaces).
- `$map` => matches [Maps](#maps).
@@ -11233,7 +11238,7 @@ pub struct C.SomeCStruct {
// union {
// struct {
data voidptr
size usize
size uint
// }
view C.DataView
// }
+1 -1
View File
@@ -2,7 +2,7 @@
In `@[translated]` files, boolean values can index arrays and pointers. Boolean,
character, and enum values can offset pointers in arithmetic and compound assignments.
Subtracting two pointers produces a pointer-width `isize` difference.
Subtracting two pointers produces a pointer-width `int` difference.
Mixed boolean and numeric conditional branches
retain the numeric branch type. Narrow integer shifts use C's minimum 32-bit
operand width. Shifts of translated `int` values use C's 32-bit `int` width.
+1 -1
View File
@@ -31,7 +31,7 @@ syn match vNumber /\v<\d[\d_]*([eE][+-]?\d[\d_]*)?>/
syn keyword vBoolean true false
syn keyword vConstant none nil
syn keyword vKeyword as asm assert atomic break const continue defer else enum false for fn __global go goto if import in interface is match module mut shared lock rlock none nil return select sizeof isreftype _likely_ _unlikely_ __offsetof struct true type typeof dump or union pub static volatile unsafe spawn implements like ilike
syn keyword vType bool string rune i8 i16 int i64 i128 isize u8 u16 u32 u64 u128 usize f32 f64 char map chan any voidptr byteptr charptr
syn keyword vType bool string rune i8 i16 i32 int i64 i128 isize u8 u16 u32 u64 u128 uint usize f32 f64 char map chan any voidptr byteptr charptr
syn match vComptime /\$[A-Za-z_][A-Za-z0-9_]*/
syn match vComptime /@[A-Z_][A-Z0-9_]*/
+4 -4
View File
@@ -5,11 +5,11 @@ import os
#include <sys/mman.h>
fn C.mmap(addr voidptr, len usize, prot i32, flags i32, fd i32, offset i64) voidptr
fn C.munmap(addr voidptr, len usize) i32
fn C.mmap(addr voidptr, len uint, prot i32, flags i32, fd i32, offset i64) voidptr
fn C.munmap(addr voidptr, len uint) i32
struct MemoryMappedFile {
size usize
size uint
mut:
data &u8
file os.File
@@ -18,7 +18,7 @@ mut:
fn mmap_file(path string) MemoryMappedFile {
mut mf := MemoryMappedFile{
file: os.open_file(path, 'r', 0) or { panic('fail') }
size: usize(os.file_size(path))
size: uint(os.file_size(path))
data: unsafe { nil }
}
+1 -1
View File
@@ -48,7 +48,7 @@ fn C.wkhtmltopdf_convert(converter &C.wkhtmltopdf_converter) i32
fn C.wkhtmltopdf_http_error_code(converter &C.wkhtmltopdf_converter) i32
fn C.wkhtmltopdf_get_output(converter &C.wkhtmltopdf_converter, const_data &&u8) isize
fn C.wkhtmltopdf_get_output(converter &C.wkhtmltopdf_converter, const_data &&u8) C.ptrdiff_t
fn main() {
// init
+4 -4
View File
@@ -186,22 +186,22 @@ fn inspect_native_window(mut app gg.App, window gg.WindowId) ! {
match backend {
.win32 {
lease.with_win32(fn (hwnd voidptr) ! {
println('borrowed HWND=${usize(hwnd):x}')
println('borrowed HWND=${uint(hwnd):x}')
})!
}
.appkit {
lease.with_appkit(fn (ns_window voidptr) ! {
println('borrowed NSWindow=${usize(ns_window):x}')
println('borrowed NSWindow=${uint(ns_window):x}')
})!
}
.x11 {
lease.with_x11(fn (display voidptr, xwindow u64) ! {
println('borrowed Display=${usize(display):x} Window=${xwindow:x}')
println('borrowed Display=${uint(display):x} Window=${xwindow:x}')
})!
}
.wayland {
lease.with_wayland(fn (display voidptr, surface voidptr) ! {
println('borrowed wl_display=${usize(display):x} wl_surface=${usize(surface):x}')
println('borrowed wl_display=${uint(display):x} wl_surface=${uint(surface):x}')
})!
}
.auto, .mock {}
+1 -1
View File
@@ -42,7 +42,7 @@ fn create_texture(w int, h int, buf &u8) (gfx.Image, gfx.Sampler) {
// comment, if .dynamic is enabled
img_desc.data.subimage[0][0] = gfx.Range{
ptr: buf
size: usize(sz)
size: uint(sz)
}
sg_img := gfx.make_image(&img_desc)
+7 -7
View File
@@ -66,7 +66,7 @@ fn create_texture(w int, h int, buf &u8) (gfx.Image, gfx.Sampler) {
// comment if .dynamic is enabled
img_desc.data.subimage[0][0] = gfx.Range{
ptr: buf
size: usize(sz)
size: uint(sz)
}
sg_img := gfx.make_image(&img_desc)
@@ -287,10 +287,10 @@ fn init_cube_glsl(mut app App) {
}
unsafe { vmemset(&vert_buffer_desc, 0, int(sizeof(vert_buffer_desc))) }
vert_buffer_desc.size = usize(vertices.len * int(sizeof(Vertex_t)))
vert_buffer_desc.size = uint(vertices.len * int(sizeof(Vertex_t)))
vert_buffer_desc.data = gfx.Range{
ptr: vertices.data
size: usize(vertices.len * int(sizeof(Vertex_t)))
size: uint(vertices.len * int(sizeof(Vertex_t)))
}
vert_buffer_desc.type = .vertexbuffer
@@ -314,10 +314,10 @@ fn init_cube_glsl(mut app App) {
}
unsafe { vmemset(&index_buffer_desc, 0, int(sizeof(index_buffer_desc))) }
index_buffer_desc.size = usize(indices.len * int(sizeof(u16)))
index_buffer_desc.size = uint(indices.len * int(sizeof(u16)))
index_buffer_desc.data = gfx.Range{
ptr: indices.data
size: usize(indices.len * int(sizeof(u16)))
size: uint(indices.len * int(sizeof(u16)))
}
index_buffer_desc.type = .indexbuffer
@@ -393,7 +393,7 @@ fn draw_cube_glsl(app App) {
// res is a 4x4 matrix of f32 thus: 4*16 byte of size
vs_uniforms_range := gfx.Range{
ptr: unsafe { &tr_matrix }
size: usize(4 * 16)
size: uint(4 * 16)
}
gfx.apply_uniforms(.vs, C.SLOT_vs_params, &vs_uniforms_range)
@@ -407,7 +407,7 @@ fn draw_cube_glsl(app App) {
]!
fs_uniforms_range := gfx.Range{
ptr: unsafe { &text_res }
size: usize(4 * 4)
size: uint(4 * 4)
}
gfx.apply_uniforms(.fs, C.SLOT_fs_params, &fs_uniforms_range)
@@ -69,7 +69,7 @@ fn create_texture(w int, h int, buf &u8) (gfx.Image, gfx.Sampler) {
// comment if .dynamic is enabled
img_desc.data.subimage[0][0] = gfx.Range{
ptr: buf
size: usize(sz)
size: uint(sz)
}
sg_img := gfx.make_image(&img_desc)
@@ -154,10 +154,10 @@ fn init_cube_glsl(mut app App) {
}
unsafe { vmemset(&vert_buffer_desc, 0, int(sizeof(vert_buffer_desc))) }
vert_buffer_desc.size = usize(vertices.len * int(sizeof(Vertex_t)))
vert_buffer_desc.size = uint(vertices.len * int(sizeof(Vertex_t)))
vert_buffer_desc.data = gfx.Range{
ptr: vertices.data
size: usize(vertices.len * int(sizeof(Vertex_t)))
size: uint(vertices.len * int(sizeof(Vertex_t)))
}
vert_buffer_desc.type = .vertexbuffer
@@ -180,10 +180,10 @@ fn init_cube_glsl(mut app App) {
}
unsafe { vmemset(&index_buffer_desc, 0, int(sizeof(index_buffer_desc))) }
index_buffer_desc.size = usize(indices.len * int(sizeof(u16)))
index_buffer_desc.size = uint(indices.len * int(sizeof(u16)))
index_buffer_desc.data = gfx.Range{
ptr: indices.data
size: usize(indices.len * int(sizeof(u16)))
size: uint(indices.len * int(sizeof(u16)))
}
index_buffer_desc.type = .indexbuffer
@@ -269,7 +269,7 @@ fn draw_cube_glsl(app App) {
// res is a 4x4 matrix of f32 thus: 4*16 byte of size
vs_uniforms_range := gfx.Range{
ptr: unsafe { &tr_matrix }
size: usize(4 * 16)
size: uint(4 * 16)
}
gfx.apply_uniforms(.vs, C.SLOT_vs_params, &vs_uniforms_range)
@@ -287,7 +287,7 @@ fn draw_cube_glsl(app App) {
]!
fs_uniforms_range := gfx.Range{
ptr: unsafe { &tmp_fs_params }
size: usize(sizeof(tmp_fs_params))
size: uint(sizeof(tmp_fs_params))
}
gfx.apply_uniforms(.fs, C.SLOT_fs_params, &fs_uniforms_range)
@@ -53,7 +53,7 @@ fn create_texture(w int, h int, buf byteptr) (gfx.Image, gfx.Sampler) {
}
img_desc.data.subimage[0][0] = gfx.Range{
ptr: buf
size: usize(sz)
size: uint(sz)
}
sg_img := gfx.make_image(&img_desc)
mut smp_desc := gfx.SamplerDesc{
@@ -111,7 +111,7 @@ fn (mut app App) init_glsl_shader(shader_name string, shader_desc &gfx.ShaderDes
mut vert_buffer_desc := gfx.BufferDesc{}
unsafe { vmemset(&vert_buffer_desc, 0, sizeof(vert_buffer_desc)) }
vert_buffer_desc.label = c'cube-vertices'
vert_buffer_desc.size = usize(vertices.len) * sizeof(Vertex_t)
vert_buffer_desc.size = uint(vertices.len) * sizeof(Vertex_t)
vert_buffer_desc.data = gfx.Range{
ptr: vertices.data
size: vert_buffer_desc.size
@@ -122,7 +122,7 @@ fn (mut app App) init_glsl_shader(shader_name string, shader_desc &gfx.ShaderDes
mut index_buffer_desc := gfx.BufferDesc{}
unsafe { vmemset(&index_buffer_desc, 0, sizeof(index_buffer_desc)) }
index_buffer_desc.label = c'cube-indices'
index_buffer_desc.size = usize(indices.len) * sizeof(u16)
index_buffer_desc.size = uint(indices.len) * sizeof(u16)
index_buffer_desc.data = gfx.Range{
ptr: indices.data
size: index_buffer_desc.size
@@ -196,7 +196,7 @@ fn (app &App) draw_glsl_shader(shader_name string) {
// res is a 4x4 matrix of f32 thus: 4*16 byte of size
vs_uniforms_range := gfx.Range{
ptr: unsafe { &tr_matrix }
size: usize(4 * 16)
size: uint(4 * 16)
}
gfx.apply_uniforms(.vs, C.SLOT_vs_params_m, &vs_uniforms_range)
@@ -216,7 +216,7 @@ fn (app &App) draw_glsl_shader(shader_name string) {
]!
fs_uniforms_range := gfx.Range{
ptr: unsafe { &tmp_fs_params }
size: usize(sizeof(tmp_fs_params))
size: uint(sizeof(tmp_fs_params))
}
gfx.apply_uniforms(.fs, C.SLOT_fs_params_p, &fs_uniforms_range)
+9 -9
View File
@@ -81,7 +81,7 @@ fn create_texture(w int, h int, buf byteptr) (gfx.Image, gfx.Sampler) {
// comment if .dynamic is enabled
img_desc.data.subimage[0][0] = gfx.Range{
ptr: buf
size: usize(sz)
size: uint(sz)
}
sg_img := gfx.make_image(&img_desc)
@@ -166,10 +166,10 @@ fn init_cube_glsl_i(mut app App) {
label: c'cube-vertices'
}
unsafe { vmemset(&vert_buffer_desc, 0, int(sizeof(vert_buffer_desc))) }
vert_buffer_desc.size = usize(vertices.len * int(sizeof(Vertex_t)))
vert_buffer_desc.size = uint(vertices.len * int(sizeof(Vertex_t)))
vert_buffer_desc.data = gfx.Range{
ptr: vertices.data
size: usize(vertices.len * int(sizeof(Vertex_t)))
size: uint(vertices.len * int(sizeof(Vertex_t)))
}
vert_buffer_desc.type = .vertexbuffer
vbuf := gfx.make_buffer(&vert_buffer_desc)
@@ -180,7 +180,7 @@ fn init_cube_glsl_i(mut app App) {
}
unsafe { vmemset(&inst_buffer_desc, 0, int(sizeof(inst_buffer_desc))) }
inst_buffer_desc.size = usize(num_inst * int(sizeof(m4.Vec4)))
inst_buffer_desc.size = uint(num_inst * int(sizeof(m4.Vec4)))
inst_buffer_desc.type = .vertexbuffer
inst_buffer_desc.usage = .stream
inst_buf := gfx.make_buffer(&inst_buffer_desc)
@@ -201,10 +201,10 @@ fn init_cube_glsl_i(mut app App) {
label: c'cube-indices'
}
unsafe { vmemset(&index_buffer_desc, 0, int(sizeof(index_buffer_desc))) }
index_buffer_desc.size = usize(indices.len * int(sizeof(u16)))
index_buffer_desc.size = uint(indices.len * int(sizeof(u16)))
index_buffer_desc.data = gfx.Range{
ptr: indices.data
size: usize(indices.len * int(sizeof(u16)))
size: uint(indices.len * int(sizeof(u16)))
}
index_buffer_desc.type = .indexbuffer
ibuf := gfx.make_buffer(&index_buffer_desc)
@@ -316,7 +316,7 @@ fn draw_cube_glsl_i(mut app App) {
}
range := gfx.Range{
ptr: unsafe { &app.inst_pos }
size: usize(num_inst * int(sizeof(m4.Vec4)))
size: uint(num_inst * int(sizeof(m4.Vec4)))
}
gfx.update_buffer(app.bind['inst'].vertex_buffers[1], &range)
@@ -326,7 +326,7 @@ fn draw_cube_glsl_i(mut app App) {
// res is a 4x4 matrix of f32 thus: 4*16 byte of size
vs_uniforms_range := gfx.Range{
ptr: unsafe { &tr_matrix }
size: usize(4 * 16)
size: uint(4 * 16)
}
gfx.apply_uniforms(.vs, C.SLOT_vs_params_i, &vs_uniforms_range)
@@ -346,7 +346,7 @@ fn draw_cube_glsl_i(mut app App) {
// vfmt on
fs_uniforms_range := gfx.Range{
ptr: unsafe { &tmp_fs_params }
size: usize(sizeof(tmp_fs_params))
size: uint(sizeof(tmp_fs_params))
}
gfx.apply_uniforms(.fs, C.SLOT_fs_params, &fs_uniforms_range)
*/
+7 -7
View File
@@ -35,7 +35,7 @@ pub fn create_texture(w int, h int, buf &u8) (gfx.Image, gfx.Sampler) {
// comment if .dynamic is enabled
img_desc.data.subimage[0][0] = gfx.Range{
ptr: buf
size: usize(sz)
size: uint(sz)
}
sg_img := gfx.make_image(&img_desc)
@@ -80,10 +80,10 @@ pub fn (mut obj_part ObjPart) create_pipeline(in_part []int, shader gfx.Shader,
mut vert_buffer_desc := gfx.BufferDesc{}
unsafe { vmemset(&vert_buffer_desc, 0, int(sizeof(vert_buffer_desc))) }
vert_buffer_desc.size = usize(obj_buf.vbuf.len * int(sizeof(Vertex_pnct)))
vert_buffer_desc.size = uint(obj_buf.vbuf.len * int(sizeof(Vertex_pnct)))
vert_buffer_desc.data = gfx.Range{
ptr: obj_buf.vbuf.data
size: usize(obj_buf.vbuf.len * int(sizeof(Vertex_pnct)))
size: uint(obj_buf.vbuf.len * int(sizeof(Vertex_pnct)))
}
vert_buffer_desc.type = .vertexbuffer
@@ -94,10 +94,10 @@ pub fn (mut obj_part ObjPart) create_pipeline(in_part []int, shader gfx.Shader,
mut index_buffer_desc := gfx.BufferDesc{}
unsafe { vmemset(&index_buffer_desc, 0, int(sizeof(index_buffer_desc))) }
index_buffer_desc.size = usize(obj_buf.ibuf.len * int(sizeof(u32)))
index_buffer_desc.size = uint(obj_buf.ibuf.len * int(sizeof(u32)))
index_buffer_desc.data = gfx.Range{
ptr: obj_buf.ibuf.data
size: usize(obj_buf.ibuf.len * int(sizeof(u32)))
size: uint(obj_buf.ibuf.len * int(sizeof(u32)))
}
index_buffer_desc.type = .indexbuffer
@@ -244,11 +244,11 @@ pub fn (obj_part ObjPart) bind_and_draw(rend_data_index int, in_data Shader_data
vs_uniforms_range := gfx.Range{
ptr: in_data.vs_data
size: usize(in_data.vs_len)
size: uint(in_data.vs_len)
}
fs_uniforms_range := gfx.Range{
ptr: unsafe { &tmp_fs_params }
size: usize(in_data.fs_len)
size: uint(in_data.fs_len)
}
gfx.apply_uniforms(.vs, C.SLOT_vs_params, &vs_uniforms_range)
@@ -98,7 +98,7 @@ fn init(user_data voidptr) {
}
unsafe { vmemset(&vertex_buffer_desc, 0, int(sizeof(vertex_buffer_desc))) }
vertex_buffer_desc.size = usize(vertices.len * int(sizeof(Vertex_t)))
vertex_buffer_desc.size = uint(vertices.len * int(sizeof(Vertex_t)))
vertex_buffer_desc.data = gfx.Range{
ptr: vertices.data
size: vertex_buffer_desc.size
+1 -1
View File
@@ -169,7 +169,7 @@ fn make_rgba_texture(w int, h int, rgba []u8) gfx.Image {
}
desc.data.subimage[0][0] = gfx.Range{
ptr: rgba.data
size: usize(w * h * 4)
size: uint(w * h * 4)
}
return gfx.make_image(&desc)
}
+7
View File
@@ -171,6 +171,11 @@ if !flag_local! NEQ 1 (
echo.
)
REM Teach pre-uint snapshots the new spelling without changing the download.
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0cmd\tools\vc_compat_uint.ps1" -Source "%V_C_FILE%" -Destination "%vc_dir%\v_win_compat.c"
if !ERRORLEVEL! NEQ 0 goto :error
set "V_C_FILE=%vc_dir%\v_win_compat.c"
echo Building V...
if not [!compiler!] == [] goto :!compiler!_strap
@@ -385,12 +390,14 @@ echo Backend compiler error
goto :error
:error
call :try_delete "%vc_dir%\v_win_compat.c"
echo.
echo Exiting from error
echo ERROR: please follow the instructions in https://github.com/vlang/v/wiki/Installing-a-C-compiler-on-Windows
exit /b 1
:success
call :try_delete "%vc_dir%\v_win_compat.c"
"%V_EXE%" run cmd/tools/detect_tcc.v
if !ERRORLEVEL! NEQ 0 exit /b !ERRORLEVEL!
echo ^> V built successfully!
+3 -3
View File
@@ -39,7 +39,7 @@ pub fn new(config Config) Arena {
$compile_error('module `arena` supports `-gc none` and the default Boehm GC, not `-gc vgc`')
}
return Arena{
handle: unsafe { v_arena_new(isize(config.chunk_size)) }
handle: unsafe { v_arena_new(int(config.chunk_size)) }
}
}
@@ -79,13 +79,13 @@ pub fn (mut a Arena) free() {
// used returns the number of bytes allocated in `a` since it was created or
// last reset.
pub fn (a &Arena) used() isize {
pub fn (a &Arena) used() int {
used, _ := v_arena_stats(a.handle)
return used
}
// capacity returns the number of bytes in the chunks that `a` holds.
pub fn (a &Arena) capacity() isize {
pub fn (a &Arena) capacity() int {
_, capacity := v_arena_stats(a.handle)
return capacity
}
+1 -1
View File
@@ -363,7 +363,7 @@ fn test_arena_memory_is_reused_in_loops() {
defer {
a.free()
}
mut warm_capacity := isize(0)
mut warm_capacity := int(0)
for i in 0 .. 2000 {
a.push()
mut sb := strings.new_builder(64)
+36 -36
View File
@@ -560,7 +560,7 @@ pub fn rotate_left[T](mut array []T, mid int) {
k := array.len - mid
p := unsafe { &T(array.data) }
unsafe {
ptr_rotate[T](mid, &T(usize(voidptr(p)) + usize(sizeof(T)) * usize(mid)), k)
ptr_rotate[T](mid, &T(uint(voidptr(p)) + uint(sizeof(T)) * uint(mid)), k)
}
}
@@ -579,24 +579,24 @@ pub fn rotate_right[T](mut array []T, k int) {
mid := array.len - k
p := unsafe { &T(array.data) }
unsafe {
ptr_rotate[T](mid, &T(usize(voidptr(p)) + usize(sizeof(T)) * usize(mid)), k)
ptr_rotate[T](mid, &T(uint(voidptr(p)) + uint(sizeof(T)) * uint(mid)), k)
}
}
@[unsafe]
fn ptr_rotate[T](left_ int, mid &T, right_ int) {
sz := usize(sizeof(T))
mut left := usize(left_)
mut right := usize(right_)
sz := uint(sizeof(T))
mut left := uint(left_)
mut right := uint(right_)
limit := raw_array_cap[T]()
for {
delta := if left < right { left } else { right }
if delta <= usize(limit) {
if delta <= uint(limit) {
break
}
unsafe {
swap_nonoverlapping[T](&T(usize(voidptr(mid)) - left * sz), &T(usize(voidptr(mid)) +
usize(right - delta) * sz), int(delta))
swap_nonoverlapping[T](&T(uint(voidptr(mid)) - left * sz), &T(uint(voidptr(mid)) +
uint(right - delta) * sz), int(delta))
}
if left <= right {
right -= delta
@@ -609,15 +609,15 @@ fn ptr_rotate[T](left_ int, mid &T, right_ int) {
defer {
free(rawarray)
}
dim := &T(usize(voidptr(mid)) - left * sz + right * sz)
dim := &T(uint(voidptr(mid)) - left * sz + right * sz)
if left <= right {
vmemcpy(rawarray, voidptr(usize(voidptr(mid)) - left * sz), isize(left * sz))
vmemmove(voidptr(usize(voidptr(mid)) - left * sz), voidptr(mid), isize(right * sz))
vmemcpy(voidptr(dim), rawarray, isize(left * sz))
vmemcpy(rawarray, voidptr(uint(voidptr(mid)) - left * sz), int(left * sz))
vmemmove(voidptr(uint(voidptr(mid)) - left * sz), voidptr(mid), int(right * sz))
vmemcpy(voidptr(dim), rawarray, int(left * sz))
} else {
vmemcpy(rawarray, voidptr(mid), isize(right * sz))
vmemmove(voidptr(dim), voidptr(usize(voidptr(mid)) - left * sz), isize(left * sz))
vmemcpy(voidptr(usize(voidptr(mid)) - left * sz), rawarray, isize(right * sz))
vmemcpy(rawarray, voidptr(mid), int(right * sz))
vmemmove(voidptr(dim), voidptr(uint(voidptr(mid)) - left * sz), int(left * sz))
vmemcpy(voidptr(uint(voidptr(mid)) - left * sz), rawarray, int(right * sz))
}
}
}
@@ -638,10 +638,10 @@ mut:
w u64
}
const extra_size = 32 * isize(sizeof(usize))
const extra_size = 32 * int(sizeof(uint))
fn raw_array_cap[T]() isize {
size := isize(sizeof(T))
fn raw_array_cap[T]() int {
size := int(sizeof(T))
if size > extra_size {
return 1
} else {
@@ -649,8 +649,8 @@ fn raw_array_cap[T]() isize {
}
}
fn raw_array_malloc_size[T]() isize {
size := isize(sizeof(T))
fn raw_array_malloc_size[T]() int {
size := int(sizeof(T))
if size > extra_size {
return size * 2
} else {
@@ -659,29 +659,29 @@ fn raw_array_malloc_size[T]() isize {
}
@[unsafe]
fn memswap(x voidptr, y voidptr, len usize) {
block_size := isize(sizeof(Block))
fn memswap(x voidptr, y voidptr, len uint) {
block_size := int(sizeof(Block))
mut i := usize(0)
for i + usize(block_size) <= len {
mut i := uint(0)
for i + uint(block_size) <= len {
mut t_ := Block{}
t := voidptr(&t_)
xi := usize(x) + i
yi := usize(y) + i
xi := uint(x) + i
yi := uint(y) + i
unsafe {
vmemcpy(t, voidptr(xi), block_size)
vmemcpy(voidptr(xi), voidptr(yi), block_size)
vmemcpy(voidptr(yi), t, block_size)
}
i += usize(block_size)
i += uint(block_size)
}
if i < len {
mut t_ := UnalignedBlock{}
t := voidptr(&t_)
rem := isize(len - i)
xi := usize(x) + i
yi := usize(y) + i
rem := int(len - i)
xi := uint(x) + i
yi := uint(y) + i
unsafe {
vmemcpy(t, voidptr(xi), rem)
vmemcpy(voidptr(xi), voidptr(yi), rem)
@@ -695,7 +695,7 @@ fn swap_nonoverlapping[T](x_ &T, y_ &T, count int) {
x := voidptr(x_)
y := voidptr(y_)
len := usize(sizeof(T)) * usize(count)
len := uint(sizeof(T)) * uint(count)
unsafe {
memswap(x, y, len)
}
@@ -711,12 +711,12 @@ pub fn copy[T](mut dst []T, src []T) int {
return 0
}
if can_copy_bits[T]() {
blen := min_len * isize(sizeof(T))
blen := min_len * int(sizeof(T))
unsafe { vmemmove(&T(dst.data), src.data, blen) }
} else {
dst_start := unsafe { usize(dst.data) }
src_start := unsafe { usize(src.data) }
copy_bytes := usize(min_len) * usize(sizeof(T))
dst_start := unsafe { uint(dst.data) }
src_start := unsafe { uint(src.data) }
copy_bytes := uint(min_len) * uint(sizeof(T))
if dst_start > src_start && dst_start - src_start < copy_bytes {
for i := min_len - 1; i >= 0; i-- {
dst[i] = src[i]
@@ -746,7 +746,7 @@ fn can_copy_bits[T]() bool {
@[unsafe]
pub fn carray_to_varray[T](c_array_data voidptr, items int) []T {
mut v_array := []T{len: items}
total_size := items * isize(sizeof(T))
total_size := items * int(sizeof(T))
unsafe { vmemcpy(v_array.data, c_array_data, total_size) }
return v_array
}
+4 -1
View File
@@ -3,6 +3,9 @@
`builtin` is a module that is implicitly imported by every V program.
It implements the builtin V types `array`, `string`, `map`.
`int` and `uint` use the pointer width of the target. The old `isize` and `usize`
names are deprecated in favor of `int` and `uint`. For signed pointer-width C
parameters and return values, `C.ptrdiff_t` aliases `int` and preserves the C ABI.
With bounds checking enabled, `first()` and `last()` on an empty dynamic array panic with
`array.first: array is empty` and `array.last: array is empty`, respectively.
This also applies when writing through the returned element, such as `cells.last().field = value`.
@@ -101,7 +104,7 @@ ensure no allocation from a rewound or freed scope remains in use.
`prealloc_scope_allocated_size(scope)` reports the bytes in all allocation blocks owned by a
scope, excluding allocator metadata and address gaps between blocks. It returns zero for a nil
scope and saturates at `usize`'s maximum on overflow. This query is unsafe: no thread may add or
scope and saturates at `uint`'s maximum on overflow. This query is unsafe: no thread may add or
remove blocks while it runs.
`string.replace_each(pairs)` ignores pairs with an empty search string. An empty replacement
+39 -39
View File
@@ -10,7 +10,7 @@ module builtin
__global v_memory_panic = false
@[noreturn]
fn _memory_panic(fname string, size isize) {
fn _memory_panic(fname string, size int) {
v_memory_panic = true
// Note: do not use string interpolation here at all, since string interpolation itself allocates
eprint(fname)
@@ -46,7 +46,7 @@ fn C.vheap_alloc(p voidptr, n u64)
fn C.vheap_free(p voidptr)
@[if track_heap ?]
fn _ht_alloc(p &u8, n isize) {
fn _ht_alloc(p &u8, n int) {
C.vheap_alloc(p, u64(n))
}
@@ -59,7 +59,7 @@ fn _ht_free(p voidptr) {
// malloc returns a `byteptr` pointing to the memory address of the allocated space.
// unlike the `calloc` family of functions - malloc will not zero the memory block.
@[inline; unsafe]
pub fn malloc(n isize) &u8 {
pub fn malloc(n int) &u8 {
$if trace_malloc ? {
total_m += n
C.fprintf(C.stderr, c'_v_malloc %6d total %10d\n', n, total_m)
@@ -85,7 +85,7 @@ pub fn malloc(n isize) &u8 {
return unsafe { prealloc_malloc(n) }
} $else $if vgc ? {
unsafe {
res = &u8(vgc_malloc(usize(n)))
res = &u8(vgc_malloc(uint(n)))
}
} $else $if gcboehm ? {
unsafe {
@@ -94,7 +94,7 @@ pub fn malloc(n isize) &u8 {
} $else $if freestanding {
// todo: is this safe to call malloc there? We export __malloc as malloc and it uses dlmalloc behind the scenes
// so theoretically it is safe
res = unsafe { __malloc(usize(n)) }
res = unsafe { __malloc(uint(n)) }
} $else {
$if windows {
// Warning! On windows, we always use _aligned_malloc to allocate memory.
@@ -120,7 +120,7 @@ pub fn malloc(n isize) &u8 {
// malloc_noscan allocates n bytes that do not contain garbage-collected pointers.
@[inline; unsafe]
pub fn malloc_noscan(n isize) &u8 {
pub fn malloc_noscan(n int) &u8 {
$if trace_malloc ? {
total_m += n
C.fprintf(C.stderr, c'malloc_noscan %6d total %10d\n', n, total_m)
@@ -142,7 +142,7 @@ pub fn malloc_noscan(n isize) &u8 {
return unsafe { prealloc_malloc(n) }
} $else $if vgc ? {
unsafe {
res = &u8(vgc_malloc_noscan(usize(n)))
res = &u8(vgc_malloc_noscan(uint(n)))
}
} $else $if gcboehm ? {
$if gcboehm_opt ? {
@@ -155,7 +155,7 @@ pub fn malloc_noscan(n isize) &u8 {
}
}
} $else $if freestanding {
res = unsafe { __malloc(usize(n)) }
res = unsafe { __malloc(uint(n)) }
} $else {
$if windows {
// Warning! On windows, we always use _aligned_malloc to allocate memory.
@@ -182,7 +182,7 @@ pub fn malloc_noscan(n isize) &u8 {
// String contents contain bytes only, including when a string view starts at an
// unaligned offset. Keep normal allocator hooks and tracing on their existing path.
@[inline; unsafe]
fn malloc_string_buffer(n isize) &u8 {
fn malloc_string_buffer(n int) &u8 {
$if prealloc && !builtin_arena ?&& !trace_malloc ? {
if n < 0 {
_memory_panic('malloc_noscan', n)
@@ -193,27 +193,27 @@ fn malloc_string_buffer(n isize) &u8 {
}
@[inline; unsafe]
fn malloc_uninit(n isize) &u8 {
fn malloc_uninit(n int) &u8 {
if n < 0 {
_memory_panic(@FN, n)
} else if n == 0 {
return &u8(unsafe { nil })
}
$if vgc ? {
return unsafe { &u8(vgc_malloc_typed_opts(usize(n), 0, 0, false)) }
return unsafe { &u8(vgc_malloc_typed_opts(uint(n), 0, 0, false)) }
}
return malloc(n)
}
@[inline; unsafe]
fn malloc_noscan_uninit(n isize) &u8 {
fn malloc_noscan_uninit(n int) &u8 {
if n < 0 {
_memory_panic(@FN, n)
} else if n == 0 {
return &u8(unsafe { nil })
}
$if vgc ? {
return unsafe { &u8(vgc_malloc_noscan_opts(usize(n), false)) }
return unsafe { &u8(vgc_malloc_noscan_opts(uint(n), false)) }
}
return malloc_noscan(n)
}
@@ -231,7 +231,7 @@ fn __at_least_one(how_many u64) u64 {
// malloc_uncollectable dynamically allocates a `n` bytes block of memory
// on the heap, which will NOT be garbage-collected (but its contents will).
@[unsafe]
pub fn malloc_uncollectable(n isize) &u8 {
pub fn malloc_uncollectable(n int) &u8 {
$if trace_malloc ? {
total_m += n
C.fprintf(C.stderr, c'malloc_uncollectable %6d total %10d\n', n, total_m)
@@ -255,14 +255,14 @@ pub fn malloc_uncollectable(n isize) &u8 {
return unsafe { prealloc_malloc(n) }
} $else $if vgc ? {
unsafe {
res = &u8(vgc_malloc(usize(n)))
res = &u8(vgc_malloc(uint(n)))
}
} $else $if gcboehm ? {
unsafe {
res = C.GC_MALLOC_UNCOLLECTABLE(n)
}
} $else $if freestanding {
res = unsafe { __malloc(usize(n)) }
res = unsafe { __malloc(uint(n)) }
} $else {
$if windows {
// Warning! On windows, we always use _aligned_malloc to allocate memory.
@@ -291,7 +291,7 @@ pub fn malloc_uncollectable(n isize) &u8 {
// previously allocated with `malloc` or `vcalloc`.
// Please, see also realloc_data, and use it instead if possible.
@[unsafe]
pub fn v_realloc(b &u8, n isize) &u8 {
pub fn v_realloc(b &u8, n int) &u8 {
$if trace_realloc ? {
C.fprintf(C.stderr, c'v_realloc %6d\n', n)
}
@@ -312,7 +312,7 @@ pub fn v_realloc(b &u8, n isize) &u8 {
}
return new_ptr
} $else $if vgc ? {
new_ptr = unsafe { &u8(vgc_realloc(b, usize(n))) }
new_ptr = unsafe { &u8(vgc_realloc(b, uint(n))) }
} $else $if gcboehm ? {
new_ptr = unsafe { C.GC_REALLOC(b, n) }
} $else {
@@ -384,7 +384,7 @@ pub fn realloc_data(old_data &u8, old_size int, new_size int) &u8 {
}
mut nptr := &u8(unsafe { nil })
$if vgc ? {
nptr = unsafe { &u8(vgc_realloc(old_data, usize(new_size))) }
nptr = unsafe { &u8(vgc_realloc(old_data, uint(new_size))) }
} $else $if gcboehm ? {
nptr = unsafe { C.GC_REALLOC(old_data, new_size) }
} $else {
@@ -399,13 +399,13 @@ pub fn realloc_data(old_data &u8, old_size int, new_size int) &u8 {
}
}
if nptr == 0 {
_memory_panic(@FN, isize(new_size))
_memory_panic(@FN, int(new_size))
}
// realloc(nil, …) means "allocate"; don't report a free with no prior block.
if old_data != unsafe { nil } {
_ht_free(old_data)
}
_ht_alloc(nptr, isize(new_size))
_ht_alloc(nptr, int(new_size))
return nptr
}
@@ -413,7 +413,7 @@ pub fn realloc_data(old_data &u8, old_size int, new_size int) &u8 {
// vcalloc returns a `byteptr` pointing to the memory address of the allocated space.
// vcalloc checks for negative values given in `n`.
@[inline]
pub fn vcalloc(n isize) &u8 {
pub fn vcalloc(n int) &u8 {
$if trace_vcalloc ? {
total_m += n
C.fprintf(C.stderr, c'vcalloc %6d total %10d\n', n, total_m)
@@ -436,7 +436,7 @@ pub fn vcalloc(n isize) &u8 {
$if prealloc {
return unsafe { prealloc_calloc(n) }
} $else $if vgc ? {
return unsafe { &u8(vgc_calloc(usize(n))) }
return unsafe { &u8(vgc_calloc(uint(n))) }
} $else $if gcboehm ? {
return unsafe { &u8(C.GC_MALLOC(n)) }
} $else {
@@ -463,7 +463,7 @@ pub fn vcalloc(n isize) &u8 {
// special versions of the above that allocate memory which is not scanned
// for pointers (but is collected) when the Boehm garbage collection is used
@[inline]
pub fn vcalloc_noscan(n isize) &u8 {
pub fn vcalloc_noscan(n int) &u8 {
$if trace_vcalloc ? {
total_m += n
C.fprintf(C.stderr, c'vcalloc_noscan %6d total %10d\n', n, total_m)
@@ -474,7 +474,7 @@ pub fn vcalloc_noscan(n isize) &u8 {
if n < 0 {
_memory_panic(@FN, n)
}
return unsafe { &u8(vgc_calloc(usize(n))) }
return unsafe { &u8(vgc_calloc(uint(n))) }
} $else $if gcboehm ? {
if n < 0 {
_memory_panic(@FN, n)
@@ -599,7 +599,7 @@ fn free_unaliased(ptr voidptr) {
// memdup then copies the contents of `src` into the allocated space and
// returns a pointer to the newly allocated space.
@[inline; unsafe]
pub fn memdup(src voidptr, sz isize) voidptr {
pub fn memdup(src voidptr, sz int) voidptr {
$if trace_memdup ? {
C.fprintf(C.stderr, c'memdup size: %10d\n', sz)
}
@@ -617,7 +617,7 @@ pub fn memdup(src voidptr, sz isize) voidptr {
// memdup_noscan copies `sz` bytes into newly allocated pointer-free storage.
@[inline; unsafe]
pub fn memdup_noscan(src voidptr, sz isize) voidptr {
pub fn memdup_noscan(src voidptr, sz int) voidptr {
$if trace_memdup ? {
C.fprintf(C.stderr, c'memdup_noscan size: %10d\n', sz)
}
@@ -638,7 +638,7 @@ pub fn memdup_noscan(src voidptr, sz isize) voidptr {
// memdup_uncollectable then copies the contents of `src` into the allocated
// space and returns a pointer to the newly allocated space.
@[unsafe]
pub fn memdup_uncollectable(src voidptr, sz isize) voidptr {
pub fn memdup_uncollectable(src voidptr, sz int) voidptr {
$if trace_memdup ? {
C.fprintf(C.stderr, c'memdup_uncollectable size: %10d\n', sz)
}
@@ -659,7 +659,7 @@ pub fn memdup_uncollectable(src voidptr, sz isize) voidptr {
// - `sz` must be non-negative
// - The memory regions should not overlap
@[unsafe]
pub fn memdup_align(src voidptr, sz isize, align isize) voidptr {
pub fn memdup_align(src voidptr, sz int, align int) voidptr {
$if trace_memdup ? {
C.fprintf(C.stderr, c'memdup_align size: %10d align: %10d\n', sz, align)
}
@@ -688,10 +688,10 @@ pub fn memdup_align(src voidptr, sz isize, align isize) voidptr {
res = prealloc_malloc_align(n, align)
} $else $if vgc ? {
// VGC traces and frees interior pointers within the scanned allocation.
alignment := usize(align)
base := vgc_malloc(usize(n) + alignment - 1)
alignment := uint(align)
base := vgc_malloc(uint(n) + alignment - 1)
if base != unsafe { nil } {
res = unsafe { &u8((usize(base) + alignment - 1) & ~(alignment - 1)) }
res = unsafe { &u8((uint(base) + alignment - 1) & ~(alignment - 1)) }
}
} $else $if gcboehm ? {
unsafe {
@@ -705,7 +705,7 @@ pub fn memdup_align(src voidptr, sz isize, align isize) voidptr {
// todo: is this safe to call malloc there? We export __malloc as malloc and it uses dlmalloc behind the scenes
// so theoretically it is safe
panic('memdup_align is not implemented with -freestanding')
res = unsafe { __malloc(usize(n)) }
res = unsafe { __malloc(uint(n)) }
} $else {
$if windows {
// Warning! On windows, we always use _aligned_malloc to allocate memory.
@@ -736,11 +736,11 @@ pub fn memdup_align(src voidptr, sz isize, align isize) voidptr {
// the same with `-gc boehm` and `-gc vgc`; they are 0 with `-gc none`.
pub struct GCHeapUsage {
pub:
heap_size usize // the heap memory obtained from the OS, without the part returned to it
free_bytes usize // the part of heap_size in free blocks
total_bytes usize // the bytes allocated since the program started
unmapped_bytes usize // free heap memory that was returned to the OS
bytes_since_gc usize // the bytes allocated since the last collection
heap_size uint // the heap memory obtained from the OS, without the part returned to it
free_bytes uint // the part of heap_size in free blocks
total_bytes uint // the bytes allocated since the program started
unmapped_bytes uint // free heap memory that was returned to the OS
bytes_since_gc uint // the bytes allocated since the last collection
}
// gc_heap_usage returns the info about heap usage.
@@ -766,7 +766,7 @@ pub fn gc_heap_usage() GCHeapUsage {
// gc_memory_use returns the total memory use in bytes by all allocated blocks: the heap_size
// of gc_heap_usage() without its free_bytes.
pub fn gc_memory_use() usize {
pub fn gc_memory_use() uint {
$if vgc ? {
return vgc_memory_use()
} $else $if gcboehm ? {
+46 -46
View File
@@ -21,8 +21,8 @@ module builtin
// never call into this file.
const arena_magic = u32(0x41524e41)
const arena_default_chunk_size = isize(64 * 1024)
const arena_max_chunk_size = isize(4 * 1024 * 1024)
const arena_default_chunk_size = int(64 * 1024)
const arena_max_chunk_size = int(4 * 1024 * 1024)
// VArenaChunk is the header at the start of each arena chunk.
struct VArenaChunk {
@@ -44,14 +44,14 @@ mut:
chunk &VArenaChunk = unsafe { nil } // serves new allocations
last &u8 = unsafe { nil } // the most recent allocation
below &VArena = unsafe { nil } // next arena down the thread's stack
chunk_size isize // size of the next regular chunk
max_chunk_size isize
chunk_size int // size of the next regular chunk
max_chunk_size int
}
struct VArenaRange {
mut:
start usize
stop usize
start uint
stop uint
owner &VArena = unsafe { nil }
}
@@ -73,8 +73,8 @@ fn C.atomic_store_ptr(voidptr, voidptr)
// and nothing clears. Publishing g_arena_hooks_ready after installation makes
// all three immutable hooks visible together to allocation entry points.
__global g_arena_hooks_ready u32
__global g_arena_alloc_hook fn (n isize, align isize) &u8
__global g_arena_realloc_hook fn (old_data &u8, old_size isize, new_size isize) &u8
__global g_arena_alloc_hook fn (n int, align int) &u8
__global g_arena_realloc_hook fn (old_data &u8, old_size int, new_size int) &u8
__global g_arena_owns_hook fn (ptr voidptr) bool
// g_arena_top is the innermost arena pushed on the current thread. It is
// thread-local (see `is_builtin_arena_top` in the C backend), so spawned
@@ -92,14 +92,14 @@ __global g_arena_ranges_len u32
// arena_align is the alignment of arena allocations without an explicit one:
// that of malloc, which is 16 bytes on 32-bit targets too.
@[inline]
fn arena_align() isize {
fn arena_align() int {
return 16
}
@[inline]
fn arena_chunk_header_size() isize {
fn arena_chunk_header_size() int {
align := arena_align()
return (isize(sizeof(VArenaChunk)) + align - 1) / align * align
return (int(sizeof(VArenaChunk)) + align - 1) / align * align
}
@[inline]
@@ -131,13 +131,13 @@ fn arena_registry_end_write() {
}
@[inline; unsafe]
fn arena_range_start(r &VArenaRange) usize {
return usize(C.atomic_load_ptr(&r.start))
fn arena_range_start(r &VArenaRange) uint {
return uint(C.atomic_load_ptr(&r.start))
}
@[inline; unsafe]
fn arena_range_stop(r &VArenaRange) usize {
return usize(C.atomic_load_ptr(&r.stop))
fn arena_range_stop(r &VArenaRange) uint {
return uint(C.atomic_load_ptr(&r.stop))
}
@[inline; unsafe]
@@ -150,7 +150,7 @@ fn arena_range_set(mut r VArenaRange, value VArenaRange) {
// arena_registry_upper returns the index of the first of the `len` ranges of
// `reg` that starts after `addr`.
@[direct_array_access; unsafe]
fn arena_registry_upper(reg &VArenaRegistry, len int, addr usize) int {
fn arena_registry_upper(reg &VArenaRegistry, len int, addr uint) int {
mut lo := 0
mut hi := len
for lo < hi {
@@ -172,26 +172,26 @@ fn arena_registry_add(owner &VArena, chunk &VArenaChunk) {
mut reg := g_arena_registry
if reg == nil || len == reg.cap {
new_cap := if reg == nil { 16 } else { reg.cap * 2 }
bytes := sizeof(VArenaRegistry) + usize(new_cap) * sizeof(VArenaRange)
bytes := sizeof(VArenaRegistry) + uint(new_cap) * sizeof(VArenaRange)
mut grown := &VArenaRegistry(C.malloc(bytes))
vmemory_abort_on_nil(grown, isize(bytes))
vmemory_abort_on_nil(grown, int(bytes))
grown.cap = new_cap
grown.ranges = &VArenaRange(&u8(grown) + sizeof(VArenaRegistry))
if len > 0 {
C.memcpy(grown.ranges, reg.ranges, usize(len) * sizeof(VArenaRange))
C.memcpy(grown.ranges, reg.ranges, uint(len) * sizeof(VArenaRange))
}
// The old registry is left allocated (see VArenaRegistry).
C.atomic_store_ptr(&g_arena_registry, grown)
reg = grown
}
start := usize(chunk.start)
start := uint(chunk.start)
i := arena_registry_upper(reg, len, start)
for j := len; j > i; j-- {
arena_range_set(mut reg.ranges[j], reg.ranges[j - 1])
}
arena_range_set(mut reg.ranges[i], VArenaRange{
start: start
stop: usize(chunk.stop)
stop: uint(chunk.stop)
owner: owner
})
C.atomic_store_u32(&g_arena_ranges_len, u32(len + 1))
@@ -205,7 +205,7 @@ fn arena_registry_remove(chunk &VArenaChunk) {
unsafe {
reg := g_arena_registry
len := int(g_arena_ranges_len)
start := usize(chunk.start)
start := uint(chunk.start)
i := arena_registry_upper(reg, len, start) - 1
if i >= 0 && reg.ranges[i].start == start {
for j in i .. len - 1 {
@@ -223,7 +223,7 @@ fn arena_registry_remove(chunk &VArenaChunk) {
// of the registry is repeated. Its loads stay inside the registry it searches,
// whatever a writer does meanwhile.
@[direct_array_access; unsafe]
fn arena_registry_find(addr usize) (&VArena, usize) {
fn arena_registry_find(addr uint) (&VArena, uint) {
for {
seq := C.atomic_load_u32(&g_arena_seq)
if seq & 1 != 0 {
@@ -231,7 +231,7 @@ fn arena_registry_find(addr usize) (&VArena, usize) {
}
reg := &VArenaRegistry(C.atomic_load_ptr(&g_arena_registry))
mut owner := &VArena(nil)
mut stop := usize(0)
mut stop := uint(0)
if reg != nil {
mut len := int(C.atomic_load_u32(&g_arena_ranges_len))
if len > reg.cap {
@@ -257,8 +257,8 @@ fn arena_registry_find(addr usize) (&VArena, usize) {
// arena_owner returns the arena that owns `ptr` (nil for any other memory) and
// the end of the chunk that contains it.
@[unsafe]
fn arena_owner(ptr voidptr) (&VArena, usize) {
addr := usize(ptr)
fn arena_owner(ptr voidptr) (&VArena, uint) {
addr := uint(ptr)
unsafe {
// Only this thread changes the arenas on its own stack, so they can be
// searched without the registry. They own most memory freed in a scope.
@@ -266,8 +266,8 @@ fn arena_owner(ptr voidptr) (&VArena, usize) {
for a != nil {
mut c := a.chunk
for c != nil {
if addr >= usize(c.start) && addr < usize(c.stop) {
return a, usize(c.stop)
if addr >= uint(c.start) && addr < uint(c.stop) {
return a, uint(c.stop)
}
c = c.prev
}
@@ -301,7 +301,7 @@ fn arena_chunk_release(chunk &VArenaChunk) {
// arena_grow adds a chunk with room for at least `need` bytes.
@[noinline; unsafe]
fn arena_grow(mut a VArena, need isize) &VArenaChunk {
fn arena_grow(mut a VArena, need int) &VArenaChunk {
mut size := a.chunk_size
if need > size {
size = need
@@ -317,9 +317,9 @@ fn arena_grow(mut a VArena, need isize) &VArenaChunk {
$if gcboehm ? {
// Uncollectable chunks are still scanned, so GC objects that are only
// referenced from arena memory stay alive.
mem = C.GC_MALLOC_UNCOLLECTABLE(usize(total))
mem = C.GC_MALLOC_UNCOLLECTABLE(uint(total))
} $else {
mem = C.malloc(usize(total))
mem = C.malloc(uint(total))
}
vmemory_abort_on_nil(mem, total)
unsafe {
@@ -335,12 +335,12 @@ fn arena_grow(mut a VArena, need isize) &VArenaChunk {
}
@[unsafe]
fn arena_alloc(mut a VArena, n isize, align isize) &u8 {
fn arena_alloc(mut a VArena, n int, align int) &u8 {
default_align := arena_align()
fixed_align := if align > default_align { align } else { default_align }
// Like malloc, fail for a size that no chunk can hold, before computing the
// size of that chunk overflows.
if usize(n) > (~usize(0) >> 1) - usize(fixed_align + arena_chunk_header_size()) {
if uint(n) > (~uint(0) >> 1) - uint(fixed_align + arena_chunk_header_size()) {
_memory_panic(@FN, n)
}
unsafe {
@@ -361,7 +361,7 @@ fn arena_alloc(mut a VArena, n isize, align isize) &u8 {
// arena_alloc_current returns `n` bytes from the current thread's arena, or
// nil when no arena is active.
fn arena_alloc_current(n isize, align isize) &u8 {
fn arena_alloc_current(n int, align int) &u8 {
mut a := g_arena_top
if a == unsafe { nil } {
return unsafe { nil }
@@ -374,7 +374,7 @@ fn arena_alloc_current(n isize, align isize) &u8 {
// of the current arena grows in place; other arena memory is copied to the
// current allocator and left in its arena. realloc(nil, n) allocates from the
// current arena.
fn arena_realloc(old_data &u8, old_size isize, new_size isize) &u8 {
fn arena_realloc(old_data &u8, old_size int, new_size int) &u8 {
unsafe {
if old_data == nil {
if new_size <= 0 {
@@ -403,16 +403,16 @@ fn arena_realloc(old_data &u8, old_size isize, new_size isize) &u8 {
n = old_size
}
// Without the old size, copy what the chunk holds: it is mapped memory.
available := isize(chunk_stop - usize(old_data))
available := int(chunk_stop - uint(old_data))
if available < n {
n = available
}
// A new block in the same chunk starts at or after the end of the old
// one, so the bytes before it hold all of the old block.
if usize(new_ptr) > usize(old_data) && usize(new_ptr) - usize(old_data) < usize(n) {
n = isize(usize(new_ptr) - usize(old_data))
if uint(new_ptr) > uint(old_data) && uint(new_ptr) - uint(old_data) < uint(n) {
n = int(uint(new_ptr) - uint(old_data))
}
C.memcpy(new_ptr, old_data, usize(n))
C.memcpy(new_ptr, old_data, uint(n))
return new_ptr
}
}
@@ -446,7 +446,7 @@ fn arena_release_chunks(mut a VArena, keep_one bool) {
if keep != nil {
$if gcboehm ? {
// Stale pointers in reused memory would keep GC objects alive.
C.memset(keep.start, 0, usize(i64(keep.cursor) - i64(keep.start)))
C.memset(keep.start, 0, uint(i64(keep.cursor) - i64(keep.start)))
}
keep.prev = nil
keep.cursor = keep.start
@@ -470,12 +470,12 @@ fn arena_checked(handle voidptr) &VArena {
// v_arena_new creates an arena whose first chunk holds `chunk_size` bytes (0
// selects 64KB). It is the low-level hook behind `arena.new()`; use that.
@[unsafe]
pub fn v_arena_new(chunk_size isize) voidptr {
pub fn v_arena_new(chunk_size int) voidptr {
$if prealloc || vgc ?|| freestanding || vinix {
panic('arena: scoped arenas are not supported with -prealloc, -gc vgc, -freestanding or on Vinix')
}
mut a := unsafe { &VArena(C.calloc(1, sizeof(VArena))) }
vmemory_abort_on_nil(a, isize(sizeof(VArena)))
vmemory_abort_on_nil(a, int(sizeof(VArena)))
a.magic = arena_magic
a.chunk_size = if chunk_size > 0 { chunk_size } else { arena_default_chunk_size }
a.max_chunk_size = if a.chunk_size > arena_max_chunk_size {
@@ -562,7 +562,7 @@ pub fn v_arena_current() voidptr {
// v_arena_stats returns the bytes handed out by an arena since its last
// reset, and the bytes of its chunks.
pub fn v_arena_stats(handle voidptr) (isize, isize) {
pub fn v_arena_stats(handle voidptr) (int, int) {
a := arena_checked(handle)
mut used := i64(0)
mut capacity := i64(0)
@@ -572,16 +572,16 @@ pub fn v_arena_stats(handle voidptr) (isize, isize) {
capacity += i64(c.stop) - i64(c.start)
c = c.prev
}
return isize(used), isize(capacity)
return int(used), int(capacity)
}
// v_arena_owns reports whether `ptr` points into the memory of an arena.
pub fn v_arena_owns(handle voidptr, ptr voidptr) bool {
a := arena_checked(handle)
addr := usize(ptr)
addr := uint(ptr)
mut c := a.chunk
for c != unsafe { nil } {
if addr >= usize(c.start) && addr < usize(c.stop) {
if addr >= uint(c.start) && addr < uint(c.stop) {
return true
}
c = c.prev
+11 -11
View File
@@ -12,7 +12,7 @@ import strings
pub struct array {
pub mut:
data voidptr
offset int // in bytes (should be `usize`), to avoid copying data while making slices, unless it starts changing
offset int // in bytes (should be `uint`), 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
@@ -59,7 +59,7 @@ fn array_data_allocation_size(total_size u64) u64 {
@[inline]
fn init_array_data(raw voidptr) voidptr {
// At most 15 bytes of padding keep both the header and element storage aligned.
padding := (16 - (usize(raw) + usize(array_data_header_size())) % 16) % 16
padding := (16 - (uint(raw) + uint(array_data_header_size())) % 16) % 16
unsafe {
data := &u8(raw) + array_data_header_size() + padding
header := &ArrayDataHeader(data - array_data_header_size())
@@ -462,7 +462,7 @@ pub fn (mut a array) ensure_cap(required int) {
if a.flags.has(.noslices) && !a.flags.has(.is_slice) && !a.buffer_has_slices() {
unsafe {
$if prealloc {
prealloc_discard_pages(a.data, usize(a.cap) * usize(a.element_size))
prealloc_discard_pages(a.data, uint(a.cap) * uint(a.element_size))
}
if a.flags.has(.managed) {
free_unaliased(a.data_header().allocation)
@@ -1199,9 +1199,9 @@ fn (mut a array) set(i int, val voidptr) {
// with indexes it has already bounded, so it skips the per-element range checks
// of `array.set`.
@[inline; markused; unsafe]
fn array_sort_move(dst voidptr, di int, src voidptr, si int, count int, element_size usize) {
vmemcpy(&u8(dst) + usize(di) * element_size, &u8(src) + usize(si) * element_size,
isize(usize(count) * element_size))
fn array_sort_move(dst voidptr, di int, src voidptr, si int, count int, element_size uint) {
vmemcpy(&u8(dst) + uint(di) * element_size, &u8(src) + uint(si) * element_size,
int(uint(count) * element_size))
}
$if !v3_backend ? {
@@ -1391,7 +1391,7 @@ pub fn (a array) reverse() array {
pub fn (a &array) free() {
$if prealloc {
if !a.flags.has(.is_slice) && !a.flags.has(.nofree) && !a.buffer_has_retained_fixed_views() {
unsafe { prealloc_discard_pages(a.data, usize(a.cap) * usize(a.element_size)) }
unsafe { prealloc_discard_pages(a.data, uint(a.cap) * uint(a.element_size)) }
}
return
}
@@ -1406,7 +1406,7 @@ pub fn (a &array) free() {
if a.flags.has(.nofree) || a.buffer_has_retained_fixed_views() {
return
}
mblock_ptr := &u8(usize(a.data) - usize(a.offset))
mblock_ptr := &u8(uint(a.data) - uint(a.offset))
if mblock_ptr != unsafe { nil } {
unsafe {
allocation := if a.flags.has(.managed) {
@@ -1547,7 +1547,7 @@ pub fn (mut a array) sort_with_compare(callback FnSortCB) {
$if freestanding {
panic('sort_with_compare does not work with -freestanding')
} $else {
unsafe { vqsort(a.data, usize(a.len), usize(a.element_size), callback) }
unsafe { vqsort(a.data, uint(a.len), uint(a.element_size), callback) }
}
}
@@ -1557,7 +1557,7 @@ pub fn (mut a array) sort_with_compare(callback FnSortCB) {
// Equal elements keep their original relative order.
pub fn (a &array) sorted_with_compare(callback FnSortCB) array {
mut r := a.clone()
unsafe { vqsort(r.data, usize(r.len), usize(r.element_size), callback) }
unsafe { vqsort(r.data, uint(r.len), uint(r.element_size), callback) }
return r
}
@@ -1640,7 +1640,7 @@ pub fn (b []u8) hex() string {
pub fn copy(mut dst []u8, src []u8) int {
min := if dst.len < src.len { dst.len } else { src.len }
if min > 0 {
unsafe { vmemmove(dst.data, src.data, isize(min) * isize(dst.element_size)) }
unsafe { vmemmove(dst.data, src.data, int(min) * int(dst.element_size)) }
}
return min
}
+10 -10
View File
@@ -4,12 +4,12 @@ const array_alignment_shift = sizeof(ArrayFlags) * 8 - 8
const array_alignment_mask = u32(63) << array_alignment_shift
@[inline]
fn (a &array) data_alignment() usize {
fn (a &array) data_alignment() uint {
exponent := (u32(a.flags) & array_alignment_mask) >> array_alignment_shift
return if exponent == 0 { usize(16) } else { usize(1) << exponent }
return if exponent == 0 { uint(16) } else { uint(1) << exponent }
}
fn data_alignment_exponent(alignment usize) u8 {
fn data_alignment_exponent(alignment uint) u8 {
if alignment <= 16 {
return 0
}
@@ -22,7 +22,7 @@ fn data_alignment_exponent(alignment usize) u8 {
return exponent
}
fn (mut a array) set_data_alignment(alignment usize) {
fn (mut a array) set_data_alignment(alignment uint) {
exponent := u32(data_alignment_exponent(alignment))
bits := u32(a.flags) & ~array_alignment_mask
a.flags = unsafe { ArrayFlags(bits | (exponent << array_alignment_shift)) }
@@ -38,7 +38,7 @@ fn (a &array) storage_flags(noscan bool) ArrayFlags {
return unsafe { ArrayFlags(flags) }
}
fn alloc_array_data_aligned(total_size u64, alignment usize, zero bool) voidptr {
fn alloc_array_data_aligned(total_size u64, alignment uint, zero bool) voidptr {
size := u64(array_data_header_size()) + u64(alignment - 1)
allocation_size := size + __at_least_one(total_size)
raw := if zero {
@@ -46,8 +46,8 @@ fn alloc_array_data_aligned(total_size u64, alignment usize, zero bool) voidptr
} else {
unsafe { malloc_uninit(allocation_size) }
}
header_size := usize(array_data_header_size())
padding := (alignment - (usize(raw) + header_size) % alignment) % alignment
header_size := uint(array_data_header_size())
padding := (alignment - (uint(raw) + header_size) % alignment) % alignment
unsafe {
data := &u8(raw) + header_size + padding
header := &ArrayDataHeader(data - header_size)
@@ -58,7 +58,7 @@ fn alloc_array_data_aligned(total_size u64, alignment usize, zero bool) voidptr
}
}
fn __new_array_aligned(mylen int, capacity int, element_size int, alignment usize) array {
fn __new_array_aligned(mylen int, capacity int, element_size int, alignment uint) array {
if alignment <= 16 {
return __new_array(mylen, capacity, element_size)
}
@@ -78,7 +78,7 @@ fn __new_array_aligned(mylen int, capacity int, element_size int, alignment usiz
return result
}
fn new_array_from_c_array_aligned(length int, capacity int, element_size int, source voidptr, alignment usize) array {
fn new_array_from_c_array_aligned(length int, capacity int, element_size int, source voidptr, alignment uint) array {
panic_on_negative_len(length)
panic_on_negative_cap(capacity)
mut result := __new_array_aligned(0, if capacity < length { length } else { capacity },
@@ -90,7 +90,7 @@ fn new_array_from_c_array_aligned(length int, capacity int, element_size int, so
return result
}
fn new_array_from_c_array_no_alloc_aligned(length int, capacity int, element_size int, source voidptr, alignment usize) array {
fn new_array_from_c_array_no_alloc_aligned(length int, capacity int, element_size int, source voidptr, alignment uint) array {
mut result := new_array_from_c_array_no_alloc(length, capacity, element_size, source)
result.set_data_alignment(alignment)
return result
+2 -2
View File
@@ -1,7 +1,7 @@
module builtin
fn test_array_alignment_does_not_overlap_retained_storage_flags() {
for alignment in [usize(16), 32, 64, 128, 4096] {
for alignment in [uint(16), 32, 64, 128, 4096] {
mut value := array{}
value.set_data_alignment(alignment)
value.mark_aligned_fixed_array_buffer()
@@ -15,7 +15,7 @@ fn test_array_alignment_does_not_overlap_retained_storage_flags() {
fn test_aligned_array_header_initializes_retained_views() {
mut value := __new_array_aligned(0, 4, int(sizeof(u64)), 64)
assert usize(value.data) % 64 == 0
assert uint(value.data) % 64 == 0
assert !value.buffer_has_retained_fixed_views()
assert !value.buffer_has_slices()
unsafe { value.free() }
+8 -8
View File
@@ -1,15 +1,15 @@
module builtin
fn test_managed_array_alignment_does_not_depend_on_allocation_alignment() {
assert sizeof(ArrayDataHeader) <= usize(array_data_header_size())
assert sizeof(ArrayDataHeader) <= uint(array_data_header_size())
// Model allocators with weaker alignment by testing every possible low nibble.
allocation := unsafe { malloc(128) }
for offset in 0 .. 16 {
raw := unsafe { allocation + offset }
data := init_array_data(raw)
assert usize(data) % 16 == 0
assert usize(data) - usize(raw) >= usize(array_data_header_size())
assert usize(data) - usize(raw) <= usize(array_data_header_size()) + 15
assert uint(data) % 16 == 0
assert uint(data) - uint(raw) >= uint(array_data_header_size())
assert uint(data) - uint(raw) <= uint(array_data_header_size()) + 15
a := array{
data: data
len: 1
@@ -38,7 +38,7 @@ fn test_managed_array_header_survives_slice_offsets() {
assert owner[1] == 1
view << u64(99)
assert view.data != owner.data
assert usize(view.data) % 16 == 0
assert uint(view.data) % 16 == 0
assert unsafe { view.data_header().allocation } != allocation
assert view == [u64(1), 2, 3, 4, 99]
assert owner[5] == 5
@@ -56,7 +56,7 @@ fn test_managed_array_offset_and_noslices_growth_free_original_allocation() {
assert unsafe { values.data_header() } == header
for n in 2 .. 128 {
values << u64(n)
assert usize(values.data) % 16 == 0
assert uint(values.data) % 16 == 0
}
assert values[0] == 1
assert values.last() == 127
@@ -74,7 +74,7 @@ fn test_noscan_array_allocations_use_the_same_alignment_and_ownership() {
} else {
alloc_array_data_noscan_uninit(32)
}
assert usize(data) % 16 == 0
assert uint(data) % 16 == 0
mut values := array{
data: data
len: 2
@@ -86,7 +86,7 @@ fn test_noscan_array_allocations_use_the_same_alignment_and_ownership() {
assert header.allocation != unsafe { nil }
assert !header.has_slices
values.ensure_cap_noscan(128)
assert usize(values.data) % 16 == 0
assert uint(values.data) % 16 == 0
assert values.flags.has(.noscan_data)
assert !values.buffer_has_slices()
unsafe { values.free() }
+1 -1
View File
@@ -36,7 +36,7 @@ fn backtrace_exec_capture(args []string) (string, int) {
mut output := ''
mut buf := [4096]u8{}
for {
n := C.read(fd, &buf[0], usize(buf.len))
n := C.read(fd, &buf[0], uint(buf.len))
if n > 0 {
// read returned n initialized bytes in the stack buffer.
output += unsafe { tos(&buf[0], int(n)) }
+11 -11
View File
@@ -214,17 +214,17 @@ $if gcboehm_leak ? {
// Do not use them manually. They are automatically chosen when
// compiled with `-gc boehm` or `-gc boehm_leak`.
@[c: 'v_gc_malloc']
fn C.GC_MALLOC(n usize) voidptr
fn C.GC_MALLOC(n uint) voidptr
@[c: 'v_gc_malloc_atomic']
fn C.GC_MALLOC_ATOMIC(n usize) voidptr
fn C.GC_MALLOC_ATOMIC(n uint) voidptr
@[c: 'v_gc_malloc_uncollectable']
@[markused]
fn C.GC_MALLOC_UNCOLLECTABLE(n usize) voidptr
fn C.GC_MALLOC_UNCOLLECTABLE(n uint) voidptr
@[c: 'v_gc_realloc']
fn C.GC_REALLOC(ptr voidptr, n usize) voidptr
fn C.GC_REALLOC(ptr voidptr, n uint) voidptr
@[c: 'v_gc_free']
@[markused]
@@ -247,7 +247,7 @@ $if !windows {
fn C.v_gc_dlopen(const_path &char, mode i32) voidptr
}
fn C.GC_memalign(align usize, size usize) voidptr
fn C.GC_memalign(align uint, size uint) voidptr
// explicitly perform garbage collection now! Garbage collections
// are done automatically when needed, so this function is hardly needed
@@ -304,9 +304,9 @@ pub fn gc_check_leaks() {
}
}
fn C.GC_get_heap_usage_safe(pheap_size &usize, pfree_bytes &usize, punmapped_bytes &usize, pbytes_since_gc &usize,
ptotal_bytes &usize)
fn C.GC_get_memory_use() usize
fn C.GC_get_heap_usage_safe(pheap_size &uint, pfree_bytes &uint, punmapped_bytes &uint, pbytes_since_gc &uint,
ptotal_bytes &uint)
fn C.GC_get_memory_use() uint
pub struct C.GC_stack_base {
mem_base voidptr
@@ -337,7 +337,7 @@ fn C.GC_set_sp_corrector(fn (voidptr, voidptr))
// FnGC_WarnCB is the type of the callback, that you have to define, if you want to redirect GC warnings and handle them.
// Note: GC warnings are silenced by default. Use gc_set_warn_proc/1 to set your own handler for them.
pub type FnGC_WarnCB = fn (const_msg &char, arg usize)
pub type FnGC_WarnCB = fn (const_msg &char, arg uint)
fn C.v_gc_get_warn_proc() voidptr
fn C.v_gc_set_warn_proc(cb FnGC_WarnCB)
@@ -345,7 +345,7 @@ fn C.v_gc_set_warn_proc(cb FnGC_WarnCB)
// GC_REGISTER_DISPLACEMENT is `GC_debug_register_displacement` when `GC_DEBUG` is set
// (`-gc boehm_leak`), and `GC_register_displacement` otherwise.
@[c: 'v_gc_register_displacement']
fn C.GC_REGISTER_DISPLACEMENT(offset usize)
fn C.GC_REGISTER_DISPLACEMENT(offset uint)
// FnGC_AbortCB is the type of Boehm's fatal error handler (`GC_abort_func`).
// `const_msg` is nil when Boehm calls it right before `exit(1)`.
@@ -371,7 +371,7 @@ pub fn gc_set_warn_proc(cb FnGC_WarnCB) {
}
// used by builtin_init:
fn internal_gc_warn_proc_none(const_msg &char, arg usize) {}
fn internal_gc_warn_proc_none(const_msg &char, arg uint) {}
// gc_report_fatal_errors_on_stderr replaces Boehm's abort handler. On Windows the
// default one shows a modal message box and waits for someone to dismiss it, so a
+2 -2
View File
@@ -24,7 +24,7 @@ $if openbsd {
type BacktraceErrorCallback = fn (data voidptr, const_msg &char, errnum i32)
type BacktraceFullCallback = fn (data voidptr, pc usize, const_filename &char, lineno i32, const_func &char) i32
type BacktraceFullCallback = fn (data voidptr, pc uint, const_filename &char, lineno i32, const_func &char) i32
fn C.backtrace_create_state(filename &char, threaded i32, error_callback BacktraceErrorCallback, data voidptr) &C.backtrace_state
fn C.backtrace_full(state &C.backtrace_state, skip i32, cb BacktraceFullCallback, err_cb BacktraceErrorCallback,
@@ -47,7 +47,7 @@ $if openbsd {
stdin bool = true
}
fn bt_print_callback(data_ptr voidptr, pc usize, filename_ptr &char, line i32, fn_name_ptr &char) i32 {
fn bt_print_callback(data_ptr voidptr, pc uint, filename_ptr &char, line i32, fn_name_ptr &char) i32 {
data := unsafe { &BacktraceOptions(data_ptr) }
filename := if filename_ptr == unsafe { nil } {
'???'
+10 -10
View File
@@ -4,22 +4,22 @@ module builtin
// Note: they will NOT be used, since calls to them are wrapped with `$if gcboehm ? { }`
fn C.GC_MALLOC(n usize) voidptr
fn C.GC_MALLOC(n uint) voidptr
fn C.GC_MALLOC_ATOMIC(n usize) voidptr
fn C.GC_MALLOC_ATOMIC(n uint) voidptr
fn C.GC_MALLOC_UNCOLLECTABLE(n usize) voidptr
fn C.GC_MALLOC_UNCOLLECTABLE(n uint) voidptr
fn C.GC_REALLOC(ptr voidptr, n usize) voidptr
fn C.GC_REALLOC(ptr voidptr, n uint) voidptr
fn C.GC_FREE(ptr voidptr)
fn C.GC_memalign(align usize, size usize) voidptr
fn C.GC_memalign(align uint, size uint) voidptr
fn C.GC_get_heap_usage_safe(pheap_size &usize, pfree_bytes &usize, punmapped_bytes &usize, pbytes_since_gc &usize,
ptotal_bytes &usize)
fn C.GC_get_heap_usage_safe(pheap_size &uint, pfree_bytes &uint, punmapped_bytes &uint, pbytes_since_gc &uint,
ptotal_bytes &uint)
fn C.GC_get_memory_use() usize
fn C.GC_get_memory_use() uint
fn C.GC_gcollect()
@@ -67,7 +67,7 @@ pub fn gc_collect() {
}
}
pub type FnGC_WarnCB = fn (msg &char, arg usize)
pub type FnGC_WarnCB = fn (msg &char, arg uint)
fn C.GC_get_warn_proc() FnGC_WarnCB
fn C.GC_set_warn_proc(cb FnGC_WarnCB)
@@ -81,4 +81,4 @@ pub fn gc_get_warn_proc() {}
pub fn gc_set_warn_proc(cb FnGC_WarnCB) {}
// used by builtin_init
fn internal_gc_warn_proc_none(msg &char, arg usize) {}
fn internal_gc_warn_proc_none(msg &char, arg uint) {}
+7 -7
View File
@@ -57,9 +57,9 @@ fn C.WriteConsoleW(voidptr, &u16, C.DWORD, &C.DWORD, voidptr) bool
fn C.WriteFile(voidptr, &u8, C.DWORD, &C.DWORD, voidptr) bool
fn C.ExitProcess(u32)
fn C.GetProcessHeap() voidptr
fn C.HeapAlloc(voidptr, u32, usize) voidptr
fn C.HeapAlloc(voidptr, u32, uint) voidptr
fn C.HeapFree(voidptr, u32, voidptr) bool
fn C.CreateThread(attributes voidptr, stack_size usize, start_routine voidptr, arg voidptr, flags u32, thread_id &u32) voidptr
fn C.CreateThread(attributes voidptr, stack_size uint, start_routine voidptr, arg voidptr, flags u32, thread_id &u32) voidptr
fn C.v_builtin_windows_stream(index u32) voidptr
fn C._setmode(int, int) int
@@ -176,7 +176,7 @@ fn write_buf_to_console_kernel32(fd int, buf &u8, buf_len int) bool {
if isnil(heap) {
return false
}
wide_size := usize((wide_len + 1) * int(sizeof(u16)))
wide_size := uint((wide_len + 1) * int(sizeof(u16)))
mut wide_buf := &u16(C.HeapAlloc(heap, 0, wide_size))
if isnil(wide_buf) {
return false
@@ -259,7 +259,7 @@ fn write_buf_to_fd_windows_non_minimal(fd int, buf &u8, buf_len int) {
return
}
mut ptr := unsafe { buf }
mut remaining_bytes := isize(buf_len)
mut remaining_bytes := int(buf_len)
if write_buf_to_console(fd, ptr, int(remaining_bytes)) {
return
}
@@ -267,10 +267,10 @@ fn write_buf_to_fd_windows_non_minimal(fd int, buf &u8, buf_len int) {
if fd == 2 {
stream = voidptr(C.stderr)
}
mut x := isize(0)
mut x := int(0)
unsafe {
for remaining_bytes > 0 {
x = isize(C.fwrite(ptr, 1, remaining_bytes, stream))
x = int(C.fwrite(ptr, 1, remaining_bytes, stream))
if x <= 0 {
// GUI programs on Windows may not have a writable stdout/stderr stream.
break
@@ -390,7 +390,7 @@ struct C.MEMORY_BASIC_INFORMATION {
AllocationBase voidptr
}
fn C.VirtualQuery(address voidptr, buffer &C.MEMORY_BASIC_INFORMATION, length usize) usize
fn C.VirtualQuery(address voidptr, buffer &C.MEMORY_BASIC_INFORMATION, length uint) uint
fn C.GetModuleHandleW(name &u16) voidptr
+46 -42
View File
@@ -6,6 +6,10 @@ pub struct C.FILE {}
@[typedef]
pub struct C.qsort_callback_func {}
// C.ptrdiff_t is the signed pointer-width integer used by C interfaces.
@[typedef]
pub type C.ptrdiff_t = int
// Virtual C globals that are available through libc or generated C headers.
__global C.errno int
__global C.stdin &C.FILE
@@ -16,74 +20,74 @@ __global C._wyp &u64
// <string.h>
@[markused; noalloc]
fn C.memcpy(dest voidptr, const_src voidptr, n usize) voidptr
fn C.memcpy(dest voidptr, const_src voidptr, n uint) voidptr
@[markused; noalloc]
fn C.memcmp(const_s1 voidptr, const_s2 voidptr, n usize) i32
fn C.memcmp(const_s1 voidptr, const_s2 voidptr, n uint) i32
@[markused; noalloc]
fn C.memmove(dest voidptr, const_src voidptr, n usize) voidptr
fn C.memmove(dest voidptr, const_src voidptr, n uint) voidptr
@[markused; noalloc]
fn C.memset(str voidptr, c i32, n usize) voidptr
fn C.memset(str voidptr, c i32, n uint) voidptr
@[noalloc]
fn C.memchr(str voidptr, c i32, n usize) voidptr
fn C.memchr(str voidptr, c i32, n uint) voidptr
@[noalloc]
fn C.memmem(haystack voidptr, haystacklen usize, needle voidptr, needlelen usize) voidptr
fn C.memmem(haystack voidptr, haystacklen uint, needle voidptr, needlelen uint) voidptr
@[noalloc]
fn C.mempcpy(dest voidptr, src voidptr, n usize) voidptr
fn C.mempcpy(dest voidptr, src voidptr, n uint) voidptr
@[markused; trusted]
fn C.calloc(usize, usize) voidptr
fn C.calloc(uint, uint) voidptr
fn C.atoi(&char) i32
@[markused]
fn C.malloc(usize) voidptr
fn C.malloc(uint) voidptr
@[markused]
fn C.realloc(a voidptr, b usize) voidptr
fn C.realloc(a voidptr, b uint) voidptr
@[markused; noalloc]
fn C.free(ptr voidptr)
@[markused]
fn C.mmap(addr_length voidptr, length usize, prot i32, flags i32, fd i32, offset isize) voidptr
fn C.mmap(addr_length voidptr, length uint, prot i32, flags i32, fd i32, offset C.ptrdiff_t) voidptr
// C.munmap releases a memory mapping created by C.mmap.
fn C.munmap(addr_length voidptr, len usize) i32
fn C.munmap(addr_length voidptr, len uint) i32
@[markused]
fn C.mprotect(addr_length voidptr, len usize, prot i32) i32
fn C.mprotect(addr_length voidptr, len uint, prot i32) i32
@[markused]
fn C.aligned_alloc(align usize, size usize) voidptr
fn C.aligned_alloc(align uint, size uint) voidptr
// windows aligned memory functions
fn C._aligned_malloc(size usize, align usize) voidptr
fn C._aligned_malloc(size uint, align uint) voidptr
fn C._aligned_free(voidptr)
fn C._aligned_realloc(voidptr, size usize, align usize) voidptr
fn C._aligned_offset_malloc(size usize, align usize, offset usize) voidptr
fn C._aligned_offset_realloc(voidptr, size usize, align usize, offset usize) voidptr
fn C._aligned_msize(voidptr, align usize, offset usize) usize
fn C._aligned_recalloc(voidptr, num usize, size usize, align usize) voidptr
fn C._aligned_realloc(voidptr, size uint, align uint) voidptr
fn C._aligned_offset_malloc(size uint, align uint, offset uint) voidptr
fn C._aligned_offset_realloc(voidptr, size uint, align uint, offset uint) voidptr
fn C._aligned_msize(voidptr, align uint, offset uint) uint
fn C._aligned_recalloc(voidptr, num uint, size uint, align uint) voidptr
$if windows {
fn C.VirtualAlloc(voidptr, isize, u32, u32) voidptr
fn C.VirtualProtect(voidptr, isize, C.DWORD, &C.DWORD) bool
fn C.VirtualAlloc(voidptr, C.ptrdiff_t, u32, u32) voidptr
fn C.VirtualProtect(voidptr, C.ptrdiff_t, C.DWORD, &C.DWORD) bool
}
@[markused; noreturn; trusted]
fn C.exit(code i32)
@[markused]
fn C.qsort(base voidptr, items usize, item_size usize, cb C.qsort_callback_func)
fn C.qsort(base voidptr, items uint, item_size uint, cb C.qsort_callback_func)
@[markused; noalloc]
fn C.strlen(const_s &char) usize
fn C.strlen(const_s &char) uint
@[trusted]
fn C.isdigit(c i32) bool
@@ -110,7 +114,7 @@ fn C.fprintf(fstream &C.FILE, const_format &char, opt ...voidptr) i32
fn C.sprintf(str &char, const_format &char, opt ...voidptr) i32
@[markused]
fn C.snprintf(str &char, size usize, const_format &char, opt ...voidptr) i32
fn C.snprintf(str &char, size uint, const_format &char, opt ...voidptr) i32
fn C.wprintf(const_format &u16, opt ...voidptr) i32
@@ -134,7 +138,7 @@ fn C.fflush(fstream &C.FILE) i32
$if windows {
fn C.fseek(stream &C.FILE, offset i32, whence i32) i32
} $else {
fn C.fseek(stream &C.FILE, offset isize, whence i32) i32
fn C.fseek(stream &C.FILE, offset C.ptrdiff_t, whence i32) i32
}
// Coverage and profiling writers call these without a V AST reference.
@@ -143,10 +147,10 @@ fn C.fopen(filename &char, mode &char) &C.FILE
fn C.fileno(&C.FILE) i32
fn C.fread(ptr voidptr, item_size usize, items usize, stream &C.FILE) usize
fn C.fread(ptr voidptr, item_size uint, items uint, stream &C.FILE) uint
@[markused]
fn C.fwrite(const_ptr voidptr, item_size usize, items usize, stream &C.FILE) usize
fn C.fwrite(const_ptr voidptr, item_size uint, items uint, stream &C.FILE) uint
@[markused]
fn C.fclose(stream &C.FILE) i32
@@ -225,7 +229,7 @@ fn C.chdir(path &char) i32
fn C.rewind(stream &C.FILE) i32
fn C.ftell(&C.FILE) isize
fn C.ftell(&C.FILE) C.ptrdiff_t
fn C.stat(&char, voidptr) i32
@@ -246,7 +250,7 @@ fn C.fgetpos(&C.FILE, voidptr) i32
@[trusted]
fn C.sigemptyset() i32
fn C.getcwd(buf &char, size usize) &char
fn C.getcwd(buf &char, size uint) &char
@[trusted]
fn C.mktime() i32
@@ -304,7 +308,7 @@ fn C.strncasecmp(s &char, s2 &char, n i32) i32
fn C.strcasecmp(s &char, s2 &char) i32
fn C.strncmp(s &char, s2 &char, n usize) i32
fn C.strncmp(s &char, s2 &char, n uint) i32
@[trusted]
fn C.strerror(i32) &char
@@ -326,7 +330,7 @@ fn C.isatty(fd i32) i32
fn C.syscall(number i32, va ...voidptr) i32
fn C.sysctl(name &i32, namelen u32, oldp voidptr, oldlenp voidptr, newp voidptr, newlen usize) i32
fn C.sysctl(name &i32, namelen u32, oldp voidptr, oldlenp voidptr, newp voidptr, newlen uint) i32
@[trusted]
fn C._fileno(&C.FILE) i32
@@ -367,9 +371,9 @@ fn C.GetComputerNameW(&u16, &u32) bool
fn C.GetUserNameW(&u16, &u32) bool
@[trusted]
fn C.SendMessageTimeout() isize
fn C.SendMessageTimeout() C.ptrdiff_t
fn C.SendMessageTimeoutW(hWnd voidptr, msg u32, wParam &u16, lParam &u32, fuFlags u32, uTimeout u32, lpdwResult &u64) isize
fn C.SendMessageTimeoutW(hWnd voidptr, msg u32, wParam &u16, lParam &u32, fuFlags u32, uTimeout u32, lpdwResult &u64) C.ptrdiff_t
fn C.CreateProcessW(lpApplicationName &u16, lpCommandLine &u16, lpProcessAttributes voidptr, lpThreadAttributes voidptr,
bInheritHandles bool, dwCreationFlags u32, lpEnvironment voidptr, lpCurrentDirectory &u16, lpStartupInfo voidptr,
@@ -411,7 +415,7 @@ fn C.SymCleanup(hProcess voidptr)
fn C.MultiByteToWideChar(codePage u32, dwFlags u32, lpMultiMyteStr &char, cbMultiByte i32, lpWideCharStr &u16,
cchWideChar i32) i32
fn C.wcslen(str voidptr) usize
fn C.wcslen(str voidptr) uint
fn C.WideCharToMultiByte(codePage u32, dwFlags u32, lpWideCharStr &u16, cchWideChar i32, lpMultiByteStr &char,
cbMultiByte i32, lpDefaultChar &char, lpUsedDefaultChar &int) i32
@@ -533,7 +537,7 @@ $if macos {
fn C.pthread_self() voidptr
} $else {
@[markused]
fn C.pthread_self() usize
fn C.pthread_self() uint
}
@[markused]
@@ -546,7 +550,7 @@ fn C.pthread_join(thread voidptr, retval voidptr) i32
fn C.pthread_attr_init(attr voidptr) i32
@[markused]
fn C.pthread_attr_setstacksize(attr voidptr, stacksize usize) i32
fn C.pthread_attr_setstacksize(attr voidptr, stacksize uint) i32
@[markused]
fn C.pthread_attr_destroy(attr voidptr) i32
@@ -618,12 +622,12 @@ fn C.dispatch_time(u64, i64) u64
fn C.dispatch_release(voidptr)
// file descriptor based reading/writing
fn C.read(fd i32, buf voidptr, count usize) i32
fn C.read(fd i32, buf voidptr, count uint) i32
$if windows {
fn C.write(fd i32, const_buf voidptr, count u32) i32
} $else {
fn C.write(fd i32, const_buf voidptr, count usize) isize
fn C.write(fd i32, const_buf voidptr, count uint) C.ptrdiff_t
}
fn C.close(fd i32) i32
@@ -735,13 +739,13 @@ fn C.__get_errno_ptr() &i32
fn C.pthread_equal(t1 voidptr, t2 voidptr) i32
@[markused]
fn C.pthread_key_create(key &usize, destructor voidptr) i32
fn C.pthread_key_create(key &uint, destructor voidptr) i32
@[markused]
fn C.pthread_getspecific(key usize) voidptr
fn C.pthread_getspecific(key uint) voidptr
@[markused]
fn C.pthread_setspecific(key usize, value voidptr) i32
fn C.pthread_setspecific(key uint, value voidptr) i32
@[markused]
fn C.pthread_once(control voidptr, init_routine voidptr) i32
+22 -22
View File
@@ -39,11 +39,11 @@ fn string_index_byte(data &u8, size int, needle u8) int {
}
}
}
found := unsafe { C.memchr(data, i32(needle), usize(size)) }
found := unsafe { C.memchr(data, i32(needle), uint(size)) }
if isnil(found) {
return -1
}
return int(usize(found) - usize(data))
return int(uint(found) - uint(data))
}
}
@@ -122,7 +122,7 @@ fn string_bytes_equal(a &u8, b &u8, size int) bool {
return unsafe { ((a[0] ^ b[0]) | (a[size >> 1] ^ b[size >> 1]) | (a[size - 1] ^ b[size - 1])) == 0 }
}
}
return unsafe { C.memcmp(a, b, usize(size)) == 0 }
return unsafe { C.memcmp(a, b, uint(size)) == 0 }
}
// string_content_equal preserves vmemcmp's guarded and traced string comparison.
@@ -131,7 +131,7 @@ fn string_content_equal(a &u8, b &u8, size int) bool {
$if trace_vmemcmp ? {
return unsafe { vmemcmp(a, b, size) == 0 }
}
if size == 0 || usize(a) <= 0xFFFF || usize(b) <= 0xFFFF {
if size == 0 || uint(a) <= 0xFFFF || uint(b) <= 0xFFFF {
return true
}
return string_bytes_equal(a, b, size)
@@ -155,7 +155,7 @@ pub fn vstrlen_char(s &char) int {
// The memory areas *MUST NOT OVERLAP*. Use vmemmove, if the memory
// areas do overlap. vmemcpy returns a pointer to `dest`.
@[inline; unsafe]
pub fn vmemcpy(dest voidptr, const_src voidptr, n isize) voidptr {
pub fn vmemcpy(dest voidptr, const_src voidptr, n int) voidptr {
$if trace_vmemcpy ? {
C.fprintf(C.stderr, c'vmemcpy dest: %p src: %p n: %6ld\n', dest, const_src, n)
}
@@ -166,7 +166,7 @@ pub fn vmemcpy(dest voidptr, const_src voidptr, n isize) voidptr {
print_backtrace()
}
}
if n == 0 || usize(dest) <= 0xFFFF || usize(const_src) <= 0xFFFF {
if n == 0 || uint(dest) <= 0xFFFF || uint(const_src) <= 0xFFFF {
return dest
}
$if prod && !tinyc && !msvc && !native {
@@ -208,11 +208,11 @@ pub fn vmemcpy(dest voidptr, const_src voidptr, n isize) voidptr {
// `src` or `dest`, and the bytes are then copied from the temporary array
// to `dest`. vmemmove returns a pointer to `dest`.
@[inline; unsafe]
pub fn vmemmove(dest voidptr, const_src voidptr, n isize) voidptr {
pub fn vmemmove(dest voidptr, const_src voidptr, n int) voidptr {
$if trace_vmemmove ? {
C.fprintf(C.stderr, c'vmemmove dest: %p src: %p n: %6ld\n', dest, const_src, n)
}
if n == 0 || usize(dest) <= 0xFFFF || usize(const_src) <= 0xFFFF {
if n == 0 || uint(dest) <= 0xFFFF || uint(const_src) <= 0xFFFF {
return dest
}
$if prod && !tinyc && !msvc && !native {
@@ -279,11 +279,11 @@ pub fn vmemmove(dest voidptr, const_src voidptr, n isize) voidptr {
// You should use a function that performs comparisons in constant time for
// this.
@[inline; unsafe]
pub fn vmemcmp(const_s1 voidptr, const_s2 voidptr, n isize) int {
pub fn vmemcmp(const_s1 voidptr, const_s2 voidptr, n int) int {
$if trace_vmemcmp ? {
C.fprintf(C.stderr, c'vmemcmp s1: %p s2: %p n: %6ld\n', const_s1, const_s2, n)
}
if n == 0 || usize(const_s1) <= 0xFFFF || usize(const_s2) <= 0xFFFF {
if n == 0 || uint(const_s1) <= 0xFFFF || uint(const_s2) <= 0xFFFF {
return 0
}
unsafe {
@@ -294,7 +294,7 @@ pub fn vmemcmp(const_s1 voidptr, const_s2 voidptr, n isize) int {
// 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`.
@[inline; unsafe]
pub fn vmemset(s voidptr, c int, n isize) voidptr {
pub fn vmemset(s voidptr, c int, n int) voidptr {
$if trace_vmemset ? {
C.fprintf(C.stderr, c'vmemset s: %p c: %d n: %6ld\n', s, c, n)
}
@@ -304,7 +304,7 @@ pub fn vmemset(s voidptr, c int, n isize) voidptr {
print_backtrace()
}
}
if n == 0 || usize(s) <= 0xFFFF {
if n == 0 || uint(s) <= 0xFFFF {
return s
}
unsafe {
@@ -315,12 +315,12 @@ pub fn vmemset(s voidptr, c int, n isize) voidptr {
type FnSortCB = fn (const_a voidptr, const_b voidptr) int
@[inline; unsafe]
fn vsort_ptr_at(base voidptr, index usize, size usize) voidptr {
fn vsort_ptr_at(base voidptr, index uint, size uint) voidptr {
return unsafe { voidptr(&u8(base) + index * size) }
}
@[unsafe]
fn vstable_sort_merge(source voidptr, dest voidptr, left usize, mid usize, right usize, size usize, sort_cb FnSortCB) {
fn vstable_sort_merge(source voidptr, dest voidptr, left uint, mid uint, right uint, size uint, sort_cb FnSortCB) {
mut left_index := left
mut right_index := mid
mut dest_index := left
@@ -328,26 +328,26 @@ fn vstable_sort_merge(source voidptr, dest voidptr, left usize, mid usize, right
left_ptr := vsort_ptr_at(source, left_index, size)
right_ptr := vsort_ptr_at(source, right_index, size)
if sort_cb(left_ptr, right_ptr) <= 0 {
vmemcpy(vsort_ptr_at(dest, dest_index, size), left_ptr, isize(size))
vmemcpy(vsort_ptr_at(dest, dest_index, size), left_ptr, int(size))
left_index++
} else {
vmemcpy(vsort_ptr_at(dest, dest_index, size), right_ptr, isize(size))
vmemcpy(vsort_ptr_at(dest, dest_index, size), right_ptr, int(size))
right_index++
}
dest_index++
}
if left_index < mid {
vmemcpy(vsort_ptr_at(dest, dest_index, size), vsort_ptr_at(source, left_index, size),
isize((mid - left_index) * size))
int((mid - left_index) * size))
}
if right_index < right {
vmemcpy(vsort_ptr_at(dest, dest_index, size), vsort_ptr_at(source, right_index, size),
isize((right - right_index) * size))
int((right - right_index) * size))
}
}
@[inline; unsafe]
fn vqsort(base voidptr, nmemb usize, size usize, sort_cb FnSortCB) {
fn vqsort(base voidptr, nmemb uint, size uint, sort_cb FnSortCB) {
$if trace_vqsort ? {
C.fprintf(C.stderr, c'vqsort base: %p, nmemb: %6uld, size: %6uld, sort_cb: %p\n', base,
nmemb, size, sort_cb)
@@ -363,16 +363,16 @@ fn vqsort(base voidptr, nmemb usize, size usize, sort_cb FnSortCB) {
print_backtrace()
}
}
total_size := isize(nmemb * size)
total_size := int(nmemb * size)
buffer := malloc(total_size)
defer {
free(buffer)
}
mut source := base
mut dest := voidptr(buffer)
mut width := usize(1)
mut width := uint(1)
for width < nmemb {
mut left := usize(0)
mut left := uint(0)
for left < nmemb {
mid := if left + width < nmemb { left + width } else { nmemb }
right := if left + width + width < nmemb { left + width + width } else { nmemb }
+6 -6
View File
@@ -347,7 +347,7 @@ fn closure_slot_meta(exec_ptr voidptr) &voidptr {
fn closure_register_page(exec_page_start voidptr) {
unsafe {
node := &ClosurePage(malloc(sizeof(ClosurePage)))
node := &ClosurePage(malloc(int(sizeof(ClosurePage))))
*node = ClosurePage{
next: g_closure.pages
exec_page_start: exec_page_start
@@ -360,13 +360,13 @@ fn closure_is_managed(exec_ptr voidptr) bool {
if isnil(exec_ptr) {
return false
}
exec_addr := unsafe { usize(exec_ptr) }
exec_addr := unsafe { uint(exec_ptr) }
mut page := g_closure.pages
for page != unsafe { nil } {
page_addr := unsafe { usize(page.exec_page_start) }
if exec_addr >= page_addr && exec_addr < page_addr + usize(g_closure.v_page_size) {
page_addr := unsafe { uint(page.exec_page_start) }
if exec_addr >= page_addr && exec_addr < page_addr + uint(g_closure.v_page_size) {
slot_offset := exec_addr - page_addr
return slot_offset >= usize(closure_size) && slot_offset % usize(closure_size) == 0
return slot_offset >= uint(closure_size) && slot_offset % uint(closure_size) == 0
}
page = page.next
}
@@ -398,7 +398,7 @@ fn new_closure_lifetime_state_no_lock() &ClosureLifetimeState {
g_closure.free_lifetime_states = state.next_free
} else {
unsafe {
state = &ClosureLifetimeState(malloc(sizeof(ClosureLifetimeState)))
state = &ClosureLifetimeState(malloc(int(sizeof(ClosureLifetimeState))))
}
g_closure.lifetime_state_allocs++
}
+1 -1
View File
@@ -47,7 +47,7 @@ fn closure_alloc_platform() &u8 {
}
@[inline]
fn closure_memory_protect_platform(ptr voidptr, size isize, attr MemoryProtectAtrr) {
fn closure_memory_protect_platform(ptr voidptr, size int, attr MemoryProtectAtrr) {
$if freestanding {
// No memory protection in freestanding mode
} $else {
+1 -1
View File
@@ -29,7 +29,7 @@ fn closure_alloc_platform() &u8 {
}
@[inline]
fn closure_memory_protect_platform(ptr voidptr, size isize, attr MemoryProtectAtrr) {
fn closure_memory_protect_platform(ptr voidptr, size int, attr MemoryProtectAtrr) {
mut tmp := C.DWORD(0)
match attr {
.read_exec {
+2 -2
View File
@@ -75,7 +75,7 @@ fn test_threads_that_exited_are_not_scanned() {
@[noinline]
fn vgc_test_garbage(n int, size int) {
for _ in 0 .. n {
_ = vgc_malloc_noscan(usize(size))
_ = vgc_malloc_noscan(uint(size))
}
}
@@ -227,7 +227,7 @@ fn test_the_heap_stays_bounded_with_a_bounded_live_set() {
gc_collect()
base := vgc_memory_use()
mut ring := []string{len: 4096}
mut peak := usize(0)
mut peak := uint(0)
// About 100 MB of strings in total, of which about 1 MB stays live.
for i in 0 .. 400_000 {
ring[i % ring.len] = 'bounded live set '.repeat(1 + i % 30)
+5 -5
View File
@@ -9,7 +9,7 @@
// - total_bytes: the bytes allocated since the program started;
// - gc_memory_use(): the heap memory in use, heap_size - free_bytes.
// The test passes with `-gc boehm` as well.
const mb = usize(1024 * 1024)
const mb = uint(1024 * 1024)
// has_collector reports whether a collector manages the heap: with `-gc none`, all the values
// are 0.
@@ -37,19 +37,19 @@ fn allocate_garbage(n int) int {
// clear_dead_stack overwrites the stack below the caller, where dead frames can still hold
// pointers that a conservative collector would take for live ones.
@[noinline]
fn clear_dead_stack() usize {
buf := [4096]usize{}
fn clear_dead_stack() uint {
buf := [4096]uint{}
return buf[0] + buf[4095]
}
// memory_use_with_a_large_object allocates a large object, and returns the memory in use while
// the object is live. The object is garbage after the return.
@[noinline]
fn memory_use_with_a_large_object(size int) usize {
fn memory_use_with_a_large_object(size int) uint {
mut big := []u8{len: size}
big[0] = 1
big[size - 1] = 2
return gc_memory_use() + usize(big[0] + big[size - 1] - 3)
return gc_memory_use() + uint(big[0] + big[size - 1] - 3)
}
fn test_bytes_since_gc_and_total_bytes_count_the_allocations() {
+5 -5
View File
@@ -24,7 +24,7 @@ fn vgc_test_is_marked(p voidptr) bool {
if span == unsafe { nil } || span.mark_bits == unsafe { nil } {
return false
}
index := u32((usize(p) - span.base) / usize(span.elem_size))
index := u32((uint(p) - span.base) / uint(span.elem_size))
return C.vgc_bitmap_get(span.mark_bits, index) != 0
}
@@ -44,8 +44,8 @@ fn test_the_globals_of_vgc_are_not_roots() {
// The cache slot of a thread that does not exist.
slot := vgc_max_threads - 1
assert !vgc_heap.caches[slot].registered
vgc_heap.caches[slot].stack_base = usize(p)
vgc_heap.caches[slot].stack_hi = usize(p)
vgc_heap.caches[slot].stack_base = uint(p)
vgc_heap.caches[slot].stack_hi = uint(p)
marked := vgc_test_marked_from_data(p)
vgc_heap.caches[slot].stack_base = 0
vgc_heap.caches[slot].stack_hi = 0
@@ -61,7 +61,7 @@ fn test_the_tiny_block_of_a_thread_is_a_root() {
idx := C.vgc_get_cache_idx()
tiny := vgc_heap.caches[idx].tiny
assert tiny != 0
assert usize(p) >= tiny && usize(p) < tiny + vgc_tiny_size
assert uint(p) >= tiny && uint(p) < tiny + vgc_tiny_size
// Mark from all the roots, without this thread's stack.
lo := vgc_heap.caches[idx].stack_lo
hi := vgc_heap.caches[idx].stack_hi
@@ -82,7 +82,7 @@ fn test_the_heap_is_far_from_small_numbers() {
// Windows hands out the lowest free addresses first: with TinyCC, whose executables
// start at 4 MB, the heap started at about 9 MB, where words in the data segment
// that hold numbers like 0x2000537 point. The arenas come from the top now.
assert vgc_arena_lo > usize(1) << 32
assert vgc_arena_lo > uint(1) << 32
}
}
}
+1 -1
View File
@@ -20,7 +20,7 @@ fn C.GC_set_all_interior_pointers(int)
fn C.GC_set_pages_executable(int)
@[c_extern]
fn C.GC_set_free_space_divisor(usize)
fn C.GC_set_free_space_divisor(uint)
@[c_extern]
fn C.GC_enable_incremental()
+2 -2
View File
@@ -14,7 +14,7 @@ __global vgc_global_aligned_cells = &[1]VgcGlobalAlignedCell{init: VgcGlobalAlig
fn test_global_aligned_array_is_scanned_by_vgc() {
$if vgc ? {
assert usize(voidptr(vgc_global_aligned_cells)) % 512 == 0
assert uint(voidptr(vgc_global_aligned_cells)) % 512 == 0
span := vgc_find_span(voidptr(vgc_global_aligned_cells))
assert span != unsafe { nil }
assert !span.noscan
@@ -43,7 +43,7 @@ fn vgc_test_object_is_marked(value voidptr) bool {
if span == unsafe { nil } || span.mark_bits == unsafe { nil } {
return false
}
index := (usize(value) - span.base) / usize(span.elem_size)
index := (uint(value) - span.base) / uint(span.elem_size)
return unsafe { span.mark_bits[index / 8] } & u8(1 << (index % 8)) != 0
}
return false
+3 -2
View File
@@ -9,17 +9,18 @@ pub struct VContext {
// ptr_str returns a string with the address of `ptr`.
pub fn ptr_str(ptr voidptr) string {
buf1 := u64_to_hex_no_leading_zeros(u64(usize(ptr)), 16)
buf1 := u64_to_hex_no_leading_zeros(u64(uint(ptr)), 16)
return buf1
}
// The legacy receiver keeps existing isize method calls working during migration.
// str returns the string equivalent of x.
pub fn (x isize) str() string {
return i64(x).str()
}
// str returns the string equivalent of x.
pub fn (x usize) str() string {
pub fn (x uint) str() string {
return u64(x).str()
}
+8 -8
View File
@@ -7,7 +7,7 @@
module builtin
// A page more than an arena: every such object takes an arena of its own.
const vgc_test_big_size = usize(vgc_arena_size + vgc_page_size)
const vgc_test_big_size = uint(vgc_arena_size + vgc_page_size)
// vgc_test_big_heap_enabled reports whether the test that needs more than 4 GB of address space
// runs. Its objects are never written, so on Linux, macOS and the BSDs they take address space,
@@ -38,14 +38,14 @@ fn vgc_test_allocate_big(n int) []voidptr {
objs << p
}
for p in objs {
last := voidptr(usize(p) + vgc_test_big_size - 1)
last := voidptr(uint(p) + vgc_test_big_size - 1)
unsafe {
*(&u8(p)) = 1
*(&u8(last)) = 2
}
span := vgc_find_span(p)
assert span != unsafe { nil }
assert span.base == usize(p)
assert span.base == uint(p)
assert vgc_find_span(last) == span
}
return objs
@@ -54,8 +54,8 @@ fn vgc_test_allocate_big(n int) []voidptr {
// vgc_test_clear_dead_stack overwrites the stack below the caller, where dead frames can still
// hold pointers that the conservative stack scan would take for live ones.
@[noinline]
fn vgc_test_clear_dead_stack() usize {
buf := [4096]usize{}
fn vgc_test_clear_dead_stack() uint {
buf := [4096]uint{}
return buf[0] + buf[4095]
}
@@ -79,13 +79,13 @@ fn vgc_test_drop(mut objs []voidptr) {
fn test_a_pointer_past_the_first_64_mb_of_an_object_is_found() {
$if vgc ? {
size := usize(96 * 1024 * 1024)
size := uint(96 * 1024 * 1024)
p := vgc_malloc_noscan_opts(size, false)
assert p != unsafe { nil }
span := vgc_find_span(p)
assert span != unsafe { nil }
assert vgc_find_span(voidptr(usize(p) + 80 * 1024 * 1024)) == span
assert vgc_find_span(voidptr(usize(p) + size - 1)) == span
assert vgc_find_span(voidptr(uint(p) + 80 * 1024 * 1024)) == span
assert vgc_find_span(voidptr(uint(p) + size - 1)) == span
}
}
+14 -13
View File
@@ -5,9 +5,10 @@ import dlmalloc
__global global_allocator dlmalloc.Dlmalloc
__global global_allocator_ready bool
// memcpy copies n bytes from const_src to dest.
@[export: 'memcpy']
@[unsafe]
pub fn memcpy(dest voidptr, const_src voidptr, n usize) voidptr {
pub fn memcpy(dest voidptr, const_src voidptr, n uint) voidptr {
dest_ := unsafe { &u8(dest) }
src_ := unsafe { &u8(const_src) }
unsafe {
@@ -22,7 +23,7 @@ pub fn memcpy(dest voidptr, const_src voidptr, n usize) voidptr {
// initializes already allocate, so it cannot wait for any of them.
@[export: 'malloc']
@[unsafe]
fn __malloc(n usize) voidptr {
fn __malloc(n uint) voidptr {
if !global_allocator_ready {
init_global_allocator()
}
@@ -31,21 +32,21 @@ fn __malloc(n usize) voidptr {
@[export: 'strlen']
@[unsafe]
fn strlen(const_s voidptr) usize {
fn strlen(const_s voidptr) uint {
s := unsafe { &u8(const_s) }
mut i := 0
for ; unsafe { s[i] } != 0; i++ {
}
return usize(i)
return uint(i)
}
@[export: 'realloc']
@[unsafe]
fn realloc(old_area voidptr, new_size usize) voidptr {
fn realloc(old_area voidptr, new_size uint) voidptr {
if old_area == 0 {
return unsafe { __malloc(new_size) }
}
if new_size == usize(0) {
if new_size == uint(0) {
unsafe { __free(old_area) }
return 0
}
@@ -54,7 +55,7 @@ fn realloc(old_area voidptr, new_size usize) voidptr {
@[export: 'memset']
@[unsafe]
fn memset(s voidptr, c int, n usize) voidptr {
fn memset(s voidptr, c int, n uint) voidptr {
mut s_ := unsafe { &char(s) }
for i in 0 .. int(n) {
unsafe {
@@ -68,10 +69,10 @@ fn memset(s voidptr, c int, n usize) voidptr {
// needs no temporary buffer.
@[export: 'memmove']
@[unsafe]
fn memmove(dest voidptr, const_src voidptr, n usize) voidptr {
fn memmove(dest voidptr, const_src voidptr, n uint) voidptr {
dest_ := unsafe { &u8(dest) }
src_ := unsafe { &u8(const_src) }
if usize(dest_) <= usize(src_) || usize(dest_) >= usize(src_) + n {
if uint(dest_) <= uint(src_) || uint(dest_) >= uint(src_) + n {
for i in 0 .. int(n) {
unsafe {
dest_[i] = src_[i]
@@ -89,7 +90,7 @@ fn memmove(dest voidptr, const_src voidptr, n usize) voidptr {
@[export: 'calloc']
@[unsafe]
fn __calloc(nmemb usize, size usize) voidptr {
fn __calloc(nmemb uint, size uint) voidptr {
new_area := unsafe { __malloc(nmemb * size) }
if new_area != 0 {
unsafe { memset(new_area, 0, nmemb * size) }
@@ -104,7 +105,7 @@ fn getchar() int {
}
@[export: 'memcmp']
fn memcmp(const_a voidptr, const_b voidptr, n usize) int {
fn memcmp(const_a voidptr, const_b voidptr, n uint) int {
a_ := unsafe { &u8(const_a) }
b_ := unsafe { &u8(const_b) }
for i in 0 .. int(n) {
@@ -132,7 +133,7 @@ fn vsprintf(str &char, format &char, ap &u8) int {
panic('vsprintf(): string interpolation is not supported in `-freestanding`')
}
fn vsnprintf(str &char, size usize, format &char, ap &u8) int {
fn vsnprintf(str &char, size uint, format &char, ap &u8) int {
panic('vsnprintf(): string interpolation is not supported in `-freestanding`')
}
@@ -172,7 +173,7 @@ fn __exit(code int) {
// __qsort takes the C callback type: a V `FnSortCB` returns a 64-bit `int`.
@[export: 'qsort']
fn __qsort(base voidptr, nmemb usize, size usize, sort_cb C.qsort_callback_func) {
fn __qsort(base voidptr, nmemb uint, size uint, sort_cb C.qsort_callback_func) {
panic('qsort() is not yet implemented in `-freestanding`')
}
+43 -43
View File
@@ -1,16 +1,16 @@
module builtin
struct LinuxMmapArgs {
addr usize
len usize
prot usize
flags usize
fd usize
offset usize
addr uint
len uint
prot uint
flags uint
fd uint
offset uint
}
fn split_int_errno(rc_in usize) (i64, Errno) {
rc := isize(rc_in)
fn split_int_errno(rc_in uint) (i64, Errno) {
rc := int(rc_in)
if rc < 0 {
return i64(-1), unsafe { Errno(-rc) }
}
@@ -19,64 +19,64 @@ fn split_int_errno(rc_in usize) (i64, Errno) {
// 3 sys_read
fn sys_read(fd i64, buf &u8, count u64) (i64, Errno) {
return split_int_errno(sys_call3(3, usize(fd), usize(buf), usize(count)))
return split_int_errno(sys_call3(3, uint(fd), uint(buf), uint(count)))
}
// 4 sys_write.
pub fn sys_write(fd i64, buf &u8, count u64) (i64, Errno) {
return split_int_errno(sys_call3(4, usize(fd), usize(buf), usize(count)))
return split_int_errno(sys_call3(4, uint(fd), uint(buf), uint(count)))
}
// 5 sys_open
fn sys_open(filename &u8, flags i64, mode int) (i64, Errno) {
return split_int_errno(sys_call3(5, usize(filename), usize(flags), usize(mode)))
return split_int_errno(sys_call3(5, uint(filename), uint(flags), uint(mode)))
}
// 6 sys_close
fn sys_close(fd i64) Errno {
return unsafe { Errno(-isize(sys_call1(6, usize(fd)))) }
return unsafe { Errno(-int(sys_call1(6, uint(fd)))) }
}
// 90 sys_mmap
fn sys_mmap(addr &u8, len u64, prot MemProt, flags MapFlags, fildes i64, off u64) (&u8, Errno) {
args := LinuxMmapArgs{
addr: usize(addr)
len: usize(len)
prot: usize(prot)
flags: usize(flags)
fd: usize(fildes)
offset: usize(off)
addr: uint(addr)
len: uint(len)
prot: uint(prot)
flags: uint(flags)
fd: uint(fildes)
offset: uint(off)
}
rc := sys_call1(90, usize(&args))
rc := sys_call1(90, uint(&args))
a, e := split_int_errno(rc)
return unsafe { &u8(usize(a)) }, e
return unsafe { &u8(uint(a)) }, e
}
// 91 sys_munmap
fn sys_munmap(addr voidptr, len u64) Errno {
return unsafe { Errno(-isize(sys_call2(91, usize(addr), usize(len)))) }
return unsafe { Errno(-int(sys_call2(91, uint(addr), uint(len)))) }
}
// 163 sys_mremap
fn sys_mremap(old_addr voidptr, old_len u64, new_len u64, flags u64) (&u8, Errno) {
rc := sys_call4(163, usize(old_addr), usize(old_len), usize(new_len), usize(flags))
rc := sys_call4(163, uint(old_addr), uint(old_len), uint(new_len), uint(flags))
a, e := split_int_errno(rc)
return unsafe { &u8(usize(a)) }, e
return unsafe { &u8(uint(a)) }, e
}
// 42 sys_pipe
fn sys_pipe(filedes &int) Errno {
return unsafe { Errno(isize(sys_call1(42, usize(filedes)))) }
return unsafe { Errno(int(sys_call1(42, uint(filedes)))) }
}
// 158 sys_sched_yield
fn sys_sched_yield() Errno {
return unsafe { Errno(isize(sys_call0(158))) }
return unsafe { Errno(int(sys_call0(158))) }
}
// 219 sys_madvise
fn sys_madvise(addr voidptr, len u64, advice int) Errno {
return unsafe { Errno(isize(sys_call3(219, usize(addr), usize(len), usize(advice)))) }
return unsafe { Errno(int(sys_call3(219, uint(addr), uint(len), uint(advice)))) }
}
// 20 sys_getpid
@@ -96,18 +96,18 @@ fn sys_vfork() int {
// 63 sys_dup2
fn sys_dup2(oldfd int, newfd int) (i64, Errno) {
return split_int_errno(sys_call2(63, usize(oldfd), usize(newfd)))
return split_int_errno(sys_call2(63, uint(oldfd), uint(newfd)))
}
// 11 sys_execve
fn sys_execve(filename &u8, argv []&u8, envp []&u8) int {
return int(sys_call3(11, usize(filename), usize(argv.data), usize(envp.data)))
return int(sys_call3(11, uint(filename), uint(argv.data), uint(envp.data)))
}
// 1 sys_exit
@[noreturn]
fn sys_exit(ec int) {
sys_call1(1, usize(ec))
sys_call1(1, uint(ec))
for {}
}
@@ -119,13 +119,13 @@ fn sys_getuid() int {
// 284 sys_waitid
fn sys_waitid(which WiWhich, pid int, infop &int, options int, ru voidptr) Errno {
return unsafe {
Errno(isize(sys_call5(284, usize(which), usize(pid), usize(infop), usize(options),
usize(ru))))
Errno(int(sys_call5(284, uint(which), uint(pid), uint(infop), uint(options),
uint(ru))))
}
}
fn sys_call0(scn usize) usize {
mut res := usize(0)
fn sys_call0(scn uint) uint {
mut res := uint(0)
asm volatile i386 {
mov eax, scn
int 0x80
@@ -138,8 +138,8 @@ fn sys_call0(scn usize) usize {
return res
}
fn sys_call1(scn usize, arg1 usize) usize {
mut res := usize(0)
fn sys_call1(scn uint, arg1 uint) uint {
mut res := uint(0)
asm volatile i386 {
mov eax, scn
mov ebx, arg1
@@ -155,8 +155,8 @@ fn sys_call1(scn usize, arg1 usize) usize {
return res
}
fn sys_call2(scn usize, arg1 usize, arg2 usize) usize {
mut res := usize(0)
fn sys_call2(scn uint, arg1 uint, arg2 uint) uint {
mut res := uint(0)
asm volatile i386 {
mov eax, scn
mov ebx, arg1
@@ -175,8 +175,8 @@ fn sys_call2(scn usize, arg1 usize, arg2 usize) usize {
return res
}
fn sys_call3(scn usize, arg1 usize, arg2 usize, arg3 usize) usize {
mut res := usize(0)
fn sys_call3(scn uint, arg1 uint, arg2 uint, arg3 uint) uint {
mut res := uint(0)
asm volatile i386 {
mov eax, scn
mov ebx, arg1
@@ -198,8 +198,8 @@ fn sys_call3(scn usize, arg1 usize, arg2 usize, arg3 usize) usize {
return res
}
fn sys_call4(scn usize, arg1 usize, arg2 usize, arg3 usize, arg4 usize) usize {
mut res := usize(0)
fn sys_call4(scn uint, arg1 uint, arg2 uint, arg3 uint, arg4 uint) uint {
mut res := uint(0)
asm volatile i386 {
mov eax, scn
mov ebx, arg1
@@ -224,8 +224,8 @@ fn sys_call4(scn usize, arg1 usize, arg2 usize, arg3 usize, arg4 usize) usize {
return res
}
fn sys_call5(scn usize, arg1 usize, arg2 usize, arg3 usize, arg4 usize, arg5 usize) usize {
mut res := usize(0)
fn sys_call5(scn uint, arg1 uint, arg2 uint, arg3 uint, arg4 uint, arg5 uint) uint {
mut res := uint(0)
asm volatile i386 {
mov eax, scn
mov ebx, arg1
+6 -6
View File
@@ -30,7 +30,7 @@ fn mm_free(addr &u8) Errno {
}
}
fn system_alloc(_ voidptr, size usize) (voidptr, usize, u32) {
fn system_alloc(_ voidptr, size uint) (voidptr, uint, u32) {
// BEGIN CONSTS
// the constants need to be here, since the initialization of other constants,
// which happen before these ones would, require malloc
@@ -46,21 +46,21 @@ fn system_alloc(_ voidptr, size usize) (voidptr, usize, u32) {
return unsafe { nil }, 0, 0
}
fn system_remap(_ voidptr, ptr voidptr, oldsize usize, newsize usize, can_move bool) voidptr {
fn system_remap(_ voidptr, ptr voidptr, oldsize uint, newsize uint, can_move bool) voidptr {
return unsafe { nil }
}
fn system_free_part(_ voidptr, ptr voidptr, oldsize usize, newsize usize) bool {
fn system_free_part(_ voidptr, ptr voidptr, oldsize uint, newsize uint) bool {
_, e := sys_mremap(ptr, u64(oldsize), u64(newsize), 0)
if e == .enoerror {
return true
}
e2 := sys_munmap(voidptr(usize(ptr) + newsize), u64(oldsize - newsize))
e2 := sys_munmap(voidptr(uint(ptr) + newsize), u64(oldsize - newsize))
return e2 == .enoerror
}
fn system_free(_ voidptr, ptr voidptr, size usize) bool {
fn system_free(_ voidptr, ptr voidptr, size uint) bool {
unsafe {
return sys_munmap(ptr, u64(size)) == .enoerror
}
@@ -74,7 +74,7 @@ fn system_allocates_zeros(_ voidptr) bool {
return true
}
fn system_page_size(_ voidptr) usize {
fn system_page_size(_ voidptr) uint {
return 4096
}
+4 -2
View File
@@ -29,7 +29,8 @@ pub fn mm_free(addr &u8) Errno {
return sys_munmap(ap, size)
}
pub fn mem_copy(dest0 voidptr, src0 voidptr, n isize) voidptr {
// mem_copy copies n bytes from src0 to dest0.
pub fn mem_copy(dest0 voidptr, src0 voidptr, n int) voidptr {
mut dest := &u8(dest0)
src := &u8(src0)
for i in 0 .. n {
@@ -38,8 +39,9 @@ pub fn mem_copy(dest0 voidptr, src0 voidptr, n isize) voidptr {
return dest0
}
// malloc allocates n bytes of memory.
@[unsafe]
pub fn malloc(n isize) &u8 {
pub fn malloc(n int) &u8 {
if n < 0 {
panic('malloc(<0)')
}
+3 -3
View File
@@ -468,9 +468,9 @@ fn (m &map) key_to_index(pkey voidptr) (u32, u32) {
if voidptr(m.hash_fn) == unsafe { nil } {
unsafe {
p := &u64(m)
prev2 := (&u64(usize(m) - usize(16)))[0]
prev1 := (&u64(usize(m) - usize(8)))[0]
panic('map.hash_fn is nil map_ptr=${usize(m)} key_bytes=${m.key_bytes} value_bytes=${m.value_bytes} even_index=${m.even_index} shift=${m.shift} metas=${usize(m.metas)} prev2=${prev2} prev1=${prev1} w0=${p[0]} w1=${p[1]} w2=${p[2]} w3=${p[3]} w4=${p[4]} w5=${p[5]} w6=${p[6]} w7=${p[7]} hash_fn=${usize(voidptr(m.hash_fn))}')
prev2 := (&u64(uint(m) - uint(16)))[0]
prev1 := (&u64(uint(m) - uint(8)))[0]
panic('map.hash_fn is nil map_ptr=${uint(m)} key_bytes=${m.key_bytes} value_bytes=${m.value_bytes} even_index=${m.even_index} shift=${m.shift} metas=${uint(m.metas)} prev2=${prev2} prev1=${prev1} w0=${p[0]} w1=${p[1]} w2=${p[2]} w3=${p[3]} w4=${p[4]} w5=${p[5]} w6=${p[6]} w7=${p[7]} hash_fn=${uint(voidptr(m.hash_fn))}')
}
}
hash := if voidptr(m.hash_fn) == voidptr(map_hash_string) {
+11 -11
View File
@@ -7,7 +7,7 @@ struct AlignedCloneCell {
fn clone_aligned_map_key(destination voidptr, source voidptr) {
// The raw map callback copies the complete aligned key, including its padding.
unsafe { vmemcpy(destination, source, sizeof(AlignedCloneCell)) }
unsafe { vmemcpy(destination, source, int(sizeof(AlignedCloneCell))) }
}
fn assert_aligned_map_clone_storage(value &map) {
@@ -16,25 +16,25 @@ fn assert_aligned_map_clone_storage(value &map) {
if value.data.count == 0 {
return
}
assert usize(value.data.key_values.keys) % 64 == 0
assert usize(value.data.key_values.values) % 64 == 0
assert uint(value.data.key_values.keys) % 64 == 0
assert uint(value.data.key_values.values) % 64 == 0
keys := value.keys()
values := value.values()
assert keys.data_alignment() == 64
assert values.data_alignment() == 64
assert usize(keys.data) % 64 == 0
assert usize(values.data) % 64 == 0
assert uint(keys.data) % 64 == 0
assert uint(values.data) % 64 == 0
for i in 0 .. keys.len {
// Raw map exports have the same aligned element layout as the input cells.
key := unsafe { &AlignedCloneCell(&u8(keys.data) + i * int(sizeof(AlignedCloneCell))) }
item := unsafe { &AlignedCloneCell(&u8(values.data) + i * int(sizeof(AlignedCloneCell))) }
assert usize(key) % 64 == 0
assert usize(item) % 64 == 0
assert uint(key) % 64 == 0
assert uint(item) % 64 == 0
assert key.value == u64(i + 1)
assert item.value == key.value * 10
zero := AlignedCloneCell{}
stored := unsafe { &AlignedCloneCell(value.get(key, &zero)) }
assert usize(stored) % 64 == 0
assert uint(stored) % 64 == 0
assert stored.value == item.value
}
unsafe {
@@ -87,13 +87,13 @@ fn test_sparse_typed_map_clone_keeps_aligned_values() {
assert copied['only'].value == 42
// Inspect each map element's address before any subsequent map mutation.
first_address := unsafe { voidptr(&copied['only']) }
assert usize(first_address) % 64 == 0
assert uint(first_address) % 64 == 0
values := copied.values()
assert usize(values.data) % 64 == 0
assert uint(values.data) % 64 == 0
assert values[0].value == 42
copied['next'] = AlignedCloneCell{ value: 99 }
next_address := unsafe { voidptr(&copied['next']) }
assert usize(next_address) % 64 == 0
assert uint(next_address) % 64 == 0
assert 'next' !in original
unsafe {
values.free()
+11 -11
View File
@@ -408,7 +408,7 @@ fn new_map(key_bytes int, value_bytes int, hash_fn MapHashFn, key_eq_fn MapEqFn,
}
fn new_map_aligned(key_bytes int, value_bytes int, hash_fn MapHashFn, key_eq_fn MapEqFn,
clone_fn MapCloneFn, free_fn MapFreeFn, key_alignment usize, value_alignment usize) map {
clone_fn MapCloneFn, free_fn MapFreeFn, key_alignment uint, value_alignment uint) map {
mut result := new_map(key_bytes, value_bytes, hash_fn, key_eq_fn, clone_fn, free_fn)
result.data.key_values.key_alignment = data_alignment_exponent(key_alignment)
result.data.key_values.value_alignment = data_alignment_exponent(value_alignment)
@@ -493,9 +493,9 @@ fn (mut m VMapData) clear() {
fn (m &VMapData) panic_nil_map_hash_fn() {
unsafe {
p := &u64(m)
prev2 := (&u64(usize(m) - usize(16)))[0]
prev1 := (&u64(usize(m) - usize(8)))[0]
panic('map.hash_fn is nil map_ptr=${usize(m)} key_bytes=${m.key_bytes} value_bytes=${m.value_bytes} even_index=${m.even_index} shift=${m.shift} metas=${usize(m.metas)} prev2=${prev2} prev1=${prev1} w0=${p[0]} w1=${p[1]} w2=${p[2]} w3=${p[3]} w4=${p[4]} w5=${p[5]} w6=${p[6]} w7=${p[7]} hash_fn=${usize(voidptr(m.hash_fn))}')
prev2 := (&u64(uint(m) - uint(16)))[0]
prev1 := (&u64(uint(m) - uint(8)))[0]
panic('map.hash_fn is nil map_ptr=${uint(m)} key_bytes=${m.key_bytes} value_bytes=${m.value_bytes} even_index=${m.even_index} shift=${m.shift} metas=${uint(m.metas)} prev2=${prev2} prev1=${prev1} w0=${p[0]} w1=${p[1]} w2=${p[2]} w3=${p[3]} w4=${p[4]} w5=${p[5]} w6=${p[6]} w7=${p[7]} hash_fn=${uint(voidptr(m.hash_fn))}')
}
}
@@ -760,7 +760,7 @@ fn (mut m VMapData) cached_rehash(old_cap u32) {
m.meta_greater(index, meta, kv_index)
}
$if prealloc {
unsafe { prealloc_discard_pages(old_metas, usize(sizeof(u32)) * usize(old_cap + 2 + old_extra_metas)) }
unsafe { prealloc_discard_pages(old_metas, uint(sizeof(u32)) * uint(old_cap + 2 + old_extra_metas)) }
}
unsafe { free(old_metas) }
}
@@ -1083,7 +1083,7 @@ fn dense_array_allocate(size u64, alignment u8) &u8 {
if alignment == 0 {
return unsafe { malloc(__at_least_one(size)) }
}
return alloc_array_data_aligned(size, usize(1) << alignment, false)
return alloc_array_data_aligned(size, uint(1) << alignment, false)
}
@[inline; unsafe]
@@ -1125,7 +1125,7 @@ fn (m &VMapData) keys() array {
mut keys := if alignment == 0 {
__new_array(m.count, 0, m.key_bytes)
} else {
__new_array_aligned(m.count, 0, m.key_bytes, usize(1) << alignment)
__new_array_aligned(m.count, 0, m.key_bytes, uint(1) << alignment)
}
mut item := unsafe { &u8(keys.data) }
if m.key_values.deletes == 0 {
@@ -1161,7 +1161,7 @@ fn (m &VMapData) values() array {
mut values := if alignment == 0 {
__new_array(m.count, 0, m.value_bytes)
} else {
__new_array_aligned(m.count, 0, m.value_bytes, usize(1) << alignment)
__new_array_aligned(m.count, 0, m.value_bytes, uint(1) << alignment)
}
if m.count == 0 {
return values
@@ -1303,7 +1303,7 @@ pub fn (m &map) free() {
@[unsafe]
fn (m &VMapData) free() {
$if prealloc {
unsafe { prealloc_discard_pages(m.metas, usize(sizeof(u32)) * usize(m.even_index + 2 + m.extra_metas)) }
unsafe { prealloc_discard_pages(m.metas, uint(sizeof(u32)) * uint(m.even_index + 2 + m.extra_metas)) }
}
unsafe { free(m.metas) }
unsafe {
@@ -1336,14 +1336,14 @@ fn (m &VMapData) free() {
}
if m.key_values.keys != nil {
$if prealloc {
prealloc_discard_pages(m.key_values.keys, usize(m.key_values.cap) * usize(m.key_bytes))
prealloc_discard_pages(m.key_values.keys, uint(m.key_values.cap) * uint(m.key_bytes))
}
dense_array_free(m.key_values.keys, m.key_values.key_alignment)
m.key_values.keys = nil
}
if m.key_values.values != nil {
$if prealloc {
prealloc_discard_pages(m.key_values.values, usize(m.key_values.cap) * usize(m.value_bytes))
prealloc_discard_pages(m.key_values.values, uint(m.key_values.cap) * uint(m.value_bytes))
}
dense_array_free(m.key_values.values, m.key_values.value_alignment)
m.key_values.values = nil
+1 -1
View File
@@ -44,7 +44,7 @@ fn test_dense_array_zero_value_size_with_every_c_compiler() {
key_bytes: int(sizeof(int))
value_bytes: 0
cap: 8
keys: unsafe { malloc(8 * isize(sizeof(int))) }
keys: unsafe { malloc(8 * int(sizeof(int))) }
values: unsafe { malloc(1) }
}
// DenseArray stores raw key bytes; fill and inspect its integer slots directly.
+29
View File
@@ -0,0 +1,29 @@
module builtin
fn test_platform_uint_preserves_unsigned_range() {
assert sizeof(uint) == sizeof(int)
assert sizeof(uint) == sizeof(voidptr)
maximum := ~uint(0)
assert maximum > uint(max_int)
assert maximum >> (sizeof(uint) * 8 - 1) == 1
assert maximum + uint(1) == 0
$if x64 || arm64 {
assert maximum.str() == '18446744073709551615'
assert uint(1) << 40 == u64(1099511627776)
} $else $if x32 || arm32 {
assert maximum.str() == '4294967295'
}
mut values := map[uint]int{}
values[maximum] = -1
assert values[maximum] == -1
}
fn test_platform_uint_pointer_round_trip() {
value := 42
address := uint(&value)
// Recover and dereference the pointer from its integer address.
unsafe {
assert &int(address) == &value
assert *(&int(address)) == value
}
}
+63 -63
View File
@@ -15,14 +15,14 @@ fn C.v_prealloc_atomic_add_i64(ptr &i64, delta i64) i64
fn C.v_prealloc_atomic_load_i64(ptr &i64) i64
fn C.madvise(addr voidptr, length usize, advice int) int
fn C.madvise(addr voidptr, length uint, advice int) int
// prealloc_discard_pages releases physical backing for dead arena storage on
// macOS and Linux. Only complete pages inside the range are discarded; their
// addresses remain reserved and writable until the containing arena is freed.
// No surviving value may depend on the contents of this range.
@[unsafe]
pub fn prealloc_discard_pages(start voidptr, size usize) {
pub fn prealloc_discard_pages(start voidptr, size uint) {
$if prealloc && !freestanding && !vinix && (macos || linux) {
if size < 65_536 || start == unsafe { nil } {
return
@@ -31,9 +31,9 @@ pub fn prealloc_discard_pages(start voidptr, size usize) {
if page_bytes <= 0 {
return
}
page_size := usize(page_bytes)
lo := (usize(start) + page_size - 1) / page_size * page_size
hi := (usize(start) + size) / page_size * page_size
page_size := uint(page_bytes)
lo := (uint(start) + page_size - 1) / page_size * page_size
hi := (uint(start) + size) / page_size * page_size
if hi <= lo {
return
}
@@ -82,8 +82,8 @@ __global g_prealloc_allocated_bytes i64
// prealloc_recyclable_block_size reports whether a block belongs to one of
// the scope size classes (256K..1M, the geometric scope growth ladder) that
// the per-thread recycle cache retains.
fn prealloc_recyclable_block_size(size isize) bool {
base := isize(prealloc_scope_block_size)
fn prealloc_recyclable_block_size(size int) bool {
base := int(prealloc_scope_block_size)
return size == base || size == base * 2 || size == base * 4
}
@@ -96,9 +96,9 @@ fn prealloc_recyclable_block_size(size isize) bool {
struct VPreallocBlockCache {
mut:
count int
bytes isize
bytes int
starts [prealloc_recycle_cache_slots]voidptr
sizes [prealloc_recycle_cache_slots]isize
sizes [prealloc_recycle_cache_slots]int
}
@[inline]
@@ -139,7 +139,7 @@ mut:
next &VMemoryBlock = 0 // 8
scope &VPreallocScope = 0
recycle_cache &VPreallocBlockCache = 0
min_block_size isize
min_block_size int
is_scope bool
mmap_allocated bool
id int // 4
@@ -149,8 +149,8 @@ mut:
@[heap]
struct VPreallocRange {
mut:
start usize
stop usize
start uint
stop uint
}
@[heap]
@@ -162,8 +162,8 @@ mut:
// linked after it: a reentered parent scope keeps rewound blocks there.
// Unlinking the scope restores them instead of dropping them from the chain.
saved_next &VMemoryBlock = 0
min_address usize
max_address usize
min_address uint
max_address uint
ranges &VPreallocRange = 0
ranges_len int
ranges_cap int
@@ -184,13 +184,13 @@ fn prealloc_scope_add_block(scope &VPreallocScope, block &VMemoryBlock) {
unsafe {
if scope.ranges_len == scope.ranges_cap {
new_cap := if scope.ranges_cap == 0 { 8 } else { scope.ranges_cap * 2 }
ranges := &VPreallocRange(C.realloc(scope.ranges, usize(new_cap) * sizeof(VPreallocRange)))
vmemory_abort_on_nil(ranges, isize(new_cap) * isize(sizeof(VPreallocRange)))
ranges := &VPreallocRange(C.realloc(scope.ranges, uint(new_cap) * sizeof(VPreallocRange)))
vmemory_abort_on_nil(ranges, int(new_cap) * int(sizeof(VPreallocRange)))
scope.ranges = ranges
scope.ranges_cap = new_cap
}
start := usize(block.start)
stop := usize(block.stop)
start := uint(block.start)
stop := uint(block.stop)
mut insert := scope.ranges_len
for insert > 0 && scope.ranges[insert - 1].start > start {
scope.ranges[insert] = scope.ranges[insert - 1]
@@ -218,7 +218,7 @@ fn prealloc_scope_remove_block(scope &VPreallocScope, block &VMemoryBlock) {
return
}
unsafe {
start := usize(block.start)
start := uint(block.start)
for i in 0 .. scope.ranges_len {
if scope.ranges[i].start == start {
for j := i; j + 1 < scope.ranges_len; j++ {
@@ -236,7 +236,7 @@ fn prealloc_scope_remove_block(scope &VPreallocScope, block &VMemoryBlock) {
}
}
fn vmemory_abort_on_nil(p voidptr, bytes isize) {
fn vmemory_abort_on_nil(p voidptr, bytes int) {
if unsafe { p == 0 } {
C.fprintf(C.stderr, c'could not allocate %td bytes\n', bytes)
exit(1)
@@ -244,8 +244,8 @@ fn vmemory_abort_on_nil(p voidptr, bytes isize) {
}
@[inline]
fn vmemory_effective_align(align isize) isize {
default_align := isize(prealloc_default_align)
fn vmemory_effective_align(align int) int {
default_align := int(prealloc_default_align)
if align > default_align {
return align
}
@@ -253,7 +253,7 @@ fn vmemory_effective_align(align isize) isize {
}
@[inline; unsafe]
fn vmemory_align_up(ptr &u8, align isize) &u8 {
fn vmemory_align_up(ptr &u8, align int) &u8 {
if align <= 1 {
return ptr
}
@@ -303,12 +303,12 @@ fn prealloc_trace_scope(action &char, scope &VPreallocScope) {
}
@[unsafe]
fn vmemory_block_new(prev &VMemoryBlock, at_least isize, align isize) &VMemoryBlock {
return unsafe { vmemory_block_new_sized(prev, at_least, align, isize(prealloc_block_size)) }
fn vmemory_block_new(prev &VMemoryBlock, at_least int, align int) &VMemoryBlock {
return unsafe { vmemory_block_new_sized(prev, at_least, align, int(prealloc_block_size)) }
}
@[unsafe]
fn vmemory_block_new_sized(prev &VMemoryBlock, at_least isize, align isize, min_block_size isize) &VMemoryBlock {
fn vmemory_block_new_sized(prev &VMemoryBlock, at_least int, align int, min_block_size int) &VMemoryBlock {
vmem_block_size := sizeof(VMemoryBlock)
mut v := unsafe { &VMemoryBlock(C.calloc(1, vmem_block_size)) }
vmemory_abort_on_nil(v, vmem_block_size)
@@ -325,7 +325,7 @@ fn vmemory_block_new_sized(prev &VMemoryBlock, at_least isize, align isize, min_
effective_min_block_size := if min_block_size > 0 {
min_block_size
} else {
isize(prealloc_block_size)
int(prealloc_block_size)
}
v.min_block_size = effective_min_block_size
base_block_size := if at_least < effective_min_block_size {
@@ -351,7 +351,7 @@ fn vmemory_block_new_sized(prev &VMemoryBlock, at_least isize, align isize, min_
v.start = unsafe { C._aligned_malloc(block_size, fixed_align) }
} $else {
$if !freestanding && !vinix {
if fixed_align <= isize(prealloc_default_align) {
if fixed_align <= int(prealloc_default_align) {
$if !prealloc_no_recycle ? {
if prealloc_recyclable_block_size(block_size) {
unsafe {
@@ -377,7 +377,7 @@ fn vmemory_block_new_sized(prev &VMemoryBlock, at_least isize, align isize, min_
}
if unsafe { v.start == 0 } {
mmap_ptr := unsafe {
C.mmap(0, usize(block_size), C.PROT_READ | C.PROT_WRITE, C.MAP_ANONYMOUS | C.MAP_PRIVATE, -1, 0)
C.mmap(0, uint(block_size), C.PROT_READ | C.PROT_WRITE, C.MAP_ANONYMOUS | C.MAP_PRIVATE, -1, 0)
}
if mmap_ptr != C.MAP_FAILED {
v.start = &u8(mmap_ptr)
@@ -426,7 +426,7 @@ fn vmemory_block_current_or_new() &VMemoryBlock {
@[noinline; unsafe]
fn vmemory_block_init_thread() &VMemoryBlock {
unsafe {
mut mb := vmemory_block_new(nil, isize(prealloc_block_size), 0)
mut mb := vmemory_block_new(nil, int(prealloc_block_size), 0)
mb.recycle_cache = &VPreallocBlockCache(C.calloc(1, sizeof(VPreallocBlockCache)))
vmemory_abort_on_nil(mb.recycle_cache, sizeof(VPreallocBlockCache))
g_memory_block = mb
@@ -435,7 +435,7 @@ fn vmemory_block_init_thread() &VMemoryBlock {
}
@[noinline; unsafe]
fn vmemory_block_grow(previous &VMemoryBlock, n isize, align isize) &VMemoryBlock {
fn vmemory_block_grow(previous &VMemoryBlock, n int, align int) &VMemoryBlock {
unsafe {
was_scope := previous.is_scope
scope := previous.scope
@@ -457,9 +457,9 @@ fn vmemory_block_grow(previous &VMemoryBlock, n isize, align isize) &VMemoryBloc
mut min_block_size := if previous.min_block_size > 0 {
previous.min_block_size
} else {
isize(prealloc_block_size)
int(prealloc_block_size)
}
if was_scope && min_block_size < isize(prealloc_scope_block_size) * 4 {
if was_scope && min_block_size < int(prealloc_scope_block_size) * 4 {
// Scopes that outgrow one block tend to keep growing: doubling
// the block size (256K..4M) turns a 100-block scope into ~10
// blocks, cutting refill and map/unmap churn per batch.
@@ -482,13 +482,13 @@ fn vmemory_block_grow(previous &VMemoryBlock, n isize, align isize) &VMemoryBloc
}
@[inline; unsafe]
fn vmemory_block_malloc(n isize, align isize) &u8 {
fn vmemory_block_malloc(n int, align int) &u8 {
return unsafe { vmemory_block_malloc_aligned(n, vmemory_effective_align(align)) }
}
// Byte buffers can use alignment 1; general allocations retain the default alignment.
@[inline; unsafe]
fn vmemory_block_malloc_aligned(n isize, align isize) &u8 {
fn vmemory_block_malloc_aligned(n int, align int) &u8 {
unsafe {
// Read the thread-local block pointer ONCE per call: it only stores
// which block is current, and the bump updates go through the block
@@ -543,7 +543,7 @@ fn vmemory_block_free(mb &VMemoryBlock) {
size := vmemory_block_size(mb)
mut recycled := false
$if !prealloc_no_recycle ? {
if prealloc_recyclable_block_size(isize(size)) {
if prealloc_recyclable_block_size(int(size)) {
unsafe {
mut cache := &VPreallocBlockCache(nil)
if g_memory_block != 0 {
@@ -551,10 +551,10 @@ fn vmemory_block_free(mb &VMemoryBlock) {
}
cache_limit := prealloc_recycle_cache_limit()
if cache != 0 && cache.count < cache_limit
&& cache.bytes + isize(size) <= isize(prealloc_scope_block_size) * cache_limit {
&& cache.bytes + int(size) <= int(prealloc_scope_block_size) * cache_limit {
cache.starts[cache.count] = voidptr(mb.start)
cache.sizes[cache.count] = isize(size)
cache.bytes += isize(size)
cache.sizes[cache.count] = int(size)
cache.bytes += int(size)
cache.count++
recycled = true
}
@@ -565,7 +565,7 @@ fn vmemory_block_free(mb &VMemoryBlock) {
$if prealloc_trace_recycle ? {
C.fprintf(C.stderr, c'[recycle-miss] size=%lld\n', size)
}
C.munmap(mb.start, usize(size))
C.munmap(mb.start, uint(size))
}
} else {
C.free(mb.start)
@@ -609,7 +609,7 @@ fn prealloc_recycle_cache_free(cache &VPreallocBlockCache) {
$if !windows && !freestanding && !vinix {
unsafe {
for i in 0 .. cache.count {
C.munmap(cache.starts[i], usize(cache.sizes[i]))
C.munmap(cache.starts[i], uint(cache.sizes[i]))
}
}
}
@@ -644,7 +644,7 @@ fn prealloc_vinit() {
C.fprintf(C.stderr, c'prealloc_vinit started\n')
}
unsafe {
mut root := vmemory_block_new(nil, isize(prealloc_block_size), 0)
mut root := vmemory_block_new(nil, int(prealloc_block_size), 0)
root.recycle_cache = &VPreallocBlockCache(C.calloc(1, sizeof(VPreallocBlockCache)))
vmemory_abort_on_nil(root.recycle_cache, sizeof(VPreallocBlockCache))
g_memory_block = root
@@ -697,10 +697,10 @@ fn prealloc_vcleanup() {
C.fprintf(C.stderr, c'prealloc_vcleanup dumping mb: %p, mb.id: %d, used: %10lld bytes\n', mb, mb.id, used)
mut ptr := mb.start
mut remaining_bytes := isize(used)
mut x := isize(0)
mut remaining_bytes := int(used)
mut x := int(0)
for remaining_bytes > 0 {
x = isize(C.fwrite(ptr, 1, remaining_bytes, stream))
x = int(C.fwrite(ptr, 1, remaining_bytes, stream))
ptr += x
remaining_bytes -= x
}
@@ -731,11 +731,11 @@ pub fn prealloc_scope_begin() voidptr {
vmemory_abort_on_nil(scope, sizeof(VPreallocScope))
scope.previous = vmemory_block_current_or_new()
scope.saved_next = scope.previous.next
scope.first = vmemory_block_new_sized(scope.previous, isize(prealloc_scope_block_size), 0, isize(prealloc_scope_block_size))
scope.first = vmemory_block_new_sized(scope.previous, int(prealloc_scope_block_size), 0, int(prealloc_scope_block_size))
scope.first.is_scope = true
scope.first.scope = scope
scope.min_address = usize(scope.first.start)
scope.max_address = usize(scope.first.stop)
scope.min_address = uint(scope.first.start)
scope.max_address = uint(scope.first.stop)
prealloc_scope_add_block(scope, scope.first)
g_memory_block = scope.first
prealloc_trace_scope(c'begin', scope)
@@ -933,7 +933,7 @@ pub fn prealloc_scope_leave(scope_ptr voidptr) {
// leaving the scope untouched, when the scope is still current, retained by
// another owner, or already being freed; the caller then starts a new scope.
@[unsafe]
pub fn prealloc_scope_reenter(scope_ptr voidptr, keep_bytes isize) bool {
pub fn prealloc_scope_reenter(scope_ptr voidptr, keep_bytes int) bool {
$if prealloc {
if scope_ptr == unsafe { nil } {
return false
@@ -949,11 +949,11 @@ pub fn prealloc_scope_reenter(scope_ptr voidptr, keep_bytes isize) bool {
}
parent := vmemory_block_current_or_new()
// Keep the first blocks, up to `keep_bytes`, for reuse; free the rest.
mut kept := isize(0)
mut kept := int(0)
mut last_kept := &VMemoryBlock(nil)
mut mb := scope.first
for mb != 0 && mb.is_scope && mb.scope == scope {
size := isize(vmemory_block_size(mb))
size := int(vmemory_block_size(mb))
if last_kept != 0 && kept + size > keep_bytes {
break
}
@@ -1042,7 +1042,7 @@ pub fn prealloc_scope_owns(scope_ptr voidptr, ptr voidptr) bool {
}
unsafe {
scope := &VPreallocScope(scope_ptr)
address := usize(ptr)
address := uint(ptr)
if address < scope.min_address || address >= scope.max_address {
return false
}
@@ -1069,7 +1069,7 @@ pub fn prealloc_scope_owns(scope_ptr voidptr, ptr voidptr) bool {
// addresses of the blocks owned by scope_ptr, so callers probing many pointers
// can reject most of them before the per-block search in prealloc_scope_owns.
@[inline; unsafe]
pub fn prealloc_scope_address_range(scope_ptr voidptr) (usize, usize) {
pub fn prealloc_scope_address_range(scope_ptr voidptr) (uint, uint) {
if scope_ptr == unsafe { nil } {
return 0, 0
}
@@ -1081,19 +1081,19 @@ pub fn prealloc_scope_address_range(scope_ptr voidptr) (usize, usize) {
// prealloc_scope_allocated_size returns the total bytes in the allocation blocks
// owned by scope_ptr. The scope must be settled: no thread may add or remove blocks
// during the query. A nil scope returns zero; size overflow saturates at usize's max.
// during the query. A nil scope returns zero; size overflow saturates at uint's max.
@[unsafe]
pub fn prealloc_scope_allocated_size(scope_ptr voidptr) usize {
pub fn prealloc_scope_allocated_size(scope_ptr voidptr) uint {
if scope_ptr == unsafe { nil } {
return 0
}
unsafe {
scope := &VPreallocScope(scope_ptr)
mut total := usize(0)
mut total := uint(0)
for i in 0 .. scope.ranges_len {
bytes := scope.ranges[i].stop - scope.ranges[i].start
if bytes > ~usize(0) - total {
return ~usize(0)
if bytes > ~uint(0) - total {
return ~uint(0)
}
total += bytes
}
@@ -1133,12 +1133,12 @@ pub fn prealloc_scope_free_after(scope_ptr voidptr) {
}
@[inline; unsafe]
fn prealloc_malloc(n isize) &u8 {
fn prealloc_malloc(n int) &u8 {
return unsafe { vmemory_block_malloc(n, 0) }
}
@[unsafe]
fn prealloc_realloc(old_data &u8, old_size isize, new_size isize) &u8 {
fn prealloc_realloc(old_data &u8, old_size int, new_size int) &u8 {
unsafe {
mut mb := g_memory_block
if mb != nil && old_data != nil && old_size >= 0 && new_size >= 0
@@ -1168,19 +1168,19 @@ fn prealloc_realloc(old_data &u8, old_size isize, new_size isize) &u8 {
}
// realloc invalidates the old buffer once its contents have been copied.
if old_size > 0 {
unsafe { prealloc_discard_pages(old_data, usize(old_size)) }
unsafe { prealloc_discard_pages(old_data, uint(old_size)) }
}
return new_ptr
}
@[inline; unsafe]
fn prealloc_calloc(n isize) &u8 {
fn prealloc_calloc(n int) &u8 {
new_ptr := unsafe { vmemory_block_malloc(n, 0) }
unsafe { C.memset(new_ptr, 0, n) }
return new_ptr
}
@[unsafe]
fn prealloc_malloc_align(n isize, align isize) &u8 {
fn prealloc_malloc_align(n int, align int) &u8 {
return unsafe { vmemory_block_malloc(n, align) }
}
+1 -1
View File
@@ -3,7 +3,7 @@ fn test_prealloc_discard_preserves_neighbors_and_writable_reservation() {
start := 10_003
end := 210_017
$if prealloc {
unsafe { prealloc_discard_pages(&bytes[start], usize(end - start)) }
unsafe { prealloc_discard_pages(&bytes[start], uint(end - start)) }
}
for i in 0 .. start {
assert bytes[i] == 0xa5
+3 -3
View File
@@ -76,10 +76,10 @@ fn test_prealloc_refills_preserve_aligned_allocations() {
mut sizes := []int{cap: 64}
for i in 0 .. 64 {
size := 16_385 + i * 19
alignment := isize(16 << (i % 5))
alignment := int(16 << (i % 5))
source := []u8{len: size, init: u8(i)}
ptr := unsafe { &u8(memdup_align(source.data, isize(size), alignment)) }
assert usize(ptr) % usize(alignment) == 0
ptr := unsafe { &u8(memdup_align(source.data, int(size), alignment)) }
assert uint(ptr) % uint(alignment) == 0
assert unsafe { prealloc_scope_owns(scope, ptr) }
allocations << ptr
sizes << size
+1 -1
View File
@@ -3,7 +3,7 @@
// Scope blocks are 256 KB, so every 200 KB allocation below starts a new block.
const reenter_alloc_size = 200 * 1024
const reenter_keep_all = isize(64 * 1024 * 1024)
const reenter_keep_all = int(64 * 1024 * 1024)
fn test_prealloc_scope_reenter_reuses_rewound_blocks() {
$if prealloc {
+4 -4
View File
@@ -9,7 +9,7 @@ fn test_prealloc_scope_allocated_size_tracks_multiple_blocks() {
first_size := unsafe { prealloc_scope_allocated_size(scope) }
second := []u8{len: 512 * 1024}
second_size := unsafe { prealloc_scope_allocated_size(scope) }
assert initial >= usize(prealloc_scope_block_size)
assert initial >= uint(prealloc_scope_block_size)
assert first_size > initial
assert second_size > first_size
assert unsafe { prealloc_scope_owns(scope, first.data) }
@@ -21,12 +21,12 @@ fn test_prealloc_scope_allocated_size_tracks_multiple_blocks() {
}
fn test_prealloc_scope_allocated_size_saturates_overflow() {
mut ranges := [VPreallocRange{ start: 1, stop: ~usize(0) }, VPreallocRange{ start: 5, stop: 6 }]
mut ranges := [VPreallocRange{ start: 1, stop: ~uint(0) }, VPreallocRange{ start: 5, stop: 6 }]
scope := VPreallocScope{
ranges: unsafe { &ranges[0] }
ranges_len: ranges.len
}
assert unsafe { prealloc_scope_allocated_size(&scope) } == ~usize(0)
assert unsafe { prealloc_scope_allocated_size(&scope) } == ~uint(0)
ranges[1].stop = 7
assert unsafe { prealloc_scope_allocated_size(&scope) } == ~usize(0)
assert unsafe { prealloc_scope_allocated_size(&scope) } == ~uint(0)
}
+4 -4
View File
@@ -6,13 +6,13 @@ fn test_prealloc_string_buffers_pack_bytes_and_preserve_general_alignment() {
first := 'ab'.clone()
second := 'cdef'.clone()
third := 'gh'.clone()
assert usize(second.str) == usize(first.str) + usize(first.len) + 1
assert usize(third.str) == usize(second.str) + usize(second.len) + 1
assert uint(second.str) == uint(first.str) + uint(first.len) + 1
assert uint(third.str) == uint(second.str) + uint(second.len) + 1
assert first == 'ab' && second == 'cdef' && third == 'gh'
assert unsafe { first.str[first.len] } == 0
assert unsafe { second.str[second.len] } == 0
general := unsafe { malloc(17) }
assert usize(general) % usize(prealloc_default_align) == 0
assert uint(general) % uint(prealloc_default_align) == 0
assert unsafe { prealloc_scope_owns(scope, first.str) }
assert unsafe { prealloc_scope_owns(scope, general) }
unsafe {
@@ -38,7 +38,7 @@ fn test_prealloc_string_buffers_grow_and_reenter_a_scope() {
assert unsafe { joined.str[joined.len] } == 0
assert unsafe { prealloc_scope_owns(scope, joined.str) }
general := unsafe { malloc(33) }
assert usize(general) % usize(prealloc_default_align) == 0
assert uint(general) % uint(prealloc_default_align) == 0
unsafe { prealloc_scope_leave(scope) }
}
unsafe { prealloc_scope_free_after(scope) }
+5 -5
View File
@@ -1,12 +1,12 @@
module builtin
fn C.setvbuf(fstream &C.FILE, buffer &char, mode i32, size usize) i32
fn C.setvbuf(fstream &C.FILE, buffer &char, mode i32, size uint) i32
// set_stream_unbuffered switches a stdio stream to unbuffered mode without using the
// deprecated `setbuf` API on Windows toolchains.
@[unsafe]
fn set_stream_unbuffered(stream &C.FILE) {
C.setvbuf(stream, &char(nil), C._IONBF, usize(0))
C.setvbuf(stream, &char(nil), C._IONBF, uint(0))
}
// race_stdio_write marks a write to stdout or stderr in a race build (`v -race`), like
@@ -219,8 +219,8 @@ fn _write_buf_to_fd(fd int, buf &u8, buf_len int) {
}
} $else {
mut ptr := unsafe { buf }
mut remaining_bytes := isize(buf_len)
mut x := isize(0)
mut remaining_bytes := int(buf_len)
mut x := int(0)
$if freestanding || vinix || builtin_write_buf_to_fd_should_use_c_write ? {
// Flush any pending libc stdio output (from C.puts, C.putchar, etc.)
// before writing directly via write() syscall to prevent output reordering.
@@ -243,7 +243,7 @@ fn _write_buf_to_fd(fd int, buf &u8, buf_len int) {
}
unsafe {
for remaining_bytes > 0 {
x = isize(C.fwrite(ptr, 1, remaining_bytes, stream))
x = int(C.fwrite(ptr, 1, remaining_bytes, stream))
if x <= 0 {
// GUI programs on Windows may not have a writable stdout/stderr stream.
break
+4 -4
View File
@@ -9,8 +9,8 @@ fn C.__tsan_acquire(addr voidptr)
fn C.__tsan_release(addr voidptr)
fn C.__tsan_read1(addr voidptr)
fn C.__tsan_write1(addr voidptr)
fn C.__tsan_read_range(addr voidptr, size usize)
fn C.__tsan_write_range(addr voidptr, size usize)
fn C.__tsan_read_range(addr voidptr, size uint)
fn C.__tsan_write_range(addr voidptr, size uint)
fn C.AnnotateIgnoreReadsBegin(file &char, line int)
fn C.AnnotateIgnoreReadsEnd(file &char, line int)
fn C.AnnotateIgnoreWritesBegin(file &char, line int)
@@ -50,13 +50,13 @@ pub fn racewrite(addr voidptr) {
// racereadrange tells the race detector that the calling thread reads `len` bytes at `addr`.
pub fn racereadrange(addr voidptr, len int) {
C.__tsan_read_range(addr, usize(len))
C.__tsan_read_range(addr, uint(len))
}
// racewriterange tells the race detector that the calling thread writes `len` bytes at
// `addr`.
pub fn racewriterange(addr voidptr, len int) {
C.__tsan_write_range(addr, usize(len))
C.__tsan_write_range(addr, uint(len))
}
// race_io_sync stands for all file I/O, like `ioSync` in Go's syscall package.
+3 -3
View File
@@ -200,7 +200,7 @@ fn panic_unwind(msg string, debug PanicDebugInfo) {
if g_panic_state.len == g_panic_state.cap {
new_cap := if g_panic_state.cap == 0 { 4 } else { g_panic_state.cap * 2 }
records := unsafe {
&PanicRecord(C.realloc(g_panic_state.records, usize(new_cap) * usize(sizeof(PanicRecord))))
&PanicRecord(C.realloc(g_panic_state.records, uint(new_cap) * uint(sizeof(PanicRecord))))
}
if records == unsafe { nil } {
panic_frames_reset()
@@ -209,13 +209,13 @@ fn panic_unwind(msg string, debug PanicDebugInfo) {
g_panic_state.records = records
g_panic_state.cap = new_cap
}
msg_copy := unsafe { &u8(C.malloc(usize(msg.len + 1))) }
msg_copy := unsafe { &u8(C.malloc(uint(msg.len + 1))) }
if msg_copy == unsafe { nil } {
panic_frames_reset()
panic(msg)
}
unsafe {
C.memcpy(msg_copy, msg.str, usize(msg.len))
C.memcpy(msg_copy, msg.str, uint(msg.len))
msg_copy[msg.len] = 0
}
mut rec := panic_record(g_panic_state.len)
+1 -1
View File
@@ -13,7 +13,7 @@ $if !native && !no_segfault_handler ?&& !freestanding && !vinix {
fn C.v_install_segfault_handler(fallback voidptr, main_argv voidptr)
@[markused]
fn C.v_thread_signal_stack_enter(stack_top voidptr, stack_size usize) voidptr
fn C.v_thread_signal_stack_enter(stack_top voidptr, stack_size uint) voidptr
@[markused]
fn C.v_thread_signal_stack_leave(alt_stack voidptr)
+3 -3
View File
@@ -1512,7 +1512,7 @@ pub fn (s string) index_(p string) int {
if p.len == 0 {
return 0
}
if p.len > s.len || usize(s.str) <= 0xFFFF || usize(p.str) <= 0xFFFF {
if p.len > s.len || uint(s.str) <= 0xFFFF || uint(p.str) <= 0xFFFF {
return -1
}
if p.len == 1 {
@@ -1818,7 +1818,7 @@ pub fn (s string) contains_any_substr(substrs []string) bool {
// starts_with returns `true` if the string starts with `p`.
@[direct_array_access; inline]
pub fn (s string) starts_with(p string) bool {
if p.len > s.len || usize(s.str) <= 0xFFFF || usize(p.str) <= 0xFFFF {
if p.len > s.len || uint(s.str) <= 0xFFFF || uint(p.str) <= 0xFFFF {
return false
}
return string_content_equal(s.str, p.str, p.len)
@@ -1827,7 +1827,7 @@ pub fn (s string) starts_with(p string) bool {
// ends_with returns `true` if the string ends with `p`.
@[direct_array_access; inline]
pub fn (s string) ends_with(p string) bool {
if p.len > s.len || usize(s.str) <= 0xFFFF || usize(p.str) <= 0xFFFF {
if p.len > s.len || uint(s.str) <= 0xFFFF || uint(p.str) <= 0xFFFF {
return false
}
return string_content_equal(unsafe { s.str + s.len - p.len }, p.str, p.len)
+3 -3
View File
@@ -22,7 +22,7 @@ mut:
const words = ['alpha'.repeat(3), 'beta'.repeat(3), 'gamma'.repeat(3), 'delta'.repeat(3)]
// GC_noop1 receives stack addresses, so the buffers behind them stay in memory.
fn C.GC_noop1(usize)
fn C.GC_noop1(uint)
@[noinline]
fn flags(a bool, b bool) int {
@@ -73,7 +73,7 @@ fn churn() {
fn scrub() {
mut buf := [4096]u8{}
unsafe { C.memset(&buf[0], 0, 4096) }
C.GC_noop1(usize(&buf[0]))
C.GC_noop1(uint(&buf[0]))
}
// copy_through_padding moves `h.f` into a local, clears the source and collects while
@@ -106,7 +106,7 @@ fn misaligned_slot() bool {
mut slot := [24]u8{}
mut p := new_block()
unsafe { C.memcpy(&slot[3], &p, sizeof(voidptr)) }
C.GC_noop1(usize(&slot[0]))
C.GC_noop1(uint(&slot[0]))
p = unsafe { nil }
gc_collect()
churn()
+1 -1
View File
@@ -1,6 +1,6 @@
module main
fn C.GC_expand_hp(usize) int
fn C.GC_expand_hp(uint) int
fn C.GC_set_force_unmap_on_gcollect(int)
fn main() {
+88 -88
View File
@@ -24,13 +24,13 @@ fn C.vgc_atomic_fence()
fn C.vgc_counter_load(ptr &u64) u64
fn C.vgc_counter_add(ptr &u64, val u64)
fn C.vgc_count_alloc(live &u64, allocated &u64, size u64, n u64)
fn C.vgc_os_alloc(size usize) voidptr
fn C.vgc_os_alloc_heap(size usize) voidptr
fn C.vgc_os_free(ptr voidptr, size usize)
fn C.vgc_os_decommit(ptr voidptr, size usize)
fn C.vgc_os_recommit(ptr voidptr, size usize) int
fn C.vgc_os_alloc(size uint) voidptr
fn C.vgc_os_alloc_heap(size uint) voidptr
fn C.vgc_os_free(ptr voidptr, size uint)
fn C.vgc_os_decommit(ptr voidptr, size uint)
fn C.vgc_os_recommit(ptr voidptr, size uint) int
fn C.vgc_get_sp() voidptr
fn C.vgc_get_stack_bounds(lo &usize, hi &usize) int
fn C.vgc_get_stack_bounds(lo &uint, hi &uint) int
fn C.vgc_bitmap_get(bits &u8, idx u32) int
fn C.vgc_bitmap_set(bits &u8, idx u32)
fn C.vgc_bitmap_clear(bits &u8, idx u32)
@@ -60,7 +60,7 @@ const vgc_page_size = 8192
const vgc_max_small_size = u32(32768) // objects > this are "large"
const vgc_num_classes = 68
const vgc_num_span_classes = 136 // 68 * 2 (scan + noscan variants)
// These MUST stay compile-time integer constants (no `usize()` cast, no division by
// These MUST stay compile-time integer constants (no `uint()` cast, no division by
// another const). Otherwise V emits them as runtime globals initialized inside
// `_vinit()`, and the allocations that run earlier in `_vinit()` (const strings, etc.)
// see them as 0: arenas get sized to a single page instead of 64MB.
@@ -97,14 +97,14 @@ const vgc_phase_sweep = u32(3)
// Translated from Go's runtime.mspan.
struct VGC_Span {
mut:
base usize // start address of the span
npages u32 // number of pages in this span
elem_size u32 // size of each object in bytes
nelems u32 // number of elements (objects) in the span
class_idx u8 // size class index (0 for large objects)
noscan bool // true if objects contain no pointers (noscan variant)
in_use bool // true if span is allocated to a size class
has_ptrmap bool // true if ptrmap is valid (precise scanning available)
base uint // start address of the span
npages u32 // number of pages in this span
elem_size u32 // size of each object in bytes
nelems u32 // number of elements (objects) in the span
class_idx u8 // size class index (0 for large objects)
noscan bool // true if objects contain no pointers (noscan variant)
in_use bool // true if span is allocated to a size class
has_ptrmap bool // true if ptrmap is valid (precise scanning available)
// Pointer bitmap: bit N = word offset N contains a pointer.
// Covers objects up to 512 bytes (64 words on 64-bit).
// For larger objects, falls back to conservative scanning.
@@ -141,9 +141,9 @@ mut:
alloc [136]&VGC_Span // one span per span class (68 scan + 68 noscan)
// Tiny allocator for objects < 16 bytes without pointers
// Translated from Go's mcache.tiny
tiny usize
tiny_offset usize
tiny_allocs usize
tiny uint
tiny_offset uint
tiny_allocs uint
// What the threads that had this slot allocated: the bytes of the objects that they allocated
// minus the ones that they freed, and the bytes that they asked for. The slot's thread adds to
// them with C.vgc_count_alloc and C.vgc_counter_add, macros without a lock, an atomic
@@ -153,9 +153,9 @@ mut:
alloc_bytes u64
// Thread info
registered bool
stack_base usize // fixed stack boundary for this thread
stack_lo usize // lowest stack address (for root scanning)
stack_hi usize // highest stack address
stack_base uint // fixed stack boundary for this thread
stack_lo uint // lowest stack address (for root scanning)
stack_hi uint // highest stack address
thread_id u64
stopped u32 // 1 if stopped for GC
}
@@ -173,9 +173,9 @@ mut:
// Translated from Go's heapArena concept.
struct VGC_Arena {
mut:
base usize
size usize
used usize
base uint
size uint
used uint
// Map from page index to span (for finding which span owns an address): one entry for each
// of the size / vgc_page_size pages, stored right after the arena.
page_span &&VGC_Span = unsafe { nil }
@@ -192,7 +192,7 @@ mut:
struct VGC_WorkBuf {
mut:
nobj int
obj [256]usize // pointers to mark
obj [256]uint // pointers to mark
next &VGC_WorkBuf = unsafe { nil }
}
@@ -216,8 +216,8 @@ mut:
// Large object spans
large_alloc &VGC_Span = unsafe { nil }
// The rest of the current chunk for span metadata, and the bytes of all chunks
meta_next usize
meta_left usize
meta_next uint
meta_left uint
meta_bytes u64
// Free spans (completely empty, reusable by page count)
free_spans_lock u32
@@ -278,10 +278,10 @@ __global vgc_heap = VGC_Heap{}
// these to 0 after the first arena has already been mapped during const init.
@[cinit]
__global vgc_arena_lo = usize(0)
__global vgc_arena_lo = uint(0)
@[cinit]
__global vgc_arena_hi = usize(0)
__global vgc_arena_hi = uint(0)
// ============================================================
// Initialization
@@ -327,13 +327,13 @@ fn vgc_register_thread() {
C.vgc_set_cache_idx(idx)
C.vgc_watch_thread_exit(idx)
sp := usize(C.vgc_get_sp())
mut stack_lo := usize(0)
mut stack_hi := usize(0)
mut stack_base := if sp > usize(8) * 1024 * 1024 {
sp - usize(8) * 1024 * 1024
sp := uint(C.vgc_get_sp())
mut stack_lo := uint(0)
mut stack_hi := uint(0)
mut stack_base := if sp > uint(8) * 1024 * 1024 {
sp - uint(8) * 1024 * 1024
} else {
usize(0)
uint(0)
}
if C.vgc_get_stack_bounds(&stack_lo, &stack_hi) != 0 && stack_lo < stack_hi {
dist_lo := if sp >= stack_lo { sp - stack_lo } else { stack_lo - sp }
@@ -348,7 +348,7 @@ fn vgc_register_thread() {
// vgc_on_thread_exit runs when a registered thread exits, with its cache index + 1.
fn vgc_on_thread_exit(value voidptr) {
vgc_unregister_thread(int(isize(value)) - 1)
vgc_unregister_thread(int(int(value)) - 1)
}
// vgc_unregister_thread frees the slot of an exiting thread, so that the collector no longer
@@ -442,7 +442,7 @@ fn vgc_enter() int {
return C.vgc_get_cache_idx()
}
fn vgc_refresh_stack_range_for_sp(cache_idx int, sp usize) {
fn vgc_refresh_stack_range_for_sp(cache_idx int, sp uint) {
if cache_idx < 0 || cache_idx >= vgc_max_threads {
return
}
@@ -472,7 +472,7 @@ fn vgc_get_free_span(npages u32, owner int) &VGC_Span {
}
// The pages of a free span were given back to the OS; Windows faults on them until they
// are committed again.
if C.vgc_os_recommit(voidptr(span.base), usize(npages) * vgc_page_size) == 0 {
if C.vgc_os_recommit(voidptr(span.base), uint(npages) * vgc_page_size) == 0 {
vgc_push_free_span(mut span)
return unsafe { nil }
}
@@ -547,7 +547,7 @@ fn vgc_put_free_span(mut span VGC_Span) {
span.ptrmap = 0
span.ptr_words = 0
// Decommit pages to return physical memory to OS
page_bytes := usize(npages) * vgc_page_size
page_bytes := uint(npages) * vgc_page_size
C.vgc_os_decommit(voidptr(span.base), page_bytes)
C.vgc_atomic_add_u64(&vgc_heap.unmapped_bytes, u64(page_bytes))
vgc_push_free_span(mut span)
@@ -583,11 +583,11 @@ fn vgc_span_alloc(npages u32, owner int) &VGC_Span {
return recycled
}
nbytes := usize(npages) * vgc_page_size
nbytes := uint(npages) * vgc_page_size
C.vgc_mutex_lock(&vgc_heap.lock)
// Try to find space in existing arenas
mut base := usize(0)
mut base := uint(0)
mut arena := unsafe { &VGC_Arena(nil) }
for i in vgc_heap.arena_open .. vgc_heap.narenas {
mut a := unsafe { vgc_heap.arenas[i] }
@@ -633,7 +633,7 @@ fn vgc_span_alloc(npages u32, owner int) &VGC_Span {
}
// Register span in arena's page map
page_start := (base - arena.base) / vgc_page_size
for p in 0 .. usize(npages) {
for p in 0 .. uint(npages) {
unsafe {
arena.page_span[page_start + p] = span
}
@@ -645,23 +645,23 @@ fn vgc_span_alloc(npages u32, owner int) &VGC_Span {
// vgc_new_arena gets an arena for a span of nbytes from the OS: vgc_arena_size bytes, or
// nbytes for a larger object. The caller holds vgc_heap.lock.
fn vgc_new_arena(nbytes usize) &VGC_Arena {
fn vgc_new_arena(nbytes uint) &VGC_Arena {
if vgc_heap.narenas == vgc_heap.arenas_cap {
new_cap := if vgc_heap.arenas_cap == 0 { 8 } else { vgc_heap.arenas_cap * 2 }
table := unsafe { &&VGC_Arena(C.vgc_os_alloc(usize(new_cap) * sizeof(voidptr))) }
table := unsafe { &&VGC_Arena(C.vgc_os_alloc(uint(new_cap) * sizeof(voidptr))) }
if table == unsafe { nil } {
return unsafe { nil }
}
if vgc_heap.arenas != unsafe { nil } {
unsafe {
C.memcpy(table, vgc_heap.arenas, usize(vgc_heap.narenas) * sizeof(voidptr))
C.memcpy(table, vgc_heap.arenas, uint(vgc_heap.narenas) * sizeof(voidptr))
}
C.vgc_os_free(vgc_heap.arenas, usize(vgc_heap.arenas_cap) * sizeof(voidptr))
C.vgc_os_free(vgc_heap.arenas, uint(vgc_heap.arenas_cap) * sizeof(voidptr))
}
vgc_heap.arenas = table
vgc_heap.arenas_cap = new_cap
}
asize := if nbytes > vgc_arena_size { nbytes } else { usize(vgc_arena_size) }
asize := if nbytes > vgc_arena_size { nbytes } else { uint(vgc_arena_size) }
mem := C.vgc_os_alloc_heap(asize)
if mem == unsafe { nil } {
return unsafe { nil }
@@ -674,9 +674,9 @@ fn vgc_new_arena(nbytes usize) &VGC_Arena {
return unsafe { nil }
}
mut arena := unsafe { &VGC_Arena(desc) }
arena.base = usize(mem)
arena.base = uint(mem)
arena.size = asize
arena.page_span = unsafe { &&VGC_Span(usize(desc) + sizeof(VGC_Arena)) }
arena.page_span = unsafe { &&VGC_Span(uint(desc) + sizeof(VGC_Arena)) }
unsafe {
vgc_heap.arenas[vgc_heap.narenas] = arena
}
@@ -730,15 +730,15 @@ fn vgc_arena_map_add(arena &VGC_Arena) bool {
// freed, so the metadata comes from large chunks; a page of its own for each span (and one for
// each of its two bitmaps) used more memory than the span's objects. The caller holds
// vgc_heap.lock.
fn vgc_meta_alloc(size usize) voidptr {
n := (size + 15) & ~usize(15)
fn vgc_meta_alloc(size uint) voidptr {
n := (size + 15) & ~uint(15)
if vgc_heap.meta_left < n {
chunk := C.vgc_os_alloc(usize(vgc_meta_chunk_size))
chunk := C.vgc_os_alloc(uint(vgc_meta_chunk_size))
if chunk == unsafe { nil } {
return unsafe { nil }
}
vgc_heap.meta_next = usize(chunk)
vgc_heap.meta_left = usize(vgc_meta_chunk_size)
vgc_heap.meta_next = uint(chunk)
vgc_heap.meta_left = uint(vgc_meta_chunk_size)
vgc_heap.meta_bytes += u64(vgc_meta_chunk_size)
}
p := vgc_heap.meta_next
@@ -808,7 +808,7 @@ fn vgc_span_alloc_obj(mut span VGC_Span) voidptr {
}
span.alloc_count++
span.free_index = i + 1
addr := span.base + usize(i) * usize(span.elem_size)
addr := span.base + uint(i) * uint(span.elem_size)
return unsafe { voidptr(addr) }
}
}
@@ -939,7 +939,7 @@ fn vgc_cache_get_span(cache_idx int, span_class int) &VGC_Span {
// (translated from Go's runtime.mallocgc)
// ============================================================
fn vgc_malloc(n usize) voidptr {
fn vgc_malloc(n uint) voidptr {
return vgc_malloc_typed_opts(n, 0, 0, true)
}
@@ -947,11 +947,11 @@ fn vgc_malloc(n usize) voidptr {
// ptrmap: bitmap where bit N means word offset N is a pointer.
// ptr_words: number of pointer words in the object.
// If ptrmap==0 && ptr_words==0, falls back to conservative scanning.
fn vgc_malloc_typed(n usize, ptrmap u64, ptr_words u8) voidptr {
fn vgc_malloc_typed(n uint, ptrmap u64, ptr_words u8) voidptr {
return vgc_malloc_typed_opts(n, ptrmap, ptr_words, true)
}
fn vgc_malloc_typed_opts(n usize, ptrmap u64, ptr_words u8, zero_fill bool) voidptr {
fn vgc_malloc_typed_opts(n uint, ptrmap u64, ptr_words u8, zero_fill bool) voidptr {
if n == 0 {
return unsafe { nil }
}
@@ -959,7 +959,7 @@ fn vgc_malloc_typed_opts(n usize, ptrmap u64, ptr_words u8, zero_fill bool) void
cache_idx := vgc_enter()
// Large allocation (> 32KB) - get dedicated span
if n > usize(vgc_max_small_size) {
if n > uint(vgc_max_small_size) {
vgc_maybe_gc()
return vgc_alloc_large(n, false, zero_fill, cache_idx)
}
@@ -1016,18 +1016,18 @@ fn vgc_maybe_gc() {
}
}
fn vgc_malloc_noscan(n usize) voidptr {
fn vgc_malloc_noscan(n uint) voidptr {
return vgc_malloc_noscan_opts(n, true)
}
fn vgc_malloc_noscan_opts(n usize, zero_fill bool) voidptr {
fn vgc_malloc_noscan_opts(n uint, zero_fill bool) voidptr {
if n == 0 {
return unsafe { nil }
}
cache_idx := vgc_enter()
if n > usize(vgc_max_small_size) {
if n > uint(vgc_max_small_size) {
vgc_maybe_gc()
return vgc_alloc_large(n, true, zero_fill, cache_idx)
}
@@ -1045,11 +1045,11 @@ fn vgc_malloc_noscan_opts(n usize, zero_fill bool) voidptr {
// Align up for the allocation
mut off := cache.tiny_offset
if n >= 8 {
off = (off + 7) & ~usize(7)
off = (off + 7) & ~uint(7)
} else if n >= 4 {
off = (off + 3) & ~usize(3)
off = (off + 3) & ~uint(3)
} else if n >= 2 {
off = (off + 1) & ~usize(1)
off = (off + 1) & ~uint(1)
}
if off + n <= vgc_tiny_size {
ptr := unsafe { voidptr(cache.tiny + off) }
@@ -1073,10 +1073,10 @@ fn vgc_malloc_noscan_opts(n usize, zero_fill bool) voidptr {
ptr := unsafe { vgc_span_alloc_obj(mut span) }
if ptr != unsafe { nil } {
if zero_fill {
unsafe { C.memset(ptr, 0, usize(span.elem_size)) }
unsafe { C.memset(ptr, 0, uint(span.elem_size)) }
}
unsafe {
vgc_heap.caches[cache_idx].tiny = usize(ptr)
vgc_heap.caches[cache_idx].tiny = uint(ptr)
vgc_heap.caches[cache_idx].tiny_offset = n
vgc_heap.caches[cache_idx].tiny_allocs++
}
@@ -1113,7 +1113,7 @@ fn vgc_malloc_noscan_opts(n usize, zero_fill bool) voidptr {
}
// Allocate a large object (> 32KB) with its own span
fn vgc_alloc_large(n usize, noscan bool, zero_fill bool, cache_idx int) voidptr {
fn vgc_alloc_large(n uint, noscan bool, zero_fill bool, cache_idx int) voidptr {
npages := u32((n + vgc_page_size - 1) / vgc_page_size)
span := vgc_span_alloc(npages, cache_idx + 1)
if span == unsafe { nil } {
@@ -1153,7 +1153,7 @@ fn vgc_alloc_large(n usize, noscan bool, zero_fill bool, cache_idx int) voidptr
}
// Realloc for VGC-managed memory
fn vgc_realloc(old_ptr voidptr, new_size usize) voidptr {
fn vgc_realloc(old_ptr voidptr, new_size uint) voidptr {
if old_ptr == unsafe { nil } {
return vgc_malloc(new_size)
}
@@ -1166,7 +1166,7 @@ fn vgc_realloc(old_ptr voidptr, new_size usize) voidptr {
// Unknown object - just malloc new
return vgc_malloc(new_size)
}
old_size := usize(old_span.elem_size)
old_size := uint(old_span.elem_size)
if new_size <= old_size {
return old_ptr // fits in current allocation
}
@@ -1230,7 +1230,7 @@ fn vgc_free(ptr voidptr) {
// vgc_free_obj frees the object at ptr for the thread with cache index cache_idx.
fn vgc_free_obj(span &VGC_Span, ptr voidptr, cache_idx int) {
obj_idx := u32((usize(ptr) - span.base) / usize(span.elem_size))
obj_idx := u32((uint(ptr) - span.base) / uint(span.elem_size))
if obj_idx < span.nelems && span.alloc_bits != unsafe { nil } {
if C.vgc_bitmap_get(span.alloc_bits, obj_idx) != 0 {
C.vgc_bitmap_clear(span.alloc_bits, obj_idx)
@@ -1247,18 +1247,18 @@ fn vgc_free_obj(span &VGC_Span, ptr voidptr, cache_idx int) {
}
// Calloc (zero-initialized allocation)
fn vgc_calloc(n usize) voidptr {
fn vgc_calloc(n uint) voidptr {
return vgc_malloc(n) // vgc_malloc already zeroes memory
}
// Typed memdup: allocate with pointer map and copy source data.
// Used by HEAP_vgc() macro for struct allocations with known layout.
@[markused]
fn vgc_memdup_typed(src voidptr, n isize, ptrmap u64, ptr_words u8) voidptr {
fn vgc_memdup_typed(src voidptr, n int, ptrmap u64, ptr_words u8) voidptr {
if src == unsafe { nil } || n <= 0 {
return unsafe { nil }
}
mem := vgc_malloc_typed_opts(usize(n), ptrmap, ptr_words, false)
mem := vgc_malloc_typed_opts(uint(n), ptrmap, ptr_words, false)
if mem != unsafe { nil } {
unsafe { C.memcpy(mem, src, n) }
}
@@ -1267,11 +1267,11 @@ fn vgc_memdup_typed(src voidptr, n isize, ptrmap u64, ptr_words u8) voidptr {
// Memdup variants that skip zero-fill when the destination will be overwritten.
@[markused]
fn vgc_memdup(src voidptr, n isize) voidptr {
fn vgc_memdup(src voidptr, n int) voidptr {
if src == unsafe { nil } || n <= 0 {
return unsafe { nil }
}
mem := vgc_malloc_typed_opts(usize(n), 0, 0, false)
mem := vgc_malloc_typed_opts(uint(n), 0, 0, false)
if mem != unsafe { nil } {
unsafe { C.memcpy(mem, src, n) }
}
@@ -1279,11 +1279,11 @@ fn vgc_memdup(src voidptr, n isize) voidptr {
}
@[markused]
fn vgc_memdup_noscan(src voidptr, n isize) voidptr {
fn vgc_memdup_noscan(src voidptr, n int) voidptr {
if src == unsafe { nil } || n <= 0 {
return unsafe { nil }
}
mem := vgc_malloc_noscan_opts(usize(n), false)
mem := vgc_malloc_noscan_opts(uint(n), false)
if mem != unsafe { nil } {
unsafe { C.memcpy(mem, src, n) }
}
@@ -1299,7 +1299,7 @@ fn vgc_memdup_noscan(src voidptr, n isize) voidptr {
// a recycled span keeps its page count, so the page map holds every span exactly once. The
// position is returned rather than kept in an iterator, because the compiler may move a local
// whose address is taken to the heap, and the collector must not allocate.
fn vgc_next_span(arena int, page usize) (&VGC_Span, int, usize) {
fn vgc_next_span(arena int, page uint) (&VGC_Span, int, uint) {
mut ai := arena
mut p := page
for ai < vgc_heap.narenas {
@@ -1311,7 +1311,7 @@ fn vgc_next_span(arena int, page usize) (&VGC_Span, int, usize) {
p++
continue
}
return span, ai, p + usize(span.npages)
return span, ai, p + uint(span.npages)
}
ai++
p = 0
@@ -1321,7 +1321,7 @@ fn vgc_next_span(arena int, page usize) (&VGC_Span, int, usize) {
@[direct_array_access]
fn vgc_find_span(ptr voidptr) &VGC_Span {
addr := usize(ptr)
addr := uint(ptr)
// Fast reject: most probed words are not heap pointers at all.
if addr < vgc_arena_lo || addr >= vgc_arena_hi {
return unsafe { nil }
@@ -1355,7 +1355,7 @@ fn vgc_find_span(ptr voidptr) &VGC_Span {
// vgc_find_arena returns the arena that holds addr, or nil.
@[direct_array_access]
fn vgc_find_arena(addr usize) &VGC_Arena {
fn vgc_find_arena(addr uint) &VGC_Arena {
g := addr >> vgc_granule_shift
if g < vgc_arena_map_granules {
chunk := vgc_heap.arena_map[g >> vgc_arena_map_l2_bits]
@@ -1386,16 +1386,16 @@ fn vgc_find_arena(addr usize) &VGC_Arena {
}
// Get the allocation size of an object
fn vgc_get_obj_size(ptr voidptr) usize {
fn vgc_get_obj_size(ptr voidptr) uint {
span := vgc_find_span(ptr)
if span == unsafe { nil } {
return 0
}
return usize(span.elem_size)
return uint(span.elem_size)
}
// Check if an address is within the GC heap - O(1) with fast bounds reject
fn vgc_is_heap_ptr(addr usize) bool {
fn vgc_is_heap_ptr(addr uint) bool {
// Fast reject: most words on the stack are NOT heap pointers
if addr < vgc_arena_lo || addr >= vgc_arena_hi {
return false
@@ -1416,16 +1416,16 @@ fn vgc_safepoint() {
fn vgc_safepoint_at(cache_idx int) {
// Wait below a frame that holds this thread's callee-saved registers, so that the
// collector's scan of this stack sees them.
C.vgc_call_with_registers_spilled(vgc_safepoint_wait, voidptr(isize(cache_idx)))
C.vgc_call_with_registers_spilled(vgc_safepoint_wait, voidptr(int(cache_idx)))
}
// vgc_safepoint_wait stops the thread with cache index arg while a collection runs. The
// collector scans its stack from regs, where the thread's registers are saved, upwards: the
// frames below are vgc's own.
fn vgc_safepoint_wait(arg voidptr, regs voidptr) {
cache_idx := int(isize(arg))
cache_idx := int(int(arg))
// Update the live stack range for root scanning.
vgc_refresh_stack_range_for_sp(cache_idx, usize(regs))
vgc_refresh_stack_range_for_sp(cache_idx, uint(regs))
// Mark ourselves as stopped
C.vgc_atomic_store_u32(&vgc_heap.caches[cache_idx].stopped, 1)
C.vgc_atomic_add_u32(&vgc_heap.gc_stopped_count, 1)
+33 -33
View File
@@ -6,7 +6,7 @@
module builtin
fn C.v3_vgc_mark_global_arrays()
fn C.vgc_data_ranges(lo &usize, hi &usize, max int) int
fn C.vgc_data_ranges(lo &uint, hi &uint, max int) int
// ============================================================
// GC Orchestration (translated from Go's runtime.gcStart, gcMarkDone, gcMarkTermination)
@@ -94,7 +94,7 @@ fn vgc_gc_run(_ voidptr, regs voidptr) {
C.vgc_atomic_store_u32(&vgc_heap.wb_enabled, 1)
// The thread starting GC does not pass through a safepoint.
vgc_refresh_stack_range_for_sp(self_idx, usize(regs))
vgc_refresh_stack_range_for_sp(self_idx, uint(regs))
// Scan roots: stacks + globals (conservative scanning)
vgc_mark_roots()
@@ -147,7 +147,7 @@ fn vgc_clear_mark_bits() {
// Keep the arena table still while walking it.
C.vgc_mutex_lock(&vgc_heap.lock)
mut arena := 0
mut page := usize(0)
mut page := uint(0)
for {
span, next_arena, next_page := vgc_next_span(arena, page)
if span == unsafe { nil } {
@@ -195,19 +195,19 @@ fn vgc_mark_roots() {
// and the spans that the caches allocate from, but no pointer that the program holds. The only
// objects that they keep alive are the tiny blocks, which vgc_mark_roots marks itself.
fn vgc_mark_data_segments() {
mut lo := [16]usize{}
mut hi := [16]usize{}
mut lo := [16]uint{}
mut hi := [16]uint{}
n := C.vgc_data_ranges(&lo[0], &hi[0], 16)
skip_lo := [usize(&vgc_heap), usize(&vgc_arena_lo), usize(&vgc_arena_hi)]!
skip_hi := [usize(&vgc_heap) + sizeof(VGC_Heap), usize(&vgc_arena_lo) + sizeof(usize),
usize(&vgc_arena_hi) + sizeof(usize)]!
skip_lo := [uint(&vgc_heap), uint(&vgc_arena_lo), uint(&vgc_arena_hi)]!
skip_hi := [uint(&vgc_heap) + sizeof(VGC_Heap), uint(&vgc_arena_lo) + sizeof(uint),
uint(&vgc_arena_hi) + sizeof(uint)]!
for i in 0 .. n {
vgc_scan_range_skipping(lo[i], hi[i], &skip_lo[0], &skip_hi[0], skip_lo.len)
}
}
// vgc_scan_range_skipping scans [lo, hi) without the nskip ranges [skip_lo[k], skip_hi[k]).
fn vgc_scan_range_skipping(lo usize, hi usize, skip_lo &usize, skip_hi &usize, nskip int) {
fn vgc_scan_range_skipping(lo uint, hi uint, skip_lo &uint, skip_hi &uint, nskip int) {
if lo >= hi {
return
}
@@ -230,22 +230,22 @@ fn vgc_scan_range_skipping(lo usize, hi usize, skip_lo &usize, skip_hi &usize, n
// Scan a memory range conservatively, looking for pointers into the GC heap.
// Each word-aligned value that looks like a heap pointer is treated as a root.
// Translated from Go's scanblock() with conservative pointer finding.
fn vgc_scan_range(lo usize, hi usize) {
fn vgc_scan_range(lo uint, hi uint) {
// Align to word boundaries
start := (lo + sizeof(usize) - 1) & ~(usize(sizeof(usize)) - 1)
start := (lo + sizeof(uint) - 1) & ~(uint(sizeof(uint)) - 1)
mut addr := start
for addr + sizeof(usize) <= hi {
val := unsafe { *(&usize(voidptr(addr))) }
for addr + sizeof(uint) <= hi {
val := unsafe { *(&uint(voidptr(addr))) }
if val != 0 {
vgc_shade(val)
}
addr += sizeof(usize)
addr += sizeof(uint)
}
}
// Shade marks an object grey (discovered but not yet scanned).
// Translated from Go's shade() in mgcmark.go.
fn vgc_shade(addr usize) {
fn vgc_shade(addr uint) {
if addr < vgc_arena_lo || addr >= vgc_arena_hi {
return
}
@@ -257,7 +257,7 @@ fn vgc_shade(addr usize) {
return
}
// Find which object this address belongs to
obj_idx := u32((addr - span.base) / usize(span.elem_size))
obj_idx := u32((addr - span.base) / uint(span.elem_size))
if obj_idx >= span.nelems {
return
}
@@ -270,7 +270,7 @@ fn vgc_shade(addr usize) {
if C.vgc_bitmap_test_and_set(span.mark_bits, obj_idx) == 0 {
// Newly marked - add to work queue for scanning (only if it may contain pointers)
if !span.noscan {
obj_addr := span.base + usize(obj_idx) * usize(span.elem_size)
obj_addr := span.base + uint(obj_idx) * uint(span.elem_size)
vgc_work_put(obj_addr)
}
}
@@ -310,7 +310,7 @@ fn vgc_drain_mark_work() {
vgc_scan_precise(obj_addr, span.ptrmap, span.ptr_words)
} else {
// Conservative fallback: scan every word
obj_size := usize(span.elem_size)
obj_size := uint(span.elem_size)
vgc_scan_range(obj_addr, obj_addr + obj_size)
}
}
@@ -318,9 +318,9 @@ fn vgc_drain_mark_work() {
// Precise pointer scanning: use the pointer bitmap to scan only
// word offsets known to contain pointers. Much faster than conservative.
fn vgc_scan_precise(obj_addr usize, ptrmap u64, ptr_words u8) {
fn vgc_scan_precise(obj_addr uint, ptrmap u64, ptr_words u8) {
mut mask := ptrmap
word_size := sizeof(usize)
word_size := sizeof(uint)
for mask != 0 {
// Find lowest set bit (next pointer offset)
mut bit := u8(0)
@@ -350,8 +350,8 @@ fn vgc_scan_precise(obj_addr usize, ptrmap u64, ptr_words u8) {
bit += 1
}
// Read the pointer at this offset
ptr_addr := obj_addr + usize(bit) * word_size
val := unsafe { *(&usize(voidptr(ptr_addr))) }
ptr_addr := obj_addr + uint(bit) * word_size
val := unsafe { *(&uint(voidptr(ptr_addr))) }
if val != 0 {
vgc_shade(val)
}
@@ -370,7 +370,7 @@ fn vgc_can_use_work_fastpath() bool {
}
// Add a pointer to the mark work queue
fn vgc_work_put(addr usize) {
fn vgc_work_put(addr uint) {
if vgc_can_use_work_fastpath() {
mut buf := vgc_heap.work_full
if buf == unsafe { nil } || buf.nobj >= 256 {
@@ -380,7 +380,7 @@ fn vgc_work_put(addr usize) {
vgc_heap.work_empty = new_buf.next
}
} else {
new_buf = unsafe { &VGC_WorkBuf(C.vgc_os_alloc(usize(sizeof(VGC_WorkBuf)))) }
new_buf = unsafe { &VGC_WorkBuf(C.vgc_os_alloc(uint(sizeof(VGC_WorkBuf)))) }
if new_buf == unsafe { nil } {
return
}
@@ -411,7 +411,7 @@ fn vgc_work_put(addr usize) {
vgc_heap.work_empty = new_buf.next
}
} else {
new_buf = unsafe { &VGC_WorkBuf(C.vgc_os_alloc(usize(sizeof(VGC_WorkBuf)))) }
new_buf = unsafe { &VGC_WorkBuf(C.vgc_os_alloc(uint(sizeof(VGC_WorkBuf)))) }
if new_buf == unsafe { nil } {
C.vgc_mutex_unlock(&vgc_heap.work_lock)
return
@@ -433,7 +433,7 @@ fn vgc_work_put(addr usize) {
}
// Get a pointer from the mark work queue
fn vgc_work_get() usize {
fn vgc_work_get() uint {
if vgc_can_use_work_fastpath() {
mut buf := vgc_heap.work_full
if buf == unsafe { nil } || buf.nobj == 0 {
@@ -489,7 +489,7 @@ fn vgc_write_barrier(new_val voidptr) {
return
}
// Shade the new pointer (mark it grey)
vgc_shade(usize(new_val))
vgc_shade(uint(new_val))
}
// ============================================================
@@ -519,7 +519,7 @@ fn vgc_sweep_spans() {
// Keep the arena table still while walking it.
C.vgc_mutex_lock(&vgc_heap.lock)
mut arena := 0
mut page := usize(0)
mut page := uint(0)
for {
span, next_arena, next_page := vgc_next_span(arena, page)
if span == unsafe { nil } {
@@ -618,7 +618,7 @@ fn vgc_count_marked() u64 {
mut total := u64(0)
C.vgc_mutex_lock(&vgc_heap.lock)
mut arena := 0
mut page := usize(0)
mut page := uint(0)
for {
span, next_arena, next_page := vgc_next_span(arena, page)
if span == unsafe { nil } {
@@ -672,7 +672,7 @@ fn vgc_update_trigger() {
// - total_bytes: the bytes allocated since the program started.
// - unmapped_bytes: the pages of the free spans, which went back to the OS.
// - bytes_since_gc: the bytes allocated since the last collection.
fn vgc_heap_usage() (usize, usize, usize, usize, usize) {
fn vgc_heap_usage() (uint, uint, uint, uint, uint) {
obtained := C.vgc_atomic_load_u64(&vgc_heap.arena_bytes)
used := C.vgc_atomic_load_u64(&vgc_heap.arena_used)
unmapped := C.vgc_atomic_load_u64(&vgc_heap.unmapped_bytes)
@@ -681,13 +681,13 @@ fn vgc_heap_usage() (usize, usize, usize, usize, usize) {
heap_size := if obtained > unmapped { obtained - unmapped } else { u64(0) }
free := if obtained > used { obtained - used } else { u64(0) }
since_gc := if total > at_gc { total - at_gc } else { u64(0) }
return usize(heap_size), usize(free), usize(total), usize(unmapped), usize(since_gc)
return uint(heap_size), uint(free), uint(total), uint(unmapped), uint(since_gc)
}
// vgc_memory_use returns the heap memory in use: the pages of the spans that are not free, which
// is heap_size - free_bytes, as with Boehm's GC_get_memory_use().
fn vgc_memory_use() usize {
fn vgc_memory_use() uint {
used := C.vgc_atomic_load_u64(&vgc_heap.arena_used)
unmapped := C.vgc_atomic_load_u64(&vgc_heap.unmapped_bytes)
return if used > unmapped { usize(used - unmapped) } else { usize(0) }
return if used > unmapped { uint(used - unmapped) } else { uint(0) }
}
+10 -10
View File
@@ -4,46 +4,46 @@ module builtin
// because of the missing definitions in $if vgc ? { } blocks.
// Note: they will NOT be called, since calls to them are wrapped with `$if vgc ? { }`.
fn vgc_malloc(n usize) voidptr {
fn vgc_malloc(n uint) voidptr {
return unsafe { nil }
}
fn vgc_malloc_noscan(n usize) voidptr {
fn vgc_malloc_noscan(n uint) voidptr {
return unsafe { nil }
}
fn vgc_malloc_typed_opts(n usize, ptrmap u64, ptr_words u8, zero_fill bool) voidptr {
fn vgc_malloc_typed_opts(n uint, ptrmap u64, ptr_words u8, zero_fill bool) voidptr {
return unsafe { nil }
}
fn vgc_malloc_noscan_opts(n usize, zero_fill bool) voidptr {
fn vgc_malloc_noscan_opts(n uint, zero_fill bool) voidptr {
return unsafe { nil }
}
fn vgc_memdup(src voidptr, n isize) voidptr {
fn vgc_memdup(src voidptr, n int) voidptr {
return unsafe { nil }
}
fn vgc_memdup_noscan(src voidptr, n isize) voidptr {
fn vgc_memdup_noscan(src voidptr, n int) voidptr {
return unsafe { nil }
}
fn vgc_realloc(old_ptr voidptr, new_size usize) voidptr {
fn vgc_realloc(old_ptr voidptr, new_size uint) voidptr {
return unsafe { nil }
}
fn vgc_calloc(n usize) voidptr {
fn vgc_calloc(n uint) voidptr {
return unsafe { nil }
}
fn vgc_free(ptr voidptr) {
}
fn vgc_heap_usage() (usize, usize, usize, usize, usize) {
fn vgc_heap_usage() (uint, uint, uint, uint, uint) {
return 0, 0, 0, 0, 0
}
fn vgc_memory_use() usize {
fn vgc_memory_use() uint {
return 0
}
+3 -3
View File
@@ -4,13 +4,13 @@ module builtin
// Shitty `sbrk` basic `malloc` and `free` impl
// TODO: implement pure V `walloc` later
__global g_heap_base = usize(vwasm_heap_base())
__global g_heap_base = uint(vwasm_heap_base())
// malloc dynamically allocates a `n` bytes block of memory on the heap.
// malloc returns a `byteptr` pointing to the memory address of the allocated space.
// unlike the `calloc` family of functions - malloc will not zero the memory block.
@[unsafe]
pub fn malloc(n isize) &u8 {
pub fn malloc(n int) &u8 {
if n <= 0 {
$if no_imports ? {
return unsafe { nil }
@@ -20,7 +20,7 @@ pub fn malloc(n isize) &u8 {
}
res := g_heap_base
g_heap_base += usize(n)
g_heap_base += uint(n)
return &u8(res)
}
+4 -4
View File
@@ -41,7 +41,7 @@ pub fn vwasm_memory_grow(size int) int {
// vcalloc returns a `byteptr` pointing to the memory address of the allocated space.
// vcalloc checks for negative values given in `n`.
@[unsafe]
pub fn vcalloc(n isize) &u8 {
pub fn vcalloc(n int) &u8 {
if n <= 0 {
$if no_imports ? {
return unsafe { nil }
@@ -73,7 +73,7 @@ pub fn isnil(v voidptr) bool {
// vmemcpy copies n bytes from memory area src to memory area dest.
// The memory areas **CAN** overlap. vmemcpy returns a pointer to `dest`.
@[unsafe]
pub fn vmemcpy(dest voidptr, const_src voidptr, n isize) voidptr {
pub fn vmemcpy(dest voidptr, const_src voidptr, n int) voidptr {
asm wasm {
local.get dest
local.get const_src
@@ -89,7 +89,7 @@ pub fn vmemcpy(dest voidptr, const_src voidptr, n isize) voidptr {
// vmemmove copies n bytes from memory area src to memory area dest.
// The memory areas **CAN** overlap. vmemmove returns a pointer to `dest`.
@[unsafe]
pub fn vmemmove(dest voidptr, const_src voidptr, n isize) voidptr {
pub fn vmemmove(dest voidptr, const_src voidptr, n int) voidptr {
asm wasm {
local.get dest
local.get const_src
@@ -105,7 +105,7 @@ pub fn vmemmove(dest voidptr, const_src voidptr, n isize) voidptr {
// 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`.
@[unsafe]
pub fn vmemset(s voidptr, c int, n isize) voidptr {
pub fn vmemset(s voidptr, c int, n int) voidptr {
asm wasm {
local.get s
local.get c
@@ -4,7 +4,7 @@ module builtin
pub fn print(s string) {
elm := CIOVec{
buf: s.str
len: usize(s.len)
len: uint(s.len)
}
WASM.fd_write(1, &elm, 1, 0)
@@ -14,7 +14,7 @@ pub fn print(s string) {
pub fn println(s string) {
elm := [CIOVec{
buf: s.str
len: usize(s.len)
len: uint(s.len)
}, CIOVec{
buf: c'\n'
len: 1
@@ -27,7 +27,7 @@ pub fn println(s string) {
pub fn eprint(s string) {
elm := CIOVec{
buf: s.str
len: usize(s.len)
len: uint(s.len)
}
WASM.fd_write(2, &elm, 1, 0)
@@ -37,7 +37,7 @@ pub fn eprint(s string) {
pub fn eprintln(s string) {
elm := [CIOVec{
buf: s.str
len: usize(s.len)
len: uint(s.len)
}, CIOVec{
buf: c'\n'
len: 1
@@ -3,7 +3,7 @@ module builtin
pub struct CIOVec {
pub:
buf &u8
len usize
len uint
}
type Errno = u16
@@ -16,16 +16,16 @@ fn WASM.args_sizes_get(argc &u32, argc_buf_size &u32) Errno
fn WASM.args_get(argv &&u8, argv_buf &u8) Errno
@[wasm_import_namespace: 'wasi_snapshot_preview1']
fn WASM.fd_write(fd FileDesc, iovs &CIOVec, iovs_len usize, retptr &usize) Errno
fn WASM.fd_write(fd FileDesc, iovs &CIOVec, iovs_len uint, retptr &uint) Errno
@[wasm_import_namespace: 'wasi_snapshot_preview1']
fn WASM.fd_read(fd FileDesc, iovs &CIOVec, iovs_len usize, nread &usize) Errno
fn WASM.fd_read(fd FileDesc, iovs &CIOVec, iovs_len uint, nread &uint) Errno
@[wasm_import_namespace: 'wasi_snapshot_preview1']
fn WASM.fd_sync(fd FileDesc) Errno
@[wasm_import_namespace: 'wasi_snapshot_preview1']
fn WASM.random_get(buf &u8, buf_len usize) Errno
fn WASM.random_get(buf &u8, buf_len uint) Errno
@[wasm_import_namespace: 'wasi_snapshot_preview1']
@[noreturn]
+15 -13
View File
@@ -2,8 +2,9 @@ module builtin
//__global global_allocator dlmalloc.Dlmalloc
// __malloc allocates size bytes of memory.
@[unsafe]
pub fn __malloc(size usize) voidptr {
pub fn __malloc(size uint) voidptr {
unsafe {
$if windows {
// Warning! On windows, we always use _aligned_malloc to allocate memory.
@@ -18,8 +19,9 @@ pub fn __malloc(size usize) voidptr {
return unsafe { nil }
}
// memcpy copies n bytes from const_src to dest.
@[unsafe]
pub fn memcpy(dest &C.void, const_src &C.void, n usize) &C.void {
pub fn memcpy(dest &C.void, const_src &C.void, n uint) &C.void {
dest_ := unsafe { &u8(dest) }
src_ := unsafe { &u8(const_src) }
unsafe {
@@ -31,20 +33,20 @@ pub fn memcpy(dest &C.void, const_src &C.void, n usize) &C.void {
}
@[unsafe]
fn strlen(const_s &char) usize {
fn strlen(const_s &char) uint {
s := unsafe { &u8(const_s) }
mut i := 0
for ; unsafe { s[i] } != 0; i++ {
}
return usize(i)
return uint(i)
}
@[unsafe]
fn realloc(old_area &C.void, new_size usize) &C.void {
fn realloc(old_area &C.void, new_size uint) &C.void {
if old_area == 0 {
return unsafe { malloc(int(new_size)) }
}
if new_size == usize(0) {
if new_size == uint(0) {
unsafe { free(old_area) }
return 0
}
@@ -53,14 +55,14 @@ fn realloc(old_area &C.void, new_size usize) &C.void {
return unsafe { old_area }
} else {
new_area := unsafe { malloc(int(new_size)) }
unsafe { memmove(new_area, old_area, usize(old_size)) }
unsafe { memmove(new_area, old_area, uint(old_size)) }
unsafe { free(old_area) }
return new_area
}
}
@[unsafe]
fn memset(s &C.void, c int, n usize) &C.void {
fn memset(s &C.void, c int, n uint) &C.void {
mut s_ := unsafe { &char(s) }
for i in 0 .. int(n) {
unsafe {
@@ -71,7 +73,7 @@ fn memset(s &C.void, c int, n usize) &C.void {
}
@[unsafe]
fn memmove(dest &C.void, const_src &C.void, n usize) &C.void {
fn memmove(dest &C.void, const_src &C.void, n uint) &C.void {
dest_ := unsafe { &u8(dest) }
src_ := unsafe { &u8(const_src) }
mut temp_buf := unsafe { malloc(int(n)) }
@@ -92,7 +94,7 @@ fn memmove(dest &C.void, const_src &C.void, n usize) &C.void {
@[export: 'calloc']
@[unsafe]
fn __calloc(nmemb usize, size usize) &C.void {
fn __calloc(nmemb uint, size uint) &C.void {
new_area := unsafe { malloc(int(nmemb) * int(size)) }
unsafe { memset(new_area, 0, nmemb * size) }
return new_area
@@ -102,7 +104,7 @@ fn getchar() int {
return 0
}
fn memcmp(const_a &C.void, const_b &C.void, n usize) int {
fn memcmp(const_a &C.void, const_b &C.void, n uint) int {
a_ := unsafe { &u8(const_a) }
b_ := unsafe { &u8(const_b) }
for i in 0 .. int(n) {
@@ -119,7 +121,7 @@ fn vsprintf(str &char, format &char, ap &u8) int {
panic('vsprintf(): string interpolation is not supported in `-freestanding`')
}
fn vsnprintf(str &char, size usize, format &char, ap &u8) int {
fn vsnprintf(str &char, size uint, format &char, ap &u8) int {
panic('vsnprintf(): string interpolation is not supported in `-freestanding`')
}
@@ -165,6 +167,6 @@ fn __exit(code int) {
}
@[export: 'qsort']
fn __qsort(base voidptr, nmemb usize, size usize, sort_cb FnSortCB) {
fn __qsort(base voidptr, nmemb uint, size uint, sort_cb FnSortCB) {
panic('qsort() is not yet implemented in `-freestanding`')
}
+10 -10
View File
@@ -12,7 +12,7 @@ $if linux {
fn C.v_brotli_open(const_name &char) voidptr
fn C.v_brotli_sym(handle voidptr, const_name &char) voidptr
fn C.v_brotli_close(handle voidptr) int
fn C.v_brotli_msan_unpoison(ptr voidptr, len usize)
fn C.v_brotli_msan_unpoison(ptr voidptr, len uint)
const min_quality = 0
const max_quality = 11
@@ -25,15 +25,15 @@ const decoder_result_success = 1
const decoder_result_needs_more_input = 2
const decoder_result_needs_more_output = 3
type FNEncoderMaxCompressedSize = fn (usize) usize
type FNEncoderMaxCompressedSize = fn (uint) uint
type FNEncoderCompress = fn (int, int, int, usize, voidptr, &usize, voidptr) int
type FNEncoderCompress = fn (int, int, int, uint, voidptr, &uint, voidptr) int
type FNDecoderCreateInstance = fn (voidptr, voidptr, voidptr) voidptr
type FNDecoderDestroyInstance = fn (voidptr)
type FNDecoderDecompressStream = fn (voidptr, &usize, &&u8, &usize, &&u8, &usize) int
type FNDecoderDecompressStream = fn (voidptr, &uint, &&u8, &uint, &&u8, &uint) int
type FNDecoderGetErrorCode = fn (voidptr) int
@@ -179,7 +179,7 @@ pub fn compress(data []u8, params CompressParams) ![]u8 {
max_compressed_size := FNEncoderMaxCompressedSize(library_symbol(enc,
'BrotliEncoderMaxCompressedSize', 'encoder')!)
encoder_compress := FNEncoderCompress(library_symbol(enc, 'BrotliEncoderCompress', 'encoder')!)
dst_capacity := max_compressed_size(usize(data.len))
dst_capacity := max_compressed_size(uint(data.len))
if dst_capacity == 0 {
return error('brotli: input is too large')
}
@@ -191,7 +191,7 @@ pub fn compress(data []u8, params CompressParams) ![]u8 {
}
}
mut encoded_size := dst_capacity
ok := encoder_compress(params.quality, params.lgwin, int(params.mode), usize(data.len),
ok := encoder_compress(params.quality, params.lgwin, int(params.mode), uint(data.len),
data.data, &encoded_size, dst.data)
if ok == 0 {
return error('brotli: compression failed')
@@ -235,17 +235,17 @@ pub fn decompress(data []u8, _ DecompressParams) ![]u8 {
defer {
unsafe { chunk.free() }
}
mut available_in := usize(data.len)
mut available_in := uint(data.len)
mut next_in := unsafe { &u8(data.data) }
for {
mut available_out := usize(chunk.len)
mut available_out := uint(chunk.len)
mut next_out := unsafe { &u8(chunk.data) }
mut total_out := usize(0)
mut total_out := uint(0)
result := decoder_stream(state, &available_in, &next_in, &available_out, &next_out,
&total_out)
produced := chunk.len - int(available_out)
if produced > 0 {
C.v_brotli_msan_unpoison(chunk.data, usize(produced))
C.v_brotli_msan_unpoison(chunk.data, uint(produced))
out << chunk[..produced]
}
match result {
+7 -7
View File
@@ -10,8 +10,8 @@ module compress
@[deprecated_after: '2026-07-31']
pub const max_size = u64(1 << 31)
fn C.tdefl_compress_mem_to_heap(source_buf voidptr, source_buf_len usize, out_len &usize, flags i32) voidptr
fn C.tinfl_decompress_mem_to_heap(source_buf voidptr, source_buf_len usize, out_len &usize, flags i32) voidptr
fn C.tdefl_compress_mem_to_heap(source_buf voidptr, source_buf_len uint, out_len &uint, flags i32) voidptr
fn C.tinfl_decompress_mem_to_heap(source_buf voidptr, source_buf_len uint, out_len &uint, flags i32) voidptr
// compresses an array of bytes based on providing flags and returns the compressed bytes in a new array
// NB: this is a low level api, a high level implementation like zlib/gzip should be preferred
@@ -22,7 +22,7 @@ pub fn compress(data []u8, flags int) ![]u8 {
if u64(data.len) > max_size {
return error('data too large (${data.len} > ${max_size})')
}
mut out_len := usize(0)
mut out_len := uint(0)
address := C.tdefl_compress_mem_to_heap(data.data, data.len, &out_len, flags)
if address == 0 {
@@ -44,7 +44,7 @@ pub fn compress(data []u8, flags int) ![]u8 {
@[deprecated_after: '2026-07-31']
@[manualfree]
pub fn decompress(data []u8, flags int) ![]u8 {
mut out_len := usize(0)
mut out_len := uint(0)
address := C.tinfl_decompress_mem_to_heap(data.data, data.len, &out_len, flags)
if address == 0 {
@@ -79,7 +79,7 @@ pub type ChunkCallback = fn (chunk []u8, userdata voidptr) int
pub fn decompress_with_callback(data []u8, cb ChunkCallback, userdata voidptr, flags int) !u64 {
cbdata := DecompressionCallBackData{
data: data.data
size: usize(data.len)
size: uint(data.len)
cb: cb
userdata: userdata
}
@@ -94,7 +94,7 @@ pub fn decompress_with_callback(data []u8, cb ChunkCallback, userdata voidptr, f
struct DecompressionCallBackData {
mut:
data voidptr
size usize
size uint
decompressed_size u64
userdata voidptr
cb ChunkCallback = unsafe { nil }
@@ -114,4 +114,4 @@ fn c_cb_for_decompress_mem(buf &char, len i32, pdcbd voidptr) i32 {
type DecompressCallback = fn (const_buffer voidptr, len i32, userdata voidptr) i32
fn C.tinfl_decompress_mem_to_callback(const_input_buffer voidptr, psize &usize, put_buf_cb DecompressCallback, userdata voidptr, flags i32) i32
fn C.tinfl_decompress_mem_to_callback(const_input_buffer voidptr, psize &uint, put_buf_cb DecompressCallback, userdata voidptr, flags i32) i32
+1 -1
View File
@@ -70,7 +70,7 @@ fn bit_flips(data []u8, start int) [][]u8 {
return res
}
// assert_checksum_errors checks that, with the payload intact, a wrong adler32, crc32 or isize
// assert_checksum_errors checks that, with the payload intact, a wrong adler32, crc32 or int
// is reported as exactly that, by the one-shot and by the callback decoder.
fn assert_checksum_errors(payload []u8, plain []u8) ! {
z := zlib_stream(payload, plain)
+1 -1
View File
@@ -240,7 +240,7 @@ fn test_gzip_damaged_payload_is_reported_as_such_whatever_the_trailer() {
'invalid gzip stream: size mismatch']
assert callback_error(damaged) == payload_error
// Nothing was decoded, so there is nothing to compare the trailer with:
// a wrong crc32 or isize on top of that does not change the error.
// a wrong crc32 or int on top of that does not change the error.
for i in [damaged.len - 8, damaged.len - 4] {
mut both := damaged.clone()
both[i] ^= 0x01
+6 -6
View File
@@ -25,7 +25,7 @@ fn C.zip_close(&Zip)
fn C.zip_entry_open(&Zip, &u8) i32
fn C.zip_entry_openbyindex(&Zip, usize) i32
fn C.zip_entry_openbyindex(&Zip, uint) i32
fn C.zip_entry_close(&Zip) i32
@@ -39,13 +39,13 @@ fn C.zip_entry_size(&Zip) u64
fn C.zip_entry_crc32(&Zip) u32
fn C.zip_entry_write(&Zip, voidptr, usize) i32
fn C.zip_entry_write(&Zip, voidptr, uint) i32
fn C.zip_entry_fwrite(&Zip, &char) i32
fn C.zip_entry_read(&Zip, &voidptr, &usize) i32
fn C.zip_entry_read(&Zip, &voidptr, &uint) i32
fn C.zip_entry_noallocread(&Zip, voidptr, usize) i32
fn C.zip_entry_noallocread(&Zip, voidptr, uint) i32
fn C.zip_entry_fread(&Zip, &char) i32
@@ -204,7 +204,7 @@ pub fn (mut zentry Zip) create_entry(name string) ! {
// for large entries, please take a look at zip_entry_extract function.
pub fn (mut zentry Zip) read_entry() !voidptr {
mut buf := &u8(unsafe { nil })
mut bsize := usize(0)
mut bsize := uint(0)
res := C.zip_entry_read(zentry, unsafe { &voidptr(&buf) }, &bsize)
if res == -1 {
return error('szip: cannot read properly data from entry')
@@ -214,7 +214,7 @@ pub fn (mut zentry Zip) read_entry() !voidptr {
// read_entry_buf extracts the current zip entry into user specified buffer.
pub fn (mut zentry Zip) read_entry_buf(buf voidptr, in_bsize int) !int {
bsize := usize(in_bsize)
bsize := uint(in_bsize)
res := C.zip_entry_noallocread(zentry, buf, bsize)
if res == -1 {
return error('szip: cannot read properly data from entry')
+49 -49
View File
@@ -28,22 +28,22 @@ const buf_out_size = 1024 * 1024
fn C.ZSTD_versionNumber() u32
fn C.ZSTD_versionString() charptr
fn C.ZSTD_compress(voidptr, usize, voidptr, usize, i32) usize
fn C.ZSTD_decompress(voidptr, usize, voidptr, usize) usize
fn C.ZSTD_getFrameContentSize(voidptr, usize) u64
fn C.ZSTD_findFrameCompressedSize(voidptr, usize) usize
fn C.ZSTD_compressBound(usize) usize
fn C.ZSTD_isError(usize) u32
fn C.ZSTD_getErrorName(usize) charptr
fn C.ZSTD_compress(voidptr, uint, voidptr, uint, i32) uint
fn C.ZSTD_decompress(voidptr, uint, voidptr, uint) uint
fn C.ZSTD_getFrameContentSize(voidptr, uint) u64
fn C.ZSTD_findFrameCompressedSize(voidptr, uint) uint
fn C.ZSTD_compressBound(uint) uint
fn C.ZSTD_isError(uint) u32
fn C.ZSTD_getErrorName(uint) charptr
fn C.ZSTD_minCLevel() i32
fn C.ZSTD_maxCLevel() i32
fn C.ZSTD_defaultCLevel() i32
fn C.ZSTD_createCCtx() &C.ZSTD_CCtx_s
fn C.ZSTD_freeCCtx(voidptr) usize
fn C.ZSTD_compressCCtx(voidptr, voidptr, usize, voidptr, usize, i32) usize
fn C.ZSTD_freeCCtx(voidptr) uint
fn C.ZSTD_compressCCtx(voidptr, voidptr, uint, voidptr, uint, i32) uint
fn C.ZSTD_createDCtx() &C.ZSTD_DCtx_s
fn C.ZSTD_freeDCtx(voidptr) usize
fn C.ZSTD_decompressDCtx(voidptr, voidptr, usize, voidptr, usize) usize
fn C.ZSTD_freeDCtx(voidptr) uint
fn C.ZSTD_decompressDCtx(voidptr, voidptr, uint, voidptr, uint) uint
// note : new strategies _might_ be added in the future. Only the order (from fast to strong) is guaranteed
pub enum Strategy {
@@ -272,14 +272,14 @@ pub enum CParameter {
pub struct Bounds {
pub:
error usize
error uint
lower_bound int
upper_bound int
}
fn C.ZSTD_cParam_getBounds(CParameter) Bounds
fn C.ZSTD_CCtx_setParameter(voidptr, CParameter, i32) usize
fn C.ZSTD_CCtx_setPledgedSrcSize(voidptr, u64) usize
fn C.ZSTD_CCtx_setParameter(voidptr, CParameter, i32) uint
fn C.ZSTD_CCtx_setPledgedSrcSize(voidptr, u64) uint
pub enum ResetDirective {
session_only = 1
@@ -287,8 +287,8 @@ pub enum ResetDirective {
session_and_parameters = 3
}
fn C.ZSTD_CCtx_reset(voidptr, ResetDirective) usize
fn C.ZSTD_compress2(voidptr, voidptr, usize, voidptr, usize) usize
fn C.ZSTD_CCtx_reset(voidptr, ResetDirective) uint
fn C.ZSTD_compress2(voidptr, voidptr, uint, voidptr, uint) uint
pub enum DParameter {
// Select a size limit (in power of 2) beyond which
@@ -317,26 +317,26 @@ pub enum DParameter {
}
fn C.ZSTD_dParam_getBounds(DParameter) Bounds
fn C.ZSTD_DCtx_setParameter(voidptr, DParameter, i32) usize
fn C.ZSTD_DCtx_reset(voidptr, ResetDirective) usize
fn C.ZSTD_DCtx_setParameter(voidptr, DParameter, i32) uint
fn C.ZSTD_DCtx_reset(voidptr, ResetDirective) uint
// streaming compression
pub struct InBuffer {
pub mut:
src voidptr
size usize
pos usize
size uint
pos uint
}
pub struct OutBuffer {
pub mut:
dst voidptr
size usize
pos usize
size uint
pos uint
}
fn C.ZSTD_createCStream() voidptr
fn C.ZSTD_freeCStream(voidptr) usize
fn C.ZSTD_freeCStream(voidptr) uint
pub enum EndDirective {
// collect more data, encoder decides when to output compressed result, for optimal compression ratio
@@ -354,21 +354,21 @@ pub enum EndDirective {
end = 2
}
fn C.ZSTD_compressStream2(voidptr, &OutBuffer, &InBuffer, EndDirective) usize
fn C.ZSTD_CStreamInSize() usize
fn C.ZSTD_CStreamOutSize() usize
fn C.ZSTD_initCStream(voidptr, i32) usize
fn C.ZSTD_compressStream(voidptr, &OutBuffer, &InBuffer) usize
fn C.ZSTD_flushStream(voidptr, &OutBuffer) usize
fn C.ZSTD_endStream(voidptr, &OutBuffer) usize
fn C.ZSTD_compressStream2(voidptr, &OutBuffer, &InBuffer, EndDirective) uint
fn C.ZSTD_CStreamInSize() uint
fn C.ZSTD_CStreamOutSize() uint
fn C.ZSTD_initCStream(voidptr, i32) uint
fn C.ZSTD_compressStream(voidptr, &OutBuffer, &InBuffer) uint
fn C.ZSTD_flushStream(voidptr, &OutBuffer) uint
fn C.ZSTD_endStream(voidptr, &OutBuffer) uint
// streaming decompression
fn C.ZSTD_createDStream() voidptr
fn C.ZSTD_freeDStream(voidptr) usize
fn C.ZSTD_initDStream(voidptr) usize
fn C.ZSTD_decompressStream(voidptr, &OutBuffer, &InBuffer) usize
fn C.ZSTD_DStreamInSize() usize
fn C.ZSTD_DStreamOutSize() usize
fn C.ZSTD_freeDStream(voidptr) uint
fn C.ZSTD_initDStream(voidptr) uint
fn C.ZSTD_decompressStream(voidptr, &OutBuffer, &InBuffer) uint
fn C.ZSTD_DStreamInSize() uint
fn C.ZSTD_DStreamOutSize() uint
// version_number returns runtime library version, the value is (MAJOR*100*100 + MINOR*100 + RELEASE).
pub fn version_number() u32 {
@@ -380,18 +380,18 @@ pub fn version_string() string {
return unsafe { tos_clone(C.ZSTD_versionString()) }
}
// is_error tells if a `usize` function result is an error code.
pub fn is_error(code usize) bool {
// is_error tells if a `uint` function result is an error code.
pub fn is_error(code uint) bool {
return C.ZSTD_isError(code) == 1
}
// get_error_name provides readable string from an error code.
pub fn get_error_name(code usize) string {
pub fn get_error_name(code uint) string {
return unsafe { tos_clone(&u8(C.ZSTD_getErrorName(code))) }
}
// check_zstd checks the zstd error code, and return a error string.
pub fn check_error(code usize) ! {
pub fn check_error(code uint) ! {
if is_error(code) {
return error(get_error_name(code))
}
@@ -496,14 +496,14 @@ pub fn (mut c CCtx) set(c_param CParameter, val int) ! {
// .zstd_e_continue => continue stream compression.
// .zstd_e_flush => flush data
// .zstd_e_end => it is the last frame
pub fn (mut c CCtx) compress_stream2(output &OutBuffer, input &InBuffer, mode EndDirective) !usize {
pub fn (mut c CCtx) compress_stream2(output &OutBuffer, input &InBuffer, mode EndDirective) !uint {
res := C.ZSTD_compressStream2(c.ctx, output, input, mode)
check_error(res)!
return res
}
// free_cctx free a compression context.
pub fn (mut c CCtx) free_cctx() usize {
pub fn (mut c CCtx) free_cctx() uint {
return C.ZSTD_freeCCtx(c.ctx)
}
@@ -535,14 +535,14 @@ pub fn (mut d DCtx) set(d_param DParameter, val int) ! {
// decompress_stream do stream decompress on `input`, and store decompressed data in `output`.
// return remaining bytes in `input` stream
pub fn (mut d DCtx) decompress_stream(output &OutBuffer, input &InBuffer) !usize {
pub fn (mut d DCtx) decompress_stream(output &OutBuffer, input &InBuffer) !uint {
res := C.ZSTD_decompressStream(d.ctx, output, input)
check_error(res)!
return res
}
// free_cctx free a compression context
pub fn (mut d DCtx) free_dctx() usize {
pub fn (mut d DCtx) free_dctx() uint {
return C.ZSTD_freeDCtx(d.ctx)
}
@@ -587,7 +587,7 @@ pub fn store_array[T](fname string, array []T, params CompressParams) ! {
fout.write(buf_out[..int(output.pos)])!
// then, write the array.data to file
input.src = array.data
input.size = usize(array.len * int(sizeof(T)))
input.size = uint(array.len * int(sizeof(T)))
input.pos = 0
output.dst = buf_out.data
output.size = buf_out_size
@@ -618,29 +618,29 @@ pub fn load_array[T](fname string, params DecompressParams) ![]T {
mut len_buf := []u8{len: 8}
mut input := &InBuffer{}
mut output := &OutBuffer{}
mut last_ret := usize(0)
mut last_ret := uint(0)
mut last_chunk := false
// first, read the array.len from file
mut read_len := fin.read(mut buf_in)!
last_chunk = read_len < buf_in.len
input.src = buf_in.data
input.size = usize(read_len)
input.size = uint(read_len)
input.pos = 0
output.dst = len_buf.data
output.size = usize(len_buf.len)
output.size = uint(len_buf.len)
output.pos = 0
last_ret = dctx.decompress_stream(output, input)!
len := binary.little_endian_u64(len_buf)
// then, read the array.data from file
mut result := []T{len: int(len)}
output.dst = result.data
output.size = usize(result.len) * sizeof(T)
output.size = uint(result.len) * sizeof(T)
output.pos = 0
last_ret = dctx.decompress_stream(output, input)!
for !last_chunk {
read_len = fin.read(mut buf_in)!
last_chunk = read_len < buf_in.len
input.size = usize(read_len)
input.size = uint(read_len)
input.pos = 0
for input.pos < input.size {
last_ret = dctx.decompress_stream(output, input)!
+3 -3
View File
@@ -164,7 +164,7 @@ fn compress_file(fname string, oname string, params CompressParams) ! {
mut finished := false
input.src = buf_in.data
input.size = usize(read_len)
input.size = uint(read_len)
input.pos = 0
for !finished {
output.dst = buf_out.data
@@ -208,11 +208,11 @@ fn decompress_file(fname string, oname string, params DecompressParams) ! {
pos: 0
}
mut last_ret := usize(0)
mut last_ret := uint(0)
for {
read_len := fin.read(mut buf_in)!
input.src = buf_in.data
input.size = usize(read_len)
input.size = uint(read_len)
input.pos = 0
for input.pos < input.size {
output.dst = buf_out.data
+10 -10
View File
@@ -78,20 +78,20 @@ fn C.EVP_PKEY_public_check(ctx &C.EVP_PKEY_CTX) i32
fn C.EVP_PKEY_dup(key &C.EVP_PKEY) &C.EVP_PKEY
fn C.EVP_PKEY_set_bn_param(pkey &C.EVP_PKEY, const_key_name &char, const_bn &C.BIGNUM) i32
fn C.EVP_PKEY_get_group_name(pkey &C.EVP_PKEY, gname &u8, gname_sz u32, gname_len &usize) i32
fn C.EVP_PKEY_get1_encoded_public_key(pkey &C.EVP_PKEY, ppub &&u8) usize
fn C.EVP_PKEY_get_group_name(pkey &C.EVP_PKEY, gname &u8, gname_sz u32, gname_len &uint) i32
fn C.EVP_PKEY_get1_encoded_public_key(pkey &C.EVP_PKEY, ppub &&u8) uint
fn C.EVP_PKEY_get_bn_param(pkey &C.EVP_PKEY, key_name &char, bn &&C.BIGNUM) i32
fn C.EVP_PKEY_fromdata_init(ctx &C.EVP_PKEY_CTX) i32
fn C.EVP_PKEY_fromdata(ctx &C.EVP_PKEY_CTX, ppkey &&C.EVP_PKEY, selection i32, params &C.OSSL_PARAM) i32
// no-prehash signing (verifying)
fn C.EVP_PKEY_sign(ctx &C.EVP_PKEY_CTX, sig &u8, siglen &usize, tbs &u8, tbslen usize) i32
fn C.EVP_PKEY_sign(ctx &C.EVP_PKEY_CTX, sig &u8, siglen &uint, tbs &u8, tbslen uint) i32
fn C.EVP_PKEY_sign_init(ctx &C.EVP_PKEY_CTX) i32
fn C.EVP_PKEY_verify_init(ctx &C.EVP_PKEY_CTX) i32
fn C.EVP_PKEY_verify(ctx &C.EVP_PKEY_CTX, sig &u8, siglen usize, tbs &u8, tbslen usize) i32
fn C.EVP_PKEY_verify(ctx &C.EVP_PKEY_CTX, sig &u8, siglen uint, tbs &u8, tbslen uint) i32
// single shoot digest signing (verifying) routine
fn C.EVP_DigestSign(ctx &C.EVP_MD_CTX, sig &u8, siglen &usize, tbs &u8, tbslen i32) i32
fn C.EVP_DigestSign(ctx &C.EVP_MD_CTX, sig &u8, siglen &uint, tbs &u8, tbslen i32) i32
fn C.EVP_DigestVerify(ctx &C.EVP_MD_CTX, sig &u8, siglen i32, tbs &u8, tbslen i32) i32
// Message digest routines
@@ -102,7 +102,7 @@ fn C.EVP_DigestFinal(ctx &C.EVP_MD_CTX, md &u8, s &u32) i32
// Recommended hashed signing/verifying routines
fn C.EVP_DigestSignInit(ctx &C.EVP_MD_CTX, pctx &&C.EVP_PKEY_CTX, tipe &C.EVP_MD, e &C.ENGINE, pkey &C.EVP_PKEY) i32
fn C.EVP_DigestSignUpdate(ctx &C.EVP_MD_CTX, d voidptr, cnt i32) i32
fn C.EVP_DigestSignFinal(ctx &C.EVP_MD_CTX, sig &u8, siglen &usize) i32
fn C.EVP_DigestSignFinal(ctx &C.EVP_MD_CTX, sig &u8, siglen &uint) i32
fn C.EVP_DigestVerifyInit(ctx &C.EVP_MD_CTX, pctx &&C.EVP_PKEY_CTX, tipe &C.EVP_MD, e &C.ENGINE, pkey &C.EVP_PKEY) i32
fn C.EVP_DigestVerifyUpdate(ctx &C.EVP_MD_CTX, d voidptr, cnt i32) i32
fn C.EVP_DigestVerifyFinal(ctx &C.EVP_MD_CTX, sig &u8, siglen i32) i32
@@ -122,7 +122,7 @@ fn C.EVP_PKEY_CTX_free(ctx &C.EVP_PKEY_CTX)
// ECDH key agreement (used to derive TLS 1.3's P-256 ECDHE shared secret).
fn C.EVP_PKEY_derive_init(ctx &C.EVP_PKEY_CTX) i32
fn C.EVP_PKEY_derive_set_peer(ctx &C.EVP_PKEY_CTX, peer &C.EVP_PKEY) i32
fn C.EVP_PKEY_derive(ctx &C.EVP_PKEY_CTX, key &u8, keylen &usize) i32
fn C.EVP_PKEY_derive(ctx &C.EVP_PKEY_CTX, key &u8, keylen &uint) i32
fn C.EVP_PKEY_get_bits(pkey &C.EVP_PKEY) i32
@@ -150,7 +150,7 @@ struct C.EC_POINT {}
fn C.EC_POINT_new(group &C.EC_GROUP) &C.EC_POINT
fn C.EC_POINT_mul(group &C.EC_GROUP, r &C.EC_POINT, n &C.BIGNUM, q &C.EC_POINT, m &C.BIGNUM, ctx &C.BN_CTX) i32
fn C.EC_POINT_point2buf(group &C.EC_GROUP, point &C.EC_POINT, form i32, pbuf &&u8, ctx &C.BN_CTX) usize
fn C.EC_POINT_point2buf(group &C.EC_GROUP, point &C.EC_POINT, form i32, pbuf &&u8, ctx &C.BN_CTX) uint
fn C.EC_POINT_free(point &C.EC_POINT)
// Elliptic group (curve) related declarations.
@@ -205,7 +205,7 @@ struct C.OSSL_PARAM_BLD {}
fn C.OSSL_PARAM_free(params &C.OSSL_PARAM)
fn C.OSSL_PARAM_BLD_free(param_bld &C.OSSL_PARAM_BLD)
fn C.OSSL_PARAM_BLD_new() &C.OSSL_PARAM_BLD
fn C.OSSL_PARAM_BLD_push_utf8_string(bld &C.OSSL_PARAM_BLD, const_key &char, const_buf &char, bsize usize) i32
fn C.OSSL_PARAM_BLD_push_utf8_string(bld &C.OSSL_PARAM_BLD, const_key &char, const_buf &char, bsize uint) i32
fn C.OSSL_PARAM_BLD_push_BN(bld &C.OSSL_PARAM_BLD, const_key &char, const_bn &C.BIGNUM) i32
fn C.OSSL_PARAM_BLD_push_octet_string(bld &C.OSSL_PARAM_BLD, const_key &char, const_buf voidptr, bsize usize) i32
fn C.OSSL_PARAM_BLD_push_octet_string(bld &C.OSSL_PARAM_BLD, const_key &char, const_buf voidptr, bsize uint) i32
fn C.OSSL_PARAM_BLD_to_param(bld &C.OSSL_PARAM_BLD) &C.OSSL_PARAM
+4 -4
View File
@@ -307,7 +307,7 @@ pub fn (pv PrivateKey) derive_shared_secret(peer PublicKey) ![]u8 {
return error('EVP_PKEY_derive_set_peer failed (mismatched curve or invalid peer key?)')
}
// First call with a nil buffer to learn the required secret length.
mut secret_len := usize(0)
mut secret_len := uint(0)
dlen := C.EVP_PKEY_derive(ctx, unsafe { nil }, &secret_len)
if dlen <= 0 || secret_len == 0 {
C.EVP_PKEY_CTX_free(ctx)
@@ -393,7 +393,7 @@ pub fn PublicKey.from_uncompressed_bytes(bytes []u8, opt CurveOptions) !PublicKe
return error('OSSL_PARAM_BLD_new failed')
}
n := C.OSSL_PARAM_BLD_push_utf8_string(param_bld, c'group', voidptr(opt.nid.str().str), 0)
o := C.OSSL_PARAM_BLD_push_octet_string(param_bld, c'pub', bytes.data, usize(bytes.len))
o := C.OSSL_PARAM_BLD_push_octet_string(param_bld, c'pub', bytes.data, uint(bytes.len))
if n <= 0 || o <= 0 {
C.OSSL_PARAM_BLD_free(param_bld)
return error('OSSL_PARAM_BLD_push failed')
@@ -481,7 +481,7 @@ fn sign_digest(key &C.EVP_PKEY, digest []u8) ![]u8 {
}
// siglen was used to store the size of the signature output. When EVP_PKEY_sign
// was called with NULL signature buffer, siglen will tell maximum size of signature.
siglen := usize(C.EVP_PKEY_size(key))
siglen := uint(C.EVP_PKEY_size(key))
sig := []u8{len: int(siglen)}
// calls directly with sign
@@ -604,7 +604,7 @@ fn evpkey_from_seed(seed []u8, opt CurveOptions) !&C.EVP_PKEY {
// push the group, private and public key bytes infos into the builder
n := C.OSSL_PARAM_BLD_push_utf8_string(param_bld, c'group', voidptr(opt.nid.str().str), 0)
m := C.OSSL_PARAM_BLD_push_BN(param_bld, c'priv', bn)
o := C.OSSL_PARAM_BLD_push_octet_string(param_bld, c'pub', pub_bytes.data, usize(pub_bytes.len))
o := C.OSSL_PARAM_BLD_push_octet_string(param_bld, c'pub', pub_bytes.data, uint(pub_bytes.len))
if n <= 0 || m <= 0 || o <= 0 {
C.EC_POINT_free(point)
C.BN_free(bn)
+12 -12
View File
@@ -356,7 +356,7 @@ fn C.mbedtls_ecdsa_init(ctx &C.mbedtls_ecdsa_context)
fn C.mbedtls_ecdsa_free(ctx &C.mbedtls_ecdsa_context)
fn C.mbedtls_ecdsa_genkey(ctx &C.mbedtls_ecdsa_context, gid int, f_rng fn (voidptr, &u8, usize) int, p_rng voidptr) int
fn C.mbedtls_ecdsa_genkey(ctx &C.mbedtls_ecdsa_context, gid int, f_rng fn (voidptr, &u8, uint) int, p_rng voidptr) int
// mbedtls_ecdsa_write_signature/read_signature operate on a whole context
// (not bare grp/d/Q like the lower-level mbedtls_ecdsa_sign/verify) and
@@ -373,9 +373,9 @@ fn C.mbedtls_ecdsa_genkey(ctx &C.mbedtls_ecdsa_context, gid int, f_rng fn (voidp
// fails -- which it always does for MBEDTLS_MD_NONE (0), since md.c's own
// switch has no case for it. PrivateKey.sign() (ecdsa_notd_use_openssl.v)
// relies on this: it never calls write_signature with md_alg 0.
fn C.mbedtls_ecdsa_write_signature(ctx &C.mbedtls_ecdsa_context, md_alg int, hash &u8, hlen usize, sig &u8, sig_size usize, slen &usize, f_rng fn (voidptr, &u8, usize) int, p_rng voidptr) int
fn C.mbedtls_ecdsa_write_signature(ctx &C.mbedtls_ecdsa_context, md_alg int, hash &u8, hlen uint, sig &u8, sig_size uint, slen &uint, f_rng fn (voidptr, &u8, uint) int, p_rng voidptr) int
fn C.mbedtls_ecdsa_read_signature(ctx &C.mbedtls_ecdsa_context, hash &u8, hlen usize, sig &u8, slen usize) int
fn C.mbedtls_ecdsa_read_signature(ctx &C.mbedtls_ecdsa_context, hash &u8, hlen uint, sig &u8, slen uint) int
fn C.mbedtls_ecp_group_init(grp &C.mbedtls_ecp_group)
@@ -387,9 +387,9 @@ fn C.mbedtls_ecp_point_init(pt &C.mbedtls_ecp_point)
fn C.mbedtls_ecp_point_free(pt &C.mbedtls_ecp_point)
fn C.mbedtls_ecp_point_write_binary(grp &C.mbedtls_ecp_group, pt &C.mbedtls_ecp_point, format int, olen &usize, buf &u8, buflen usize) int
fn C.mbedtls_ecp_point_write_binary(grp &C.mbedtls_ecp_group, pt &C.mbedtls_ecp_point, format int, olen &uint, buf &u8, buflen uint) int
fn C.mbedtls_ecp_point_read_binary(grp &C.mbedtls_ecp_group, pt &C.mbedtls_ecp_point, buf &u8, ilen usize) int
fn C.mbedtls_ecp_point_read_binary(grp &C.mbedtls_ecp_group, pt &C.mbedtls_ecp_point, buf &u8, ilen uint) int
fn C.mbedtls_ecp_point_cmp(p &C.mbedtls_ecp_point, q &C.mbedtls_ecp_point) int
@@ -412,18 +412,18 @@ fn C.mbedtls_ecp_set_public_key(grp_id int, key &C.mbedtls_ecdsa_context, q &C.m
// the big-endian private scalar `d`, then rejects it via
// mbedtls_ecp_check_privkey unless it lies in `[1, curve_order-1]`. It does
// NOT compute the public point -- call mbedtls_ecp_keypair_calc_public next.
fn C.mbedtls_ecp_read_key(grp_id int, key &C.mbedtls_ecdsa_context, buf &u8, buflen usize) int
fn C.mbedtls_ecp_read_key(grp_id int, key &C.mbedtls_ecdsa_context, buf &u8, buflen uint) int
// mbedtls_ecp_keypair_calc_public computes and stores `Q = d * G` for a
// keypair whose group and private scalar are already set. `f_rng` is
// required (used for scalar-multiplication blinding, not for the key itself).
fn C.mbedtls_ecp_keypair_calc_public(key &C.mbedtls_ecdsa_context, f_rng fn (voidptr, &u8, usize) int, p_rng voidptr) int
fn C.mbedtls_ecp_keypair_calc_public(key &C.mbedtls_ecdsa_context, f_rng fn (voidptr, &u8, uint) int, p_rng voidptr) int
fn C.mbedtls_mpi_init(x &C.mbedtls_mpi)
fn C.mbedtls_mpi_free(x &C.mbedtls_mpi)
fn C.mbedtls_mpi_write_binary(x &C.mbedtls_mpi, buf &u8, buflen usize) int
fn C.mbedtls_mpi_write_binary(x &C.mbedtls_mpi, buf &u8, buflen uint) int
fn C.mbedtls_mpi_cmp_mpi(x &C.mbedtls_mpi, y &C.mbedtls_mpi) int
@@ -432,18 +432,18 @@ fn C.mbedtls_mpi_cmp_mpi(x &C.mbedtls_mpi, y &C.mbedtls_mpi) int
// directly from bare grp/d/Q -- the lower-level API, not the stateful
// mbedtls_ecdh_context one, since this module never needs to hold ECDH
// state across calls the way a TLS handshake would.
fn C.mbedtls_ecdh_compute_shared(grp &C.mbedtls_ecp_group, z &C.mbedtls_mpi, q &C.mbedtls_ecp_point, d &C.mbedtls_mpi, f_rng fn (voidptr, &u8, usize) int, p_rng voidptr) int
fn C.mbedtls_ecdh_compute_shared(grp &C.mbedtls_ecp_group, z &C.mbedtls_mpi, q &C.mbedtls_ecp_point, d &C.mbedtls_mpi, f_rng fn (voidptr, &u8, uint) int, p_rng voidptr) int
fn C.mbedtls_ctr_drbg_init(ctx &C.mbedtls_ctr_drbg_context)
fn C.mbedtls_ctr_drbg_free(ctx &C.mbedtls_ctr_drbg_context)
fn C.mbedtls_ctr_drbg_seed(ctx &C.mbedtls_ctr_drbg_context, f_entropy fn (voidptr, &u8, usize) int, p_entropy voidptr, custom &u8, len usize) int
fn C.mbedtls_ctr_drbg_seed(ctx &C.mbedtls_ctr_drbg_context, f_entropy fn (voidptr, &u8, uint) int, p_entropy voidptr, custom &u8, len uint) int
fn C.mbedtls_ctr_drbg_random(p_rng voidptr, output &u8, output_len usize) int
fn C.mbedtls_ctr_drbg_random(p_rng voidptr, output &u8, output_len uint) int
fn C.mbedtls_entropy_init(ctx &C.mbedtls_entropy_context)
fn C.mbedtls_entropy_free(ctx &C.mbedtls_entropy_context)
fn C.mbedtls_entropy_func(data voidptr, output &u8, len usize) int
fn C.mbedtls_entropy_func(data voidptr, output &u8, len uint) int
+9 -9
View File
@@ -165,7 +165,7 @@ pub fn new_key_from_seed(seed []u8, opt CurveOptions) !PrivateKey {
// read_key loads the group and the private scalar (range-checked), but
// leaves the public point unset -- calc_public derives Q = d * G, which
// sign()/public_key()/derive_shared_secret() all need present in the ctx.
rret := C.mbedtls_ecp_read_key(opt.nid.mbedtls_group_id(), ctx, seed.data, usize(seed.len))
rret := C.mbedtls_ecp_read_key(opt.nid.mbedtls_group_id(), ctx, seed.data, uint(seed.len))
if rret != 0 {
C.mbedtls_ecdsa_free(ctx)
return error_with_code('crypto.ecdsa: mbedtls_ecp_read_key failed (seed is not a valid private scalar for the curve?)', rret)
@@ -280,7 +280,7 @@ pub fn (pv PrivateKey) bytes() ![]u8 {
}
size := if pv.ks_flag == .flexible { pv.ks_size } else { pv.nid.byte_size() }
mut buf := []u8{len: size}
wret := C.mbedtls_mpi_write_binary(&d, buf.data, usize(size))
wret := C.mbedtls_mpi_write_binary(&d, buf.data, uint(size))
if wret != 0 {
return error_with_code('crypto.ecdsa: mbedtls_mpi_write_binary failed', wret)
}
@@ -365,7 +365,7 @@ pub fn (pv PrivateKey) derive_shared_secret(peer PublicKey) ![]u8 {
}
size := pv.nid.byte_size()
mut secret := []u8{len: size}
wret := C.mbedtls_mpi_write_binary(&z, secret.data, usize(size))
wret := C.mbedtls_mpi_write_binary(&z, secret.data, uint(size))
if wret != 0 {
return error_with_code('crypto.ecdsa: mbedtls_mpi_write_binary failed', wret)
}
@@ -417,7 +417,7 @@ pub fn (pb PublicKey) verify(message []u8, sig []u8, opt SignerOpts) !bool {
// write_signature/sign) -- it verifies against whatever digest bytes are
// given, algorithm-agnostic.
_, digest := calc_digest(pb.nid, message, opt)!
ret := C.mbedtls_ecdsa_read_signature(pb.ctx, digest.data, usize(digest.len), sig.data, usize(sig.len))
ret := C.mbedtls_ecdsa_read_signature(pb.ctx, digest.data, uint(digest.len), sig.data, uint(sig.len))
return ret == 0
}
@@ -465,8 +465,8 @@ pub fn (pb PublicKey) uncompressed_bytes() ![]u8 {
return error_with_code('crypto.ecdsa: mbedtls_ecp_export failed', eret)
}
mut buf := []u8{len: int(C.MBEDTLS_ECP_MAX_PT_LEN)}
mut olen := usize(0)
wret := C.mbedtls_ecp_point_write_binary(&grp, &q, C.MBEDTLS_ECP_PF_UNCOMPRESSED, &olen, buf.data, usize(buf.len))
mut olen := uint(0)
wret := C.mbedtls_ecp_point_write_binary(&grp, &q, C.MBEDTLS_ECP_PF_UNCOMPRESSED, &olen, buf.data, uint(buf.len))
if wret != 0 {
return error_with_code('crypto.ecdsa: mbedtls_ecp_point_write_binary failed', wret)
}
@@ -499,7 +499,7 @@ pub fn PublicKey.from_uncompressed_bytes(bytes []u8, opt CurveOptions) !PublicKe
defer {
C.mbedtls_ecp_point_free(&q)
}
rret := C.mbedtls_ecp_point_read_binary(&grp, &q, bytes.data, usize(bytes.len))
rret := C.mbedtls_ecp_point_read_binary(&grp, &q, bytes.data, uint(bytes.len))
if rret != 0 {
return error_with_code('crypto.ecdsa: mbedtls_ecp_point_read_binary failed', rret)
}
@@ -616,8 +616,8 @@ fn sign_digest(ctx &C.mbedtls_ecdsa_context, md_alg int, digest []u8) ![]u8 {
free_rng(mut ctr_drbg, mut entropy)
}
mut sig := []u8{len: int(C.MBEDTLS_ECDSA_MAX_LEN)}
mut slen := usize(0)
ret := C.mbedtls_ecdsa_write_signature(ctx, md_alg, digest.data, usize(digest.len), sig.data, usize(sig.len), &slen, C.mbedtls_ctr_drbg_random, voidptr(&ctr_drbg))
mut slen := uint(0)
ret := C.mbedtls_ecdsa_write_signature(ctx, md_alg, digest.data, uint(digest.len), sig.data, uint(sig.len), &slen, C.mbedtls_ctr_drbg_random, voidptr(&ctr_drbg))
if ret != 0 {
return error_with_code('crypto.ecdsa: mbedtls_ecdsa_write_signature failed', ret)
}
@@ -6,11 +6,11 @@ fn test_entropy_callback_preserves_integer_result() {
defer { C.mbedtls_entropy_free(&entropy) }
mut output := [32]u8{}
callback := C.mbedtls_entropy_func
status := callback(voidptr(&entropy), &output[0], usize(output.len))
status := callback(voidptr(&entropy), &output[0], uint(output.len))
assert status == 0
}
fn reject_entropy(_ voidptr, _ &u8, _ usize) int {
fn reject_entropy(_ voidptr, _ &u8, _ uint) int {
return -1
}
+1 -1
View File
@@ -235,7 +235,7 @@ const default_groupname_size = 25 // short name commonly only take 10-15 length
// key_group_name returns underlying group name of the key as a string.
fn key_group_name(key &C.EVP_PKEY) !string {
gname := []u8{len: default_groupname_size}
gname_len := usize(0)
gname_len := uint(0)
mut s := C.EVP_PKEY_get_group_name(key, gname.data, u32(gname.len), &gname_len)
if s == 0 {
unsafe { gname.free() }
+1 -1
View File
@@ -5,7 +5,7 @@ module internal
#include <sys/random.h>
fn C.getentropy(buf voidptr, buflen usize) i32
fn C.getentropy(buf voidptr, buflen uint) i32
const read_batch_size = 256
Loaded 100 of 521 files, more files were not shown because too many files have changed in this diff. Show more