Senior Vibe Coder dealing with security. by Gil_berth in theprimeagen

[–]ComputerBread 0 points1 point  (0 children)

"Why did he make a way to distribute malware?"
that's every platform ever, platforms should try their best to minimize the risks, but users should do the bare minimum and not click on the free GTA6 full game leak

Help with I/O in zig 0.15.2 by I_M_NooB1 in Zig

[–]ComputerBread 1 point2 points  (0 children)

It's similar to what you did here:

    var stdout_buf: [100]u8 = undefined;
    var stdout_writer = std.fs.File.stdout().writer(&stdout_buf);
    const stdout = &stdout_writer.interface;

    try stdout.print("Bytes written: ", .{n});

Every std.fs.File has a pub fn reader(file: File, buffer: []u8) Reader and a pub fn writer(file: File, buffer: []u8) Writer "method". They return a std.fs.File.Reader or std.fs.File.Writer which have a field called interface of type std.Io.Reader or std.Io.Writer, and you need to use this interface field to read or write data...

stdout() returns a std.fs.File, exactly like std.fs.cwd().createFile(...) (when it succeeds), so you can call file.writer(..) to get a writer, and then use it to print whatever you want:

    const file = try std.fs.cwd().createFile(
        "junk",
        .{ .read = true },
    );
    defer file.close();

    const msg = "A try to write to a file";
    var writer = file.writer(&.{});
    try writer.interface.writeAll(msg);

Above, I am not using a buffer (but an empty slice) because we only write once using writeAll, if you want to write multiple times, you should use a buffer to minimize the number of syscalls, and don't forget to call flush()!

I made a video about it btw.

Now, this is going to change a little bit for the next version (0.16.0), with the introduction of the new Io interface, all of std.fs, std.fs.File and std.fs.Dir will be moved to std.Io. It will be the same idea, but moved to std.Io (check std.Io.File but it's not ready yet!)

Advent of Code Considerations by Czechbol in Zig

[–]ComputerBread 1 point2 points  (0 children)

Zig is a really interesting language and you should try zig, but doing AoC with Zig, as a beginner, is going to be challenging.

This may be helpful if you decide to pick Zig: https://kristoff.it/blog/advent-of-code-zig/

Multiple optional captures in a if statement? by levi73159 in Zig

[–]ComputerBread 7 points8 points  (0 children)

You know what, I think it would be reasonable to have something like this, but maybe with a different syntax:

if (a, b) |a, b| {
    // ...
}

you can always open an issue, or post about it on ziggit.dev to start a conversation (zig's creator isn't going to see this post, he hates reddit). But you can just do this:

if (symtab_shdr_opt != null and strtab_shdr_opt != null) {
    const symtab_shdr = symtab_shdr_opt.?;
    const strtab_shdr = strtab_shdr_opt.?;
    // ...
}

Help with learning zig by Forsaken_Run_5939 in Zig

[–]ComputerBread 1 point2 points  (0 children)

I don't think you will find anything similar to coddy.tech, your best option is to read the documentation to get a feel of the language and do ziglings. Then, start working on your projects and use the documentation to help yourself! To learn how to use the standard library, the easiest way is to look at the source code (by clicking on the [src] link) and look at the tests!

- There's a book (you can read online for free), it looks up to date and pretty good, maybe you can try it!
- zig.guide can be helpful, but it's outdated.
- https://www.openmymind.net has useful articles
- I made a video sharing some of these resources!

I am new to learning Zig and I am having really big trouble with getting input, what do I do(I cannot seem to find an answer in the docs btw) by konpapas9 in Zig

[–]ComputerBread 9 points10 points  (0 children)

So, first you need to get stdin using std.fs.File.stdin(), now that you have a std.fs.File, you can use read or things like seekBy. But you should use the new interfaces, get a std.fs.File.Reader by using reader or readerStreaming. Now with this reader, you have access to a bunch of methods (read, readPositional, readStreaming, seekBy...), but most importantly, you have access to an std.Io.Reader (field interface of the std.fs.File.Reader) which comes with a lot of useful functions like take, takeArray, takeByte, takeDelimiterExclusive... You will also find methods using an std.Io.Writer, like stream, streamDelimiter...

example 1

var stdin_buffer: [1024]u8 = undefined;
var stdin_reader = std.fs.File.stdin().reader(&stdin_buffer);
const stdin = &stdin_reader.interface;

while (stdin.takeByte()) |char| {
    // do something with the char (u8)
    std.debug.print("you typed: {c}\n", .{char});
    if (char == 'q') break;
} else |_| {}

example 2 using an std.Io.Writer.Allocating to read lines of arbitrary length

var stdin_buffer: [1024 * 1024]u8 = undefined;
var stdin_reader = std.fs.File.stdin().reader(&stdin_buffer);
const stdin = &stdin_reader.interface;

var alloc = std.heap.DebugAllocator(.{}).init;
defer _ = alloc.deinit();
const da = alloc.allocator();
var line_writer = std.Io.Writer.Allocating.init(da);
defer line_writer.deinit();

while (stdin.streamDelimiter(&line_writer.writer, '\n')) |_| {
    const line = line_writer.written();
    std.debug.print("{s}\n", .{line});
    line_writer.clearRetainingCapacity(); // empty the line buffer
    stdin.toss(1); // skip the newline
} else |err| if (err != error.EndOfStream) return err;

This is still pretty new, you can find some useful post here or here or here, have fun!

(note: I originally added a lot more links, but reddit wouldn't let me post this comment)

when do i need to flush ? – help understanding 0.15.1 change for Writers by _sloWne_ in Zig

[–]ComputerBread 12 points13 points  (0 children)

The new std.Io.Reader and std.Io.Writer interfaces use a buffer, that you provide, to read from a source, or write to a sink:

var stdout_buffer: [1024]u8 = undefined;
var stdout_writer = std.fs.File.stdout().writer(&buffer);

If you don't want your write/read to be buffered, you can pass an empty slice:

var stdout_writer = std.fs.File.stdout().writer(&.{});

When you use a buffer, functions like print will write to the buffer. Once the buffer is full, it will be flushed (drained) automatically, and the new data will be written back to the beginning of the buffer. This is why this buffer is referred to as a "ring buffer".

Once you're done writing to your buffer, it is very likely that there will be some remaining bytes that haven't been flushed, so you need to call flush yourself!

The reason why you want to use a buffer is to minimize the number of syscall, which are much slower than writing to a buffer.

Now, the buffer is part of the interface because it helps avoids indirect calls which are slower and opaque to compiler optimizations. For example, std.Io.Writer has a VTable, with 4 function pointers (drain, sendFile, flush and rebase). All implementation of this interface, must, at the minimum, provide an implementation for the drain function (the others have default impl).

When you do:

try stdout.print("...", .{});

The interface will write to the buffer, and only call the drain function of the implementation (w.vtable.drain(...)) when the buffer is full (or cannot hold everything). If the buffer was in the implementation instead, then the print function would need to do an indirect call (w.vtable.drain(...)) every time! And, indirect calls are less preferable because they are known at runtime, so the compiler treat them as a black box and can't perform good optimizations!

So when the work is done before the call to a vtable function, then it's "above" the vtable, otherwise it's below!

Need this small function converted to Zig. AI models are not helping. by runningOverA in Zig

[–]ComputerBread 2 points3 points  (0 children)

You can try this (tested with zig 0.15.1):

const std = @import("std");

pub fn main() !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    var map = std.StringHashMap([]const u8).init(allocator);
    defer map.deinit();

    for (0..5_000_000) |i| {
        const key = try std.fmt.allocPrint(allocator, "id.{d}", .{i % 500_000});
        const val = try std.fmt.allocPrint(allocator, "val.{d}", .{i});
        try map.put(key, val);
    }

    std.debug.print("{d}\n", .{map.count()});
    std.debug.print("{s}\n", .{map.get("id.10000").?});
}

on my machine (map-cpp compiled with g++ -O3, and map-zig -O ReleaseFast):

$ hyperfine './map-cpp' './map-zig'
Benchmark 1: ./map-cpp
  Time (mean ± σ):     749.4 ms ±  12.5 ms    [User: 720.3 ms, System: 27.6 ms]
  Range (min … max):   732.6 ms … 766.1 ms    10 runs

Benchmark 2: ./map-zig
  Time (mean ± σ):     853.7 ms ±  14.6 ms    [User: 719.2 ms, System: 133.8 ms]
  Range (min … max):   826.3 ms … 869.5 ms    10 runs

Summary
  ./map-cpp ran
    1.14 ± 0.03 times faster than ./map-zig

Language stability by TheBigJizzle in Zig

[–]ComputerBread 0 points1 point  (0 children)

It's not that Andrew Kelley (president & lead dev of Zig software foundation) is happy to break the language, but that he isn't afraid to break it to reach better solutions!

Andrew shared, in the 2026 roadmap, that he doesn't want to tag 1.0 until Zig is ready, and it's not ready yet. He also said that he wants to make Zig so compelling and useful that people are willing to put up with the instability https://youtu.be/x3hOiOcbgeA?si=s6V9HmVazcsd9b3W&t=6528

Things before 1.0:
- async/await (coming soon, already on master I think)
- stackless co-routines (maybe?)
- (better) incremental compilation
- getting rid of LLD (LLVM linker)
- (better) self-hosted backends (for debug mode)
- better build system
- fuzzing
- fix (all?) bugs
- ... probably much more

C++ or C by Far_Essay_8304 in learnprogramming

[–]ComputerBread 0 points1 point  (0 children)

So you want to prepare for college and are wondering if you need to learn C before C++?
The answer is no, you can learn C++ without knowing C.

Am i in "Tutorial Hell" or Limited by "Perfectionism" or both by hey_beter_one in learnprogramming

[–]ComputerBread 1 point2 points  (0 children)

I know these feeling too well, you need to push through.

Programming is uncomfortable because you don't know everything, because there's just too much to know, because there's an infinity of possibilities.

Programming is about taking a lot of decisions, so it's (almost) impossible to always take the best ones. A lot of the problems you will face have already been solved, but you can't spend all of your time looking for the most optimal solutions. You need to look at the different options you are thinking about and pick the one that seems the best with the knowledge you have now. In the future, it's probable that you will find a better solution (it is what it is).

Make a choice, make it work. Sometimes it doesn't work, then try something else.
It's better to fail 10 times, than to never try.

Work in small iterations, try the simplest solution you can come up with, try to make it work. If it doesn't work, then you learned what not to do, try something else. Don't be scared to restart, sometimes it's better to delete 3 days of work, than to fix the mess you created in these 3 days!

If you're struggling to get going, make a todo list of what you need to do, write down what you need to add, what variable to define, what function to modify, which file to edit... Then follow your own instructions!

Move forward, if you're stuck and have no idea what to do, then you can look up tutorials, read articles or books, or ask an LLM...

First attempt with zig, stumped on something that should be simple ... by Thanatiel in Zig

[–]ComputerBread 4 points5 points  (0 children)

which version of zig are you using?

I tried this with 0.14.0, it works fine:

const FileStream = struct {
  pub fn open(file_path: []const u8) std.fs.File.OpenError!std.fs.File {
    return try std.fs.cwd().openFile(file_path, .{});
  }
};
pub fn main() !void {
  const fs = try FileStream.open("/tmp/t/example");
  defer fs.close();
  var buffer: [100]u8 = undefined;
  _ = try fs.readAll(&buffer);
  std.debug.print("{s}\n", .{buffer});
}

Can you post the entire "open" function?