What Should We _Remove_ from Zig?

That’s a very convoluted way to express a simple requiremente: I want the bytes without an additional terminator.

Rust handles the distinction between those two types quite well one for ordinary string literals and another for C literals; I think Zig should benefit from a similar way and offer more control and explicitness in that regard, rather than storing an extra byte “just in case.”

const text = "test";

“test” has type *const [N:0]u8, which is a literal backed by four content bytes + a traling zero

I know we can quit that terminator using an array conversion or a comptime helper, etc.
But requesting a N bytes backing array should be similarly and so easy, concise and explicit.

The saving can be small for just one literal, but it can accumulate with many literals and matter in memory-constrained programs. Making this choice easier would fit Zig’s philosophy on explicitness and control over memory representation.

I can understand the convenience for C interoperability however i dont think that matter should dictate the default representation of Zig’s literals and in some aspects of the language. I would prefer ordinary literals without an implicit terminator with simple explicit way to construct a version with terminator when an interface requires one.

For literals knwon at compile time, this choice could be resolved during compilation.
Also interfaces requiring only a pointer and a length would not need additional terminator in the literal’s underlying storage.

This doesn’t make sense to me. The savings are O(N), where N is (more or less) the number of string literals present in your source code. Moreover, unless I’m wildly mistaken, the place where you are saving memory is in the binary of your program, where the combination “I have a lot of string literals” and “I am memory constrained” seems vanishingly unlikely to be correctly solved by “I will shave one byte off of my string literals” rather than “I will rewrite my program so as to put fewer string literals into my binary”.

3 Likes

Even more so with string literal deduplication. Now it’s “I will rewrite my program to put fewer unique string literals into my binary”

3 Likes

There’s sometimes when you cant do that. Programming covers many uses cases today.
Think about embedded systems or firmware, where the binary has to fit on a fixed flash budget.
In that context, saving space in the binary is useful, even if it doesnt reduce RAM usage.

“Use fewer literals” is not always equivalent. Strings can be required for command names, protocol identifiers, user facing messages, menu labels, diagnostic messages… removing those can remove functionality omiting unused terminators may preserves their contents.

For example if the firmware were 100 bytes over the budget maybe saving 200 bytes could matter, and the actual saving would need to be checked in the compiled output.

The idea is that even minimal savings can be significant when memory is limited.
Although Zig already allows for the creation of arrays without a terminating character, Im arguing that requesting that representation should be more straightforward.

I just think that i see this as a design trade-off worth improving: making unnecessary storage easier to avoid would align with Zig’s emphasis on explicitness and control over memory.

Girl, use less AI when you write your replies, please.

In such a situation, the best thing to do is clearly to create one (1) string literal in your binary by concatenating all the string literals in your source code and rewriting your source code to use slices of that literal. It’s technically suboptimal because you will still have one (1) null terminator.

4 Likes

I mostly write code for microcontrollers, so I can truly claim I write “memory constrained” programs. I have had to play the game of hunt-the-byte a few times to get things to run.

When I hear “memory constrained” I always want to ask “what type of memory is constrained?”.

Consider, for example, an ESP32-S3 chip, which is a fairly powerful IoT microcontroller: dual-core 240 MHZ CPU, 512KB of on-chip SRAM that serves as general-purpose memory. Sounds like a lot, until you find out WiFi / LWIP alone uses up half of it.

There is a problem, though: SRAM doesn’t retain it’s data when the chip is powered off, and having to re-program your IoT device every time it’s unplugged gets old after a while. To fix this, we wire up a NAND flash chip, and save the .text section (code and constant data, including string literals) onto it instead. These chips range from 4MB-16MB in size.

Then, when the chip powers on, the bootloader loads all the code from flash into SRAM before running it…

What if instead, we load only the most-commonly used code, then load the rest of the code and constant data through a small cache of SRAM as-and-when we need it? That leaves us with more SRAM to use on fun things like variables and DMA buffers.

As a result, when it’s time to go hunting for bytes, I don’t bother with static strings. It’s not because they don’t use a lot of memory (they do!) but because the type of memory they use - flash ROM - is not the one I care about. I’ve got enough flash memory to store my program three times over (and I usually do - it makes over-the-air updates simpler). The memory I run out of is SRAM, of which constant strings occupy precisely 0 bytes of.

P.S. this is one situation in which C strings have a slight advantage over slices - they can be stored in a single register or word, instead of two. They use slightly less stack memory as a result, which is well worth the extra null byte.

3 Likes

That’s actually a really good idea, but yeah im just going down the rabbit hole of the most optimal way. Seeing how far we can go reducing unnecesary storage and what the trade-offs would be. I dont speak native english sorry if its very google translator or whatever.

1 Like

Better yet, take it to its logical extreme and merge strings that have a common prefix & suffix.*

It sounds silly, but if (hypothetically) you’re desperate enough to scrape individual bytes off strings…

*I think it’s an NP-hard problem (to calculate the most efficient merge). But it wouldn’t be hard to brute-force, when the total size is so small.

1 Like

