223 Commits

Author SHA1 Message Date
Andrew Kelley
0794e48b91 update a couple more callsites to @memset 2023-04-28 13:24:43 -07:00
Andrew Kelley
6261c13731 update codebase to use @memset and @memcpy 2023-04-28 13:24:43 -07:00
zooster
bc8e1e1de4
Improvements to docs and text
* docs(std.math): elaborate on difference between absCast and absInt

* docs(std.rand.Random.weightedIndex): elaborate on likelihood

I think this makes it easier to understand.

* langref: add small reminder

* docs(std.fs.path.extension): brevity

* docs(std.bit_set.StaticBitSet): mention the specific types

* std.debug.TTY: explain what purpose this struct serves

This should also make it clearer that this struct is not supposed to provide unrelated terminal manipulation functionality such as setting the cursor position or something because terminals are complicated and we should keep this struct simple and focused on debugging.

* langref(package listing): brevity

* langref: explain what exactly `threadlocal` causes to happen

* std.array_list: link between swapRemove and orderedRemove

Maybe this can serve as a TLDR and make it easier to decide.

* PrefetchOptions.locality: clarify docs that this is a range

This confused me previously and I thought I can only use either 0 or 3.

* fix typos and more

* std.builtin.CallingConvention: document some CCs

* langref: explain possibly cryptic names

I think it helps knowing what exactly these acronyms (@clz and @ctz) and
abbreviations (@popCount) mean.

* variadic function error: add missing preposition

* std.fmt.format docs: nicely hyphenate

* help menu: say what to optimize for

I think this is slightly more specific than just calling it
"optimizations". These are speed optimizations. I used the word
"performance" here.
2023-04-23 21:06:21 +03:00
Jacob Young
bf6fd9ae3f cbe: enable CI for std tests 2023-04-21 16:36:10 -04:00
mlugg
77fdd76c16 std: fix uses of comptime blocks in non-inline functions
ccf670c made using `return` from within a comptime block in a non-inline
function illegal, since it is a use of runtime control flow in a
comptime block. It is allowed if the function in question is `inline`,
since no actual control flow occurs in this case. A few functions from
std (notably `std.fmt.comptimePrint`) needed to be marked `inline` to
support this change.
2023-04-18 19:51:18 -07:00
Carl Åstholm
3cd72951c0 std.mem.reverseIterator: add nextPtr() 2023-03-31 22:50:31 +02:00
Carl Åstholm
0bbc1ec206 std.mem.reverseIterator: accept pointer to array 2023-03-31 22:48:32 +02:00
Andrew Kelley
4db5bc7b21 std.mem.copy: update to new for loop syntax 2023-03-15 10:48:12 -07:00
Frank Denis
6214f66dc1 trim(Left|Right): clarify that values_to_strip is a set
The parameter could be confused with a prefix or suffix, instead
of a set of values.
2023-02-20 13:55:45 -05:00
Andrew Kelley
aeaef8c0ff update std lib and compiler sources to new for loop syntax 2023-02-18 19:17:21 -07:00
Isaac Freund
23b7d28896 std: restrict mem.span() and mem.len() to sentinel terminated pointers
These functions are currently footgunny when working with pointers to
arrays and slices. They just return the stated length of the array/slice
without iterating and looking for the first sentinel, even if the
array/slice is a sentinel terminated type.

From looking at the quite small list of places in the standard
library/compiler that this change breaks existing code, the new code
looks to be more readable in all cases.

The usage of std.mem.span/len was totally unneeded in most of the cases
affected by this breaking change.

We could remove these functions entirely in favor of other existing
functions in std.mem such as std.mem.sliceTo(), but that would be a
somewhat nasty breaking change as std.mem.span() is very widely used for
converting sentinel terminated pointers to slices. It is however not at
all widely used for anything else.

Therefore I think it is better to break these few non-standard and
potentially incorrect usages of these functions now and at some later
time, if deemed worthwhile, finally remove these functions.

If we wait for at least a full release cycle so that everyone adapts to
this change first, updating for the removal could be a simple find and
replace without needing to worry about the semantics.
2023-01-29 15:07:06 -05:00
Michael Bartnett
31a2b8c364
std: Handle field struct defaults in std.mem.zeroInit
I originally started monkeying with this because std.mem.zeroes doesn't support sentinel-terminated const slices even with defaults in 0.10.x.

I see that std.mem.zeroes was modified in #13256 to allow setting these slices to "".

That got me partway to where I wanted, but there was still an issue fields whose types are structs, they wouldn't get their defaults.

So when iterating struct fields looking for default values, when there is no default value and the type is .Struct, it will delegate to a call to zeroInit.

* Initialize struct fields in zeroInit exactly once

In my changes, similar to the previous implementation, the priority order for fields being initialized is:

1. If the `init` argument is a tuple, the nth element corresponding to the nth field of the struct.
2. Otherwise, if the `init` argument is not a tuple, try to find a matching field name on `init` and use that field.
3. Is the field has a default value, initalize with that value.
4. Fall back to what the field would have been initialized to via a recursive call to `std.mem.zeroInit`.

But instead of initializing a default instance of the struct and then running multiple passes over it, the init method is chosen per-field and each field is initialized exactly once.
2023-01-16 14:24:47 +02:00
kcbanner
9a77743cc7 cbe: add doNotOptimizeAwayC to handle not having __asm support in msvc 2023-01-01 16:44:28 -05:00
Veikka Tuominen
622311fb9a update uses of overflow arithmetic builtins 2022-12-27 15:13:14 +02:00
Jacob Young
52e5c66025 llvm: fix use of invalid alignment
* Initialize `big_align` with 1 as 0 is not a valid alignment.
 * Add an assert to `alignForwardGeneric` to catch this issue earlier.
 * Refactor valid alignment checks to call a more descriptive function.
2022-12-18 22:11:26 -05:00
r00ster91
aac2d6b56f std.builtin: rename Type.UnionField and Type.StructField's field_type to type 2022-12-17 14:11:33 +01:00
Jonathan Marler
5d3adc568c add std.mem.reverseIterator 2022-12-13 15:13:25 -05:00
Ronald Chen
959c10c5e5 std: added std.mem.window 2022-12-12 07:07:56 +02:00
Veikka Tuominen
9d93b2ccf1 Eliminate BoundFn type from the language
Closes #9484
2022-12-09 20:37:18 -07:00
Frank Denis
c49e4d534f
Improve and remove duplicate doNotOptimizeAway() implementations (#13790)
* Improve and remove duplicate doNotOptimizeAway() implementations

We currently have two doNotOptimizeAway() implementations, one in
std.math and the other one in std.mem.

Maybe we should deprecate one. In the meantime, the std.math one
now just calls the std.mem one.

In a comptime environment, just ignore the value. Previously,
std.mem.doNotOptimizeAway() did not work at comptime.

If the value fits in a CPU register, just tell the compiler we
need that value to be computed, without clobbering anything else.

Only clobber all possibly escaped memory on pointers or large arrays.

Add tests by the way since we didn't had any (we had, but only
indirect ones).
2022-12-09 18:22:50 +01:00
Andrew Kelley
50eb7983cd remove most conditional compilation based on stage1
There are still a few occurrences of "stage1" in the standard library
and self-hosted compiler source, however, these instances need a bit
more careful inspection to ensure no breakage.
2022-12-06 20:38:54 -07:00
Andrew Kelley
ceb0a632cf std.mem.Allocator: allow shrink to fail
closes #13535
2022-11-29 23:30:38 -07:00
IntegratedQuantum
d1e7be0bd1
Handle sentinel slices in std.mem.zeroes
Fixes #13256
2022-11-09 17:33:48 +02:00
delitako
c8a5ad6d9d
Improve doc comments for two functions (#13456)
* std.heap: fix function name in doc comment

* std.mem: document return value of `replace`
2022-11-05 22:55:50 +01:00
Andrew Kelley
3f3003097c std.heap.PageAllocator: add check for large allocation
Instead of making the memory alignment functions more complicated, I
added more API documentation for their existing semantics.

closes #12118
closes #12135
2022-10-30 16:10:20 -07:00
Andrew Kelley
c36eb4ede9
Merge pull request #13221 from topolarity/packed-mem
Introduce `std.mem.readPackedInt` and improve bitcasting of packed memory layouts
2022-10-28 21:15:16 -04:00
Zhora Trush
c66d3f6bf6 Enhance indexOfIgnoreCase with Boyer-Moore-Horspool algorithm 2022-10-28 20:29:41 -04:00
Cody Tapscott
03ed0a59e3 std.mem: Skip read/writePackedInt test on WASM32/64 2022-10-28 08:41:04 -07:00
Cody Tapscott
c639c22544 std.mem: Add readPackedInt, writePackedInt, etc.
These utility functions allow reading from (stage2) packed memory at
runtime-known offsets.
2022-10-28 08:41:04 -07:00
Veikka Tuominen
541b3e3a31 Sema: check pointer qualifiers before implicit cast
Closes #12881
2022-09-20 00:50:13 +03:00
Andrew Kelley
d3d24874c9 std: remove deprecated API for the upcoming release
See #3811
2022-09-16 14:46:53 -04:00
Jonas Gollenz
07afd5bdba docs: remove confusion about align[For|Back]ward 2022-08-24 17:18:29 -04:00
Veikka Tuominen
62ff8871ed stage2+stage1: remove type parameter from bit builtins
Closes #12529
Closes #12511
Closes #6835
2022-08-22 11:19:20 +03:00
N00byEdge
18440cb239
std.mem.zeroes: Zero sized structs with uninitialized members (#12246)
`std.mem.zeroes(struct{handle: void})` Failed with the following error before:
```
/nix/store/l6v4359wc9xrxxmvvp3rynsb5s3d78xf-zig-0.9.1/lib/zig/std/mem.zig:270:42: error: missing field: 'handle'
            if (@sizeOf(T) == 0) return T{};
                                         ^
```
2022-08-05 15:47:52 +03:00
r00ster
1a16b7214d
std.mem: add reset to SplitBackwardsIterator and SplitIterator 2022-07-26 14:26:46 +03:00
r00ster
cff5d9c805
std.mem: add first method to SplitIterator and SplitBackwardsIterator 2022-07-25 22:04:30 +03:00
Andrew Kelley
6ab5219e34 std: update test cases to reflect new packed struct semantics 2022-07-12 18:38:11 -07:00
Andrew Kelley
cbdd21cd9a std: disable tests regressed from LLVM 14 2022-07-03 15:39:39 -07:00
Motiejus Jakštys
4a6b70fbd1
mem: add splitBackwards (#11908)
* mem: refactor tests of split()

- add a few cases for .rest()
- use expectEqualSlices()

* mem: add splitBackwards

Over the last couple of weeks weeks I needed to iterate over a
collection backwards at least twice. Do we want to have this in stdlib?
If yes, click "Merge" and start using today! Free shipping and returns
(before 1.0).

Why is this useful?
-------------------

I need this for building an error wrapper: errors are added in the
wrapper from "lowest" level to "highest" level, and then printed in
reverse order. Imagine `UpdateUsers` call, which needs to return
`error.InvalidInput` and a wrappable error context. In Go we would add a
context to the error when returning it:

    // if update_user fails, add context on which user we are operating
    if err := update_user(user); err != nil {
        return fmt.Errorf("user id=%d: %w", user.id, err)
    }

Since Zig cannot pass anything else than u16 with an error (#2647), I
will pass a `err_ctx: *Err`, to the callers, where they can, besides
returning an error, augment it with auxiliary data. `Err` is a
preallocated array that can add zero-byte-separated strings. For a
concrete example, imagine such a call graph:

    update_user(User, *Err) error{InvalidInput}!<...>
      validate_user([]const u8, *Err) error{InvalidInput}!<...>

Where `validate_user` would like, besides only the error, signal the
invalid field. And `update_user`, besides the error, would signal the
offending user id.

We also don't want the low-level functions to know in which context they
are operating to construct a meaningful error message: if validation
fails, they append their "context" to the buffer. To translate/augment
the Go example above:

    pub fn validate_user(err_ctx: *Err, user: User) error{InvalidInput}!void {
        const name = user.name;
        if (!ascii.isAlpha(name)) {
            err_ctx.print("name '{s}' must be ascii-letters only", .{name});
            return error.InvalidInput;
        }
        <...>
    }

    // update_user validates each user and does something with it.
    pub fn update_user(err_ctx: *Err, user: User) error{InvalidInput}!void {
        // validate the user before updating it
        validate_user(user) catch {
            err_ctx.print("user id={d}", .{user.id});
            return error.InvalidInput;
        };
        <...>
    }

Then the top-level function (in my case, CLI) will read the buffer
backwards (splitting on `"\x00"`) and print:

    user id=123: name 'Žvangalas' must be ascii-letters only

To read that buffer backwards, dear readers of this commit message, I
need `mem.splitBackwards`.
2022-06-29 08:23:09 +02:00
Ben Fiedler
76546b3f8e std.mem: add peek() to TokenIterator(T) 2022-06-28 21:45:02 +02:00
Veikka Tuominen
8f9b31af92 value: handle slices in canMutateComptimeVarState 2022-06-18 20:04:49 +03:00
Andrew Kelley
ffa700ee58
Merge pull request #11837 from Vexu/stage2
Fix (nearly) all stage2 crashes when testing stdlib
2022-06-12 17:45:57 -04:00
Andrew Kelley
85492f2b91 std.mem.zeroes: remove call to std.meta
everybody is so horny for std.meta
2022-06-12 00:56:59 -07:00
Veikka Tuominen
6b36774adc std: disable failing tests, add zig2 build test-std to CI 2022-06-12 10:43:28 +03:00
Koakuma
fb0692334e target: Rename sparcv9 -> sparc64
Rename all references of sparcv9 to sparc64, to make Zig align more with
other projects. Also, added new function to convert glibc arch name to Zig
arch name, since it refers to the architecture as sparcv9.

This is based on the suggestion by @kubkon in PR 11847.
(https://github.com/ziglang/zig/pull/11487#pullrequestreview-963761757)
2022-05-13 16:43:59 -04:00
Yusuf Bham
41654a318d std.mem: add concatWithSentinel 2022-04-21 14:39:41 -04:00
ominitay
25d4c5df70
std.mem.zeroInit: Fix behaviour with empty initialiser 2022-03-28 14:10:36 +03:00
Andrew Kelley
fd85cfe154 std.mem: remove redundant namespaces in test names
related: #7923
2022-03-09 15:44:08 -07:00
Jonathan Marler
d805adddd6 deprecated TypeInfo in favor of Type
Co-authored-by: Veikka Tuominen <git@vexu.eu>
2022-03-08 20:38:12 +02:00
Evan Haas
e382e7be2b std: Allow mem.zeroes to work at comptime with extern union
Fixes #10797
2022-02-07 11:34:20 +02:00