Help use writePositional

hello

example to use please

writePositional(file: File, io: Io, buffer: [][]const u8, offset: u64)

It’s not implemented yet:

2 Likes

buffer: [][]const
I have never used this type

in the three years I have been doing zig

but always [] const u8 or arraylist etc.

How do I transfer [] const u8 [][] u8?

Please

try this:

pub fn strArrToBytes(allocator: std.mem.Allocator, str_arr: [][]const u8) ![]u8 {
    var total_size: usize = (str_arr.len + 1) * @sizeOf(usize);
    for (0..str_arr.len) |i| total_size += str_arr[i].len;
    var bytes = try allocator.alloc(u8, total_size);
    var length: usize = str_arr.len;
    var pos: usize = 0;
    mem.copyForwards(u8, bytes[pos..], mem.asBytes(&length)[0..]);
    pos += @sizeOf(usize);
    for (0..str_arr.len) |i| {
        length = str_arr[i].len;
        mem.copyForwards(u8, bytes[pos..], mem.asBytes(&length)[0..]);
        pos += @sizeOf(usize);
        mem.copyForwards(u8, bytes[pos..], str_arr[i][0..length]);
        pos += str_arr[i].len;
    }
    return bytes;
}

pub fn bytesToStrArr(allocator: std.mem.Allocator, bytes: []u8) ![][]const u8 {
    var bytes_usize:[@sizeOf(usize)]u8 = undefined;
    var pos: usize = 0;
    mem.copyForwards(u8, bytes_usize[0..], bytes[pos..(pos + @sizeOf(usize))]);
    pos += @sizeOf(usize);
    var length: usize = mem.bytesToValue(usize, bytes_usize[0..]);
    var str_arr: [][]const u8 = try allocator.alloc([]const u8, length);
    for (0..str_arr.len) |i| {
        mem.copyForwards(u8, bytes_usize[0..], bytes[pos..(pos + @sizeOf(usize))]);
        pos += @sizeOf(usize);
        length = mem.bytesToValue(usize, bytes_usize[0..]);
        str_arr[i] = try allocator.alloc(u8, length);
        mem.copyForwards(u8, @constCast(str_arr[i][0..]), bytes[pos..(pos + length)]);
        pos += length;
    }
    return str_arr;
}

test "TestStrArr" {
    var str_arr = [_][]const u8{ "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" };
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    const allocator = gpa.allocator();
    const bytes = try strArrToBytes(allocator, &str_arr);
    const str_arr2 = try bytesToStrArr(allocator, bytes);
    for (0..str_arr.len) |i| try expect(mem.eql(u8, str_arr[i], str_arr2[i]));
}

1 Like

No need for all of that

var buf: [1][]const u8 = .{bytes};
const n = try file.writePositional(io, &buf, 123);

but, again, it’ll just panic:

thread 17904 panic: TODO implement fileWritePositional
C:\Users\Ryan\Programming\Zig\zig\lib\std\Io\Threaded.zig:2851:9: 0x7ff7ae16a848 in fileWritePositional (writepos_zcu.obj)
        @panic("TODO implement fileWritePositional");
        ^
2 Likes