I mean, in a way, Zig already has a builtin for assertion, unreachable. Isn’t that what std.debug.assert already uses? I’ve always thought of it as a thin wrapper. It’s not much of a static analyzer if it can’t reason about a function call imho. You could even make assert an inlined function, so the IR would be inlined.

yeah there might be better solutions, I’d just think that it might be a good idea, plus I wonder if it would help with some hardware that have dedicated instructions for signing pointers, or variables, or to protect some parts of the code. Having said that assert is good enough, but I’m pretty sure it would be better as a builtin, for the convenience, to encourage good practice, and because it’s easy to see.

I think discussions about assert can be continued in one of those topics, I don’t want endless re-iteration of previous discussions:

4 Likes

https://codeberg.org/ziglang/zig/issues/36520

1 Like

Agreed. I enjoy try because it makes it easy to clearly specify exact positions in the code that can raise an error. It’s easy to just do a quick search for all lines starting with try and have those exact locations. Anything that needs to be handled can be explicitly expanded with catch and unpacked either unconditionally for any error or using switch on the error type for different behaviors.

I also like more of the strictness of the language and specifically the explicitness of the language. It is part of the language zen to be explicit, so removing implicit type coercions would be something I’m in favor of. Although paradoxically I guess I am in favor of the global error set and not necessarily forcing all functions calls to specify the exact list of errors, that would be too much to maintain. There are also places in the code that may say they don’t fail but they actually do. Zig can only protect you from the information it knows, not what it doesn’t know. In the latter case (like if a specific invariant is violated), the application would just crash. Of course you’ll probably end up manually adding some sort of error handling to guard yourself against that situation if it ever happens, but that would mostly just come through actual usage and experience rather than foresight.

Overall Zig is still continuing to go in the right direction, I’ve been using it since 0.11 :). Lastly, I do still support doing a massive library renaming from camelCase to snake case (I supported that initiative back when we had the github issue about it). Although if we decide to go camelCase completely, I’m fine with that as well. At the moment it seems that the naming conventions are not necessarily consistent throughout the library. There are also a lot of functions that are not really self documenting or easily readable. The whole “allocPrint” “allocPrintZ” situation comes to mind. I’ve gotten used to it and know what they do but it was a journey to get to that point of understanding where things are located in the stdlib, and why we have a difference. I suppose the lack of polymorphic functions that can overload based on different arguments types accounts for this, but I’m fine with not having polymorphism in that way as long as the names are more readable.

1 Like

I’ve been using ensureUnusedCapacity() and appendAssumeCapacity() a lot to do reserve-first programming, but I still feel it’s hard for me to move away from ArrayList, because the valid data length is just as important as the capacity, and it’s useful for error handling safety. Even though the capacity is decided from the start, ArrayList keeps track of what’s valid while it’s being built, so it can correctly handle state rollback with errdefer.

6 Likes

Error set member access is misleading because FooSet.Error == BarSet.Error. It is also another way to write error.Error, there is no One Obvious Way To Do Things. It should thus be removed.

5 Likes

Huh, TIL. It makes sense, I suppose.

One nice thing lost if error set member access is removed is “namespaced” errors. This is useful for tools such as ZLS to autocomplete error values (e.g. std.Io.File.Writer.Error.AccessDenied). This is useful when switching on an error (for autocomplete, visibility, etc.):

switch (err) {
    Writer.Error.AccessDenied => // ...
    else => {e} // ...
}

Admittedly, this is more of a use-case issue than anything. Maybe ZLS can infer the error set; maybe it already does…

Another thing is error grouping. Seeing an error set in a struct that defines the set of errors for an API is useful to see. This would be unfortunate to lose.

I’m almost the opposite here. I see the value in error.Error, but in order to strictly adhere to the One Obvious Way to Do Things mantra, I’d prefer a strict error set. But since that’s not really practical, having error.Error and MyError.Error I think makes sense here.

2 Likes

The autocomplete is a good point.

Another thing is error grouping. Seeing an error set in a struct that defines the set of errors for an API is useful to see. This would be unfortunate to lose.

I agree, I don’t think error sets should be removed, just the feature of referencing an error value through an error set with the dot syntax.

Another problem with error set member access is that it’s not clear which error set to pull from: For example:

const FooError = error {Foo} || std.Io.Cancelable;
const BarError = error {Bar} || std.Io.Cancelable;

fn foo() FooError!void {
    bar() catch |err| switch (err) {
        std.Io.Cancelable.Canceled => |e| return e,
        BarError.Bar => return FooError.Foo,
    };
}

It doesn’t matter which error set is used. error.Canceled, BarError.Canceled, FooError.Canceled, and std.Io.Cancelable.Canceled are all the same error.

This example would be clearer if it was written:

const FooError = error {Foo} || std.Io.Cancelable;
const BarError = error {Bar} || std.Io.Cancelable;

fn foo() FooError!void {
    bar() catch |err| switch (err) {
        error.Canceled => |e| return e,
        error.Bar => return error.Foo,
    };
}
3 Likes

Errors should be unique in my opinion. Not merged by name.

3 Likes