#How are you able to copy a struct in zig?

1 messages · Page 1 of 1 (latest)

livid tulip
#

How are you able to copy a struct in zig?

limber rock
#

Use parseFromSliceLeaky to get the value directly, not wrapped in a Parsed

#

er, wait

#

That would be, well, leaky.. I guess instead why not just return parsed (and not deinit it inside of fetch)?

#

Well, that could result in more memory usage than desired... so if you just wanna copy the value, create a new Response with the allocator, and copy it in to it

#

Actually I've confused myself now...

#

Right, okay, yeah, resp.content is a slice, which is a pointer and a length -- parsed.value is copied when you return it, but the pointer remains a pointer to the memory from the arena inside parsed, which is freed when it's deinit-ed

#

The easiest solution is returning the full parsed and letting the caller deinit it

#

Which will entail a little more memory overhead than copying just the exact memory you need, but will be faster since it doesn't require a copy

#

If you want to copy, you'd use allocator.dupe on the slice(s) you need to copy

#

I don't think that the std has a generic deep copy function in it rn, so you'd have to just manually do it for the relevant fields
e.g. if content is your only slice field:

var res: Response = parsed.value;
res.content = allocator.dupe(u8, res.content);
return res;
limber rock