use case: generalize the format string mechanism so code other than printf can use it #250
Labels
enhancement
Solving this issue will likely involve adding new logic or components to the codebase.
Milestone
Requirements:
The type of
writeBytes
is a bound method, so that it can accessthe
result
variable. We can allow users to call functions whichexpect normal function pointers. Whenever a function expects a
function pointer, if it is ever potentially called with a bound
function, we can secretly make it expect a bound function, because
we can set theh instance pointer value to null, since it is never
accessed in a normal function.
The point of all this is that the format code is now decoupled from
I/O, and it could be used for other purposes.
For example, in a kernel, one might define a function like this:
Also, in general, it makes callbacks more viable, because it solves the
void * context
unsafety problem.There is a flaw, however, in the optimality. Here is some C:
Here, the struct efficiently stores
userdata
- representing the pointer weare binding to in a bound function. If we had automatic bound functions
as proposed above:
With the above automatic bound function proposal, if the programmer only set
these fields to normal functions, we would actually end up saving space
over C.
But if the programmer set all 3 fields at some point to bound functions,
for example, to the same instance, that would waste 2 pointers worth of
space.
However, this isn't quite analogous to the C example, because the Zig version
allows the programmer to set each function to a different instance of
potentially even different types. If you did that in C you would end up
introducing the extra pointers anyway.
A completely different take on this:
This is more explicit - requiring the definition to explicitly support a
context - and it has none of the requirements of the first example (except completing var args a little more #77 (comment)).
One downside is that it generates wasteful template instantiations. But
since most will use a pointer which is passed verbatim, we should be
able to avoid most of the waste when we can detect that these
instantiations can codegen to the same thing.
For completeness, the kernel log example with the 2nd proposal:
The text was updated successfully, but these errors were encountered: