Thread View: comp.lang.c
129 messages
129 total messages
Page 2 of 3
Started by Ross Finlayson
Thu, 12 Nov 2026 17:41
Page 2 of 3 • 129 total messages
Re: Inversion-of-control and dependency-injection in C
Author: Bonita Montero
Date: Mon, 16 Nov 2026 17:04
Date: Mon, 16 Nov 2026 17:04
10 lines
2040 bytes
2040 bytes
Am 16.11.2026 um 18:00 schrieb fir: > so maybe try it right c way Do you want to compare C vs. C++ or algorithm A vs. algorithm B ? The point was that C++ is more convenient and faster than C through functional programming when using functional programming with both languages; as far as the C-solution can be called functional (I wouldn't call it so). And as I've shown the std::sort() leads to about six times less code than qsort().
Re: Inversion-of-control and dependency-injection in C
Author: fir
Date: Mon, 16 Nov 2026 17:24
Date: Mon, 16 Nov 2026 17:24
16 lines
2339 bytes
2339 bytes
Bonita Montero pisze: > Am 16.11.2026 um 18:00 schrieb fir: > >> so maybe try it right c way > Do you want to compare C vs. C++ or algorithm A vs. algorithm B ? > The point was that C++ is more convenient and faster than C through > functional programming when using functional programming with both > languages; as far as the C-solution can be called functional (I > wouldn't call it so). And as I've shown the std::sort() leads to > about six times less code than qsort(). > i compare you and myself... you compere your own shilt choice of qsort (which only lame coders would take..surprise! bonita took it! sith lame std::sort which only lame c++ crowd could take..surprise again)
Re: Inversion-of-control and dependency-injection in C
Author: Bonita Montero
Date: Mon, 16 Nov 2026 17:29
Date: Mon, 16 Nov 2026 17:29
7 lines
1920 bytes
1920 bytes
Am 16.11.2026 um 18:24 schrieb fir: > i compare you and myself... The discussion was about functional programming in either languagage with comparable algorithms. Not about algorithm A in language X vs. algorithm B in language Y.
Re: Inversion-of-control and dependency-injection in C
Author: Ross Finlayson
Date: Mon, 16 Nov 2026 17:35
Date: Mon, 16 Nov 2026 17:35
88 lines
4769 bytes
4769 bytes
On 11/14/2026 09:05 AM, Ross Finlayson wrote: > On 11/12/2026 01:44 PM, Ross Finlayson wrote: >> On 11/12/2026 12:55 PM, Richard Harnden wrote: >>> On 12/11/2026 20:11, Lew Pitcher wrote: >>>> On Thu, 12 Nov 2026 09:41:04 -0800, Ross Finlayson wrote: >>>> >>>>> Hello, dear C experts, I'm hoping you can tell me a story about >>>>> modularity and composability, about the concerns of >>>>> inversion-of-control >>>>> and dependency-injection in C, basically about wiring >>>>> test-time and run-time targets, for example about conditional-includes >>>>> and various build-targets, probably mostly about function pointers. >>>> >>>> Pardon my impertinence, but this sounds like a homework problem to me. >>>> >>>> Could you rephrase your question without the academic wording? >>>> >>> >>> Or get an AI do to your homework? >>> >>> Be careful to remove the white-on-white-very-small-font gotcha your >>> professor doubtlessly put in. >>> >>> >> >> >> When I use "A.I." it's framed as a dialogue and I just copy the >> transcripts directly, with the attributions. >> >> I.e., I've never submitted anything to Usenet written by a bot >> on my behalf. >> >> >> I'm not sure whether I'd call it "distance learning", or, >> "distance learning", say, .... >> >> >> >> >> Like say for example I'm looking at something like this that I tapped >> up this morning, and I want to figure out then how to make it so that >> the guts of the workers have a nice real quality of covering all the >> bases of covering all the cases, when for example according to the C >> host as it were or POSIX there's signals and traps to be figured out >> in accounts of "asynchronous concurrency". >> >> >> >> >> >> >> Outline of "I/O-handle-bound process model" >> >> The "I/O-handle-bound process model", is an account of a process group >> in a process tree, >> that works up to the bounds of 1024 many file-descriptors that a >> pselect() call can poll, >> with up to 1000-many file-descriptors in up to 1000-many worker >> processes, for up to >> 1,000,000-many open connections. >> [ ... ] I posted another long and discursive bot-chat on comp.theory/comp.unix.programmer about "Portable, Safe, Parallel-Semantic Protocol Servers", basically getting into concepts of modules and module-ry (like pattern-ry) about config and protocol and resource models in a runtime this "I/O-handle-bound process-model" of a C11 (C++11-friendly) POSIX-platform framework account of "what are modules for componentry about the composable then the component-registry and service-discovery for configuration the code the process-model of a runtime of a high-performance high-reliability re-purposable run-time of protocols and resources". I wondered if they had anything to cure OCD yet then I'd figure they'd forget it, ...., So, this sort of account about C11 (obligatory relevance to a discussion about C) of pattern-ry of module-ry (that's a new one) of component-ry, mostly is about design, then also about the fact that a rather simple and uncomplicated footprint of code, is quite most the guts of "the server" (application layer).
Re: Inversion-of-control and dependency-injection in C
Author: fir
Date: Mon, 16 Nov 2026 17:43
Date: Mon, 16 Nov 2026 17:43
17 lines
2563 bytes
2563 bytes
Bonita Montero pisze: > Am 16.11.2026 um 18:24 schrieb fir: > >> i compare you and myself... > The discussion was about functional programming in either languagage > with comparable algorithms. Not about algorithm A in language X vs. > algorithm B in language Y. > note i call you a lame becouse in such kind of opinioons youre lame ans spread lame talk.. but mostly i call you a lame becouse of your offensive and stuppid atitude to c..so i dont wanted to be pointed i "name somewhat lame" its a contextual reaction to some user who dont want to learn something - not my 'global' ( not context ) opinion (not saying i have or not have any.. im like not much have becouse things are context dependant and it looks different in many different contexts) (obviousy in the context of clc bonita is not doin much well)
Re: Inversion-of-control and dependency-injection in C
Author: Bonita Montero
Date: Mon, 16 Nov 2026 17:47
Date: Mon, 16 Nov 2026 17:47
10 lines
2016 bytes
2016 bytes
Am 16.11.2026 um 18:43 schrieb fir: > note i call you a lame becouse in such kind of opinioons youre lame ans > spread lame talk.. And you are shifting to aspects that have nothing to do with the initial discussion. Rest unread.
Re: Inversion-of-control and dependency-injection in C
Author: fir
Date: Mon, 16 Nov 2026 17:55
Date: Mon, 16 Nov 2026 17:55
15 lines
2220 bytes
2220 bytes
Bonita Montero pisze: > Am 16.11.2026 um 18:43 schrieb fir: > >> note i call you a lame becouse in such kind of opinioons youre lame >> ans spread lame talk.. > > And you are shifting to aspects that have nothing to do with the initial > discussion. > > Rest unread. > i know lame bonita i dont answer oryginal discusion i just show youre very lame in sorting and you talk lame shit
Re: Inversion-of-control and dependency-injection in C
Author: Bonita Montero
Date: Mon, 16 Nov 2026 17:57
Date: Mon, 16 Nov 2026 17:57
17 lines
2341 bytes
2341 bytes
Am 16.11.2026 um 18:55 schrieb fir: > Bonita Montero pisze: >> Am 16.11.2026 um 18:43 schrieb fir: >> >>> note i call you a lame becouse in such kind of opinioons youre lame >>> ans spread lame talk.. >> >> And you are shifting to aspects that have nothing to do with the initial >> discussion. >> >> Rest unread. >> > > i know lame bonita i dont answer oryginal discusion i just show youre > very lame in sorting and you talk lame shit You're like fifteen.
Re: Inversion-of-control and dependency-injection in C
Author: fir
Date: Mon, 16 Nov 2026 18:08
Date: Mon, 16 Nov 2026 18:08
69 lines
3933 bytes
3933 bytes
fir pisze:
> so maybe try it right c way
>
>
>
>
> typedef unsigned int UI32;
>
> UI32 * RadixSortUnsigned(UI32 * pData, UI32 * pTemp, size_t count)
> {
> size_t mIndex[4][256] = {0}; // index matrix
> UI32 *pDst, *pSrc, *pTmp;
> size_t i,j,m,n;
> UI32 u;
>
> for(i = 0; i < count; i++){ // generate histograms
> u = pData[i];
> for(j = 0; j < 4; j++){
> mIndex[j][(size_t)(u & 0xff)]++;
> u >>= 8;
> }
> }
> for(j = 0; j < 4; j++){ // convert to indices
> n = 0;
> for(i = 0; i < 256; i++){
> m = mIndex[j][i];
> mIndex[j][i] = n;
> n += m;
> }
> }
> pDst = pTemp; // radix sort
> pSrc = pData;
> for(j = 0; j < 4; j++){
> for(i = 0; i < count; i++){
> u = pSrc[i];
> m = (size_t)(u >> (j<<3)) & 0xff;
> pDst[mIndex[j][m]++] = u;
> }
> pTmp = pSrc;
> pSrc = pDst;
> pDst = pTmp;
> }
> return(pSrc);
> }
>
>
not i took this from the net so its not my own code and when i took it i
dont understood it (i only knew that radix sort may be nbetter and
std sort form c++ is suposingly lame)..so i measured it 27 ms C vs 111
ms stdlib C++ ;c
now i understand it its not so hard first you build histograms for each
byte of input (if input is 1M you got 4M ++s
then you transform this histogram into offsets like 0:17 1:32 turns into
0 17 49...
then you travel on oryginal input array and use those offsets as movabe
i mean if you find byte "2" you put it in tab[49]="this number that lasy
byte is 2" and increase 49 on 50 on next pass you do it on 2nd byte
so its 4x1MB insertions
its quite neat and i dont see it yet maybe totally sharop but a abit of
focus and it can be quite sharply understood (i understand it enough)
overally it is quite C style algortihm much more than typical sorting
so it not only beats those sortings but is indeed C style
Re: Inversion-of-control and dependency-injection in C
Author: Bonita Montero
Date: Mon, 16 Nov 2026 18:09
Date: Mon, 16 Nov 2026 18:09
15 lines
2570 bytes
2570 bytes
Am 13.11.2026 um 23:50 schrieb Ross Finlayson: > So, here's one. Say you got a server process for sockets of the > connection-oriented or datagram-wise or association-oriented like > TCP, UDP, or SCTP, and it manages the connecting and the sending and > receiving about a million of those and is sort of fixed-size and > stable in a usual runtime. So, how do you design the interface, > about stuff like the state-machine of _protocols_, all about > _protocols_, in the application-layer and above, say, for example > the incremental-parsing and the state-machine of the protocol > and sub-protocols and upgrade-protocols and the like, what sort > of abstraction with suitable-defaults and reasonable-opinions > makes for having any sort protocol as a composable library. Use C++20 coroutines with Bost.ASIO and io_uring. This gives as less code as possible with nearly optimal I/O performance.
Re: Inversion-of-control and dependency-injection in C
Author: fir
Date: Mon, 16 Nov 2026 18:10
Date: Mon, 16 Nov 2026 18:10
20 lines
2551 bytes
2551 bytes
Bonita Montero pisze: > Am 16.11.2026 um 18:55 schrieb fir: >> Bonita Montero pisze: >>> Am 16.11.2026 um 18:43 schrieb fir: >>> >>>> note i call you a lame becouse in such kind of opinioons youre lame >>>> ans spread lame talk.. >>> >>> And you are shifting to aspects that have nothing to do with the initial >>> discussion. >>> >>> Rest unread. >>> >> >> i know lame bonita i dont answer oryginal discusion i just show youre >> very lame in sorting and you talk lame shit > You're like fifteen. > to may friend emo i always said im almost 15 (14.9 maybe, 14.8?) (but now i feel old..where are those times i felt like 14)
Re: Inversion-of-control and dependency-injection in C
Author: Ross Finlayson
Date: Mon, 16 Nov 2026 20:04
Date: Mon, 16 Nov 2026 20:04
58 lines
4698 bytes
4698 bytes
On 11/16/2026 10:09 AM, Bonita Montero wrote: > Am 13.11.2026 um 23:50 schrieb Ross Finlayson: > >> So, here's one. Say you got a server process for sockets of the >> connection-oriented or datagram-wise or association-oriented like >> TCP, UDP, or SCTP, and it manages the connecting and the sending and >> receiving about a million of those and is sort of fixed-size and >> stable in a usual runtime. So, how do you design the interface, >> about stuff like the state-machine of _protocols_, all about >> _protocols_, in the application-layer and above, say, for example >> the incremental-parsing and the state-machine of the protocol >> and sub-protocols and upgrade-protocols and the like, what sort >> of abstraction with suitable-defaults and reasonable-opinions >> makes for having any sort protocol as a composable library. > Use C++20 coroutines with Bost.ASIO and io_uring. This gives > as less code as possible with nearly optimal I/O performance. Thanks for writing Bonita. I'd infer from "schrieb" that your user-agent locale country/language is DE/de or as variously for example about 2-letter and 3-letter country codes and accounts of language or ISO 601 or what I forget. Mann kann nur kleine Deutsch gesprechern, nicht viel das hier doch, aber los. Mein Wortschatz, es ist kaput. That said, _why_ I specifically am not using epoll/kqueue or io_uring instead pselect not select or poll, is: if you overload the epoll red/black tree or io_iuring queues respectively, they drop messages. Now, most of the time, that's accommodated by some absurdly simple back-end like "send" that tolerates drops itself, in things like message-bus. Then, epoll for example, on a wake-up or return from the blocking syscall, doesn't notify twice when there remains data to be read. Then, pselect() may be blocking and furthermore with the impact that the kernel polls the sockets busily, yet, pselect() can timeout itself, for example, and register interest on active selectors and only periodically eg 5ms register interest on active + inactive selectors (file-descriptors). Then, there's a fact that POSIX runtimes have signals, then, that pselect() behaves in a more defined manner. Another key distinction is that: buffers for use with epoll and I believe also kqueue, or io_uring, must be "pinned" with mlock() or what, to physical memory, for the kernel to treat them, instead of copying from user-space to kernel-space or vice-versa or however the runtime may care to swap pages under addresses with making copies, that for accounts of vector I/O, scatter/gather yet mostly vector I/O for the bus boss the DMA, it's just plain old heap RAM. Then, also pselect() is POSIX and so it's portable. It's less code if it doesn't need multiple back-ends for various platforms' implementations of I/O multiplexing.
Re: Inversion-of-control and dependency-injection in C
Author: Ross Finlayson
Date: Mon, 16 Nov 2026 20:20
Date: Mon, 16 Nov 2026 20:20
97 lines
6061 bytes
6061 bytes
On 11/16/2026 12:04 PM, Ross Finlayson wrote: > On 11/16/2026 10:09 AM, Bonita Montero wrote: >> Am 13.11.2026 um 23:50 schrieb Ross Finlayson: >> >>> So, here's one. Say you got a server process for sockets of the >>> connection-oriented or datagram-wise or association-oriented like >>> TCP, UDP, or SCTP, and it manages the connecting and the sending and >>> receiving about a million of those and is sort of fixed-size and >>> stable in a usual runtime. So, how do you design the interface, >>> about stuff like the state-machine of _protocols_, all about >>> _protocols_, in the application-layer and above, say, for example >>> the incremental-parsing and the state-machine of the protocol >>> and sub-protocols and upgrade-protocols and the like, what sort >>> of abstraction with suitable-defaults and reasonable-opinions >>> makes for having any sort protocol as a composable library. >> Use C++20 coroutines with Bost.ASIO and io_uring. This gives >> as less code as possible with nearly optimal I/O performance. > > Thanks for writing Bonita. I'd infer from "schrieb" that > your user-agent locale country/language is DE/de or as > variously for example about 2-letter and 3-letter country > codes and accounts of language or ISO 601 or what I forget. > Mann kann nur kleine Deutsch gesprechern, nicht viel das > hier doch, aber los. Mein Wortschatz, es ist kaput. > > > That said, _why_ I specifically am not using epoll/kqueue > or io_uring instead pselect not select or poll, is: > if you overload the epoll red/black tree or io_iuring queues > respectively, they drop messages. Now, most of the time, > that's accommodated by some absurdly simple back-end like > "send" that tolerates drops itself, in things like message-bus. > Then, epoll for example, on a wake-up or return from the blocking > syscall, doesn't notify twice when there remains data to be read. > Then, pselect() may be blocking and furthermore with the impact > that the kernel polls the sockets busily, yet, pselect() can > timeout itself, for example, and register interest on active > selectors and only periodically eg 5ms register interest on > active + inactive selectors (file-descriptors). > > Then, there's a fact that POSIX runtimes have signals, > then, that pselect() behaves in a more defined manner. > > Another key distinction is that: buffers for use with > epoll and I believe also kqueue, or io_uring, must > be "pinned" with mlock() or what, to physical memory, > for the kernel to treat them, instead of copying from > user-space to kernel-space or vice-versa or however > the runtime may care to swap pages under addresses > with making copies, that for accounts of vector I/O, > scatter/gather yet mostly vector I/O for the bus boss > the DMA, it's just plain old heap RAM. > > > Then, also pselect() is POSIX and so it's portable. > It's less code if it doesn't need multiple back-ends > for various platforms' implementations of I/O multiplexing. > > Why don't they just call std::coroutine "fiber"? About asynchronous-concurrency, and, progress without starvation, and, parallelism, and task-level parallelism vis-a-vis instruction-level parallelism, the "re-routine" account basically makes a model of asynchronous concurrency "in the language, well, with a subset of the libraries of the language", with "automatic parallelization of independent tasks", in a sort of account of framework. "Computronomat: the re-routine, a model of co-operative co-routine" Anyways I suppose I mentioned that before, the re-routine, .... Have I mentioned the re-routine? About asynchrony, there's basically that co-operative multithreading, requires yield, and, call-backs. This is implicit in many accounts of event loops with short-running functions and get tossed back atop the event loop queue. Re-routines just implicitly always yield when any logical dependency is unsatisfied and it's all callbacks and callbacks just re-enter the re-routine. Yeah, I know, basta, enough, enough, basta, I know, I know. It'd be great to have a model of co-operative co-routine in the language, ....
Re: Inversion-of-control and dependency-injection in C
Author: Chris M. Thomasson
Date: Mon, 16 Nov 2026 21:10
Date: Mon, 16 Nov 2026 21:10
63 lines
4813 bytes
4813 bytes
On 11/16/2026 12:04 PM, Ross Finlayson wrote: > On 11/16/2026 10:09 AM, Bonita Montero wrote: >> Am 13.11.2026 um 23:50 schrieb Ross Finlayson: >> >>> So, here's one. Say you got a server process for sockets of the >>> connection-oriented or datagram-wise or association-oriented like >>> TCP, UDP, or SCTP, and it manages the connecting and the sending and >>> receiving about a million of those and is sort of fixed-size and >>> stable in a usual runtime. So, how do you design the interface, >>> about stuff like the state-machine of _protocols_, all about >>> _protocols_, in the application-layer and above, say, for example >>> the incremental-parsing and the state-machine of the protocol >>> and sub-protocols and upgrade-protocols and the like, what sort >>> of abstraction with suitable-defaults and reasonable-opinions >>> makes for having any sort protocol as a composable library. >> Use C++20 coroutines with Bost.ASIO and io_uring. This gives >> as less code as possible with nearly optimal I/O performance. > > Thanks for writing Bonita. I'd infer from "schrieb" that > your user-agent locale country/language is DE/de or as > variously for example about 2-letter and 3-letter country > codes and accounts of language or ISO 601 or what I forget. > Mann kann nur kleine Deutsch gesprechern, nicht viel das > hier doch, aber los. Mein Wortschatz, es ist kaput. > > > That said, _why_ I specifically am not using epoll/kqueue > or io_uring instead pselect not select or poll, is: > if you overload the epoll red/black tree or io_iuring queues > respectively, they drop messages. Now, most of the time, > that's accommodated by some absurdly simple back-end like > "send" that tolerates drops itself, in things like message-bus. > Then, epoll for example, on a wake-up or return from the blocking > syscall, doesn't notify twice when there remains data to be read. > Then, pselect() may be blocking and furthermore with the impact > that the kernel polls the sockets busily, yet, pselect() can > timeout itself, for example, and register interest on active > selectors and only periodically eg 5ms register interest on > active + inactive selectors (file-descriptors). > > Then, there's a fact that POSIX runtimes have signals, > then, that pselect() behaves in a more defined manner. > > Another key distinction is that: buffers for use with > epoll and I believe also kqueue, or io_uring, must > be "pinned" with mlock() or what, to physical memory, > for the kernel to treat them, instead of copying from > user-space to kernel-space or vice-versa or however > the runtime may care to swap pages under addresses > with making copies, that for accounts of vector I/O, > scatter/gather yet mostly vector I/O for the bus boss > the DMA, it's just plain old heap RAM. > > > Then, also pselect() is POSIX and so it's portable. > It's less code if it doesn't need multiple back-ends > for various platforms' implementations of I/O multiplexing. > > Huh? Do you have a clue at all about this? From what you wrote, perhaps not. Sigh.
Re: Inversion-of-control and dependency-injection in C
Author: Ross Finlayson
Date: Tue, 17 Nov 2026 09:00
Date: Tue, 17 Nov 2026 09:00
98 lines
6429 bytes
6429 bytes
On 11/16/2026 01:10 PM, Chris M. Thomasson wrote: > On 11/16/2026 12:04 PM, Ross Finlayson wrote: >> On 11/16/2026 10:09 AM, Bonita Montero wrote: >>> Am 13.11.2026 um 23:50 schrieb Ross Finlayson: >>> >>>> So, here's one. Say you got a server process for sockets of the >>>> connection-oriented or datagram-wise or association-oriented like >>>> TCP, UDP, or SCTP, and it manages the connecting and the sending and >>>> receiving about a million of those and is sort of fixed-size and >>>> stable in a usual runtime. So, how do you design the interface, >>>> about stuff like the state-machine of _protocols_, all about >>>> _protocols_, in the application-layer and above, say, for example >>>> the incremental-parsing and the state-machine of the protocol >>>> and sub-protocols and upgrade-protocols and the like, what sort >>>> of abstraction with suitable-defaults and reasonable-opinions >>>> makes for having any sort protocol as a composable library. >>> Use C++20 coroutines with Bost.ASIO and io_uring. This gives >>> as less code as possible with nearly optimal I/O performance. >> >> Thanks for writing Bonita. I'd infer from "schrieb" that >> your user-agent locale country/language is DE/de or as >> variously for example about 2-letter and 3-letter country >> codes and accounts of language or ISO 601 or what I forget. >> Mann kann nur kleine Deutsch gesprechern, nicht viel das >> hier doch, aber los. Mein Wortschatz, es ist kaput. >> >> >> That said, _why_ I specifically am not using epoll/kqueue >> or io_uring instead pselect not select or poll, is: >> if you overload the epoll red/black tree or io_iuring queues >> respectively, they drop messages. Now, most of the time, >> that's accommodated by some absurdly simple back-end like >> "send" that tolerates drops itself, in things like message-bus. >> Then, epoll for example, on a wake-up or return from the blocking >> syscall, doesn't notify twice when there remains data to be read. >> Then, pselect() may be blocking and furthermore with the impact >> that the kernel polls the sockets busily, yet, pselect() can >> timeout itself, for example, and register interest on active >> selectors and only periodically eg 5ms register interest on >> active + inactive selectors (file-descriptors). >> >> Then, there's a fact that POSIX runtimes have signals, >> then, that pselect() behaves in a more defined manner. >> >> Another key distinction is that: buffers for use with >> epoll and I believe also kqueue, or io_uring, must >> be "pinned" with mlock() or what, to physical memory, >> for the kernel to treat them, instead of copying from >> user-space to kernel-space or vice-versa or however >> the runtime may care to swap pages under addresses >> with making copies, that for accounts of vector I/O, >> scatter/gather yet mostly vector I/O for the bus boss >> the DMA, it's just plain old heap RAM. >> >> >> Then, also pselect() is POSIX and so it's portable. >> It's less code if it doesn't need multiple back-ends >> for various platforms' implementations of I/O multiplexing. >> >> > > Huh? Do you have a clue at all about this? From what you wrote, perhaps > not. Sigh. > About epoll and dropping reads, it's not the same as io_uring which has fixed-sized queues and if it gets full drops those in the kernel, it's about the edge-triggered case or "e"-poll for edge-triggered poll, vis-a-vis the usual account of poll or select or pselect as level-triggered, that there's perceived to be an edge case where epoll would lose notice of a notification. The idea is that while blocking in epoll_wait, that the process gets a signal, then, the kernel interrupts and runs the signal-handler and returning from epoll_wait it gets EINTR, _or_, according to a policy of whether to re-try blocking sys-calls the kernel interrupts and runs the signal-handler and the process enters epoll_wait again. So, I'm under the impression that there's a race-condition where the process gets a signal while blocked in epoll_wait, then according to one of two policies, EAGAIN error-handling or re-try, that it loses the notification, not the packet. The packet is still on the socket to be read, the notification of it was lost. The pselect simply doesn't have that problem, it's level-triggered, and however it re-enters pselect after getting interrupted, as long as there's data yet to read, it will get notified. Then also epoll might not need mlock'ed memory like io_uring does. That's about it.
Re: Inversion-of-control and dependency-injection in C
Author: Chris M. Thomasson
Date: Tue, 17 Nov 2026 23:46
Date: Tue, 17 Nov 2026 23:46
129 lines
7987 bytes
7987 bytes
On 11/17/2026 1:00 AM, Ross Finlayson wrote: > On 11/16/2026 01:10 PM, Chris M. Thomasson wrote: >> On 11/16/2026 12:04 PM, Ross Finlayson wrote: >>> On 11/16/2026 10:09 AM, Bonita Montero wrote: >>>> Am 13.11.2026 um 23:50 schrieb Ross Finlayson: >>>> >>>>> So, here's one. Say you got a server process for sockets of the >>>>> connection-oriented or datagram-wise or association-oriented like >>>>> TCP, UDP, or SCTP, and it manages the connecting and the sending and >>>>> receiving about a million of those and is sort of fixed-size and >>>>> stable in a usual runtime. So, how do you design the interface, >>>>> about stuff like the state-machine of _protocols_, all about >>>>> _protocols_, in the application-layer and above, say, for example >>>>> the incremental-parsing and the state-machine of the protocol >>>>> and sub-protocols and upgrade-protocols and the like, what sort >>>>> of abstraction with suitable-defaults and reasonable-opinions >>>>> makes for having any sort protocol as a composable library. >>>> Use C++20 coroutines with Bost.ASIO and io_uring. This gives >>>> as less code as possible with nearly optimal I/O performance. >>> >>> Thanks for writing Bonita. I'd infer from "schrieb" that >>> your user-agent locale country/language is DE/de or as >>> variously for example about 2-letter and 3-letter country >>> codes and accounts of language or ISO 601 or what I forget. >>> Mann kann nur kleine Deutsch gesprechern, nicht viel das >>> hier doch, aber los. Mein Wortschatz, es ist kaput. >>> >>> >>> That said, _why_ I specifically am not using epoll/kqueue >>> or io_uring instead pselect not select or poll, is: >>> if you overload the epoll red/black tree or io_iuring queues >>> respectively, they drop messages. Now, most of the time, >>> that's accommodated by some absurdly simple back-end like >>> "send" that tolerates drops itself, in things like message-bus. >>> Then, epoll for example, on a wake-up or return from the blocking >>> syscall, doesn't notify twice when there remains data to be read. >>> Then, pselect() may be blocking and furthermore with the impact >>> that the kernel polls the sockets busily, yet, pselect() can >>> timeout itself, for example, and register interest on active >>> selectors and only periodically eg 5ms register interest on >>> active + inactive selectors (file-descriptors). >>> >>> Then, there's a fact that POSIX runtimes have signals, >>> then, that pselect() behaves in a more defined manner. >>> >>> Another key distinction is that: buffers for use with >>> epoll and I believe also kqueue, or io_uring, must >>> be "pinned" with mlock() or what, to physical memory, >>> for the kernel to treat them, instead of copying from >>> user-space to kernel-space or vice-versa or however >>> the runtime may care to swap pages under addresses >>> with making copies, that for accounts of vector I/O, >>> scatter/gather yet mostly vector I/O for the bus boss >>> the DMA, it's just plain old heap RAM. >>> >>> >>> Then, also pselect() is POSIX and so it's portable. >>> It's less code if it doesn't need multiple back-ends >>> for various platforms' implementations of I/O multiplexing. >>> >>> >> >> Huh? Do you have a clue at all about this? From what you wrote, perhaps >> not. Sigh. >> > > > About epoll and dropping reads, it's not the same as io_uring > which has fixed-sized queues and if it gets full drops those > in the kernel, it's about the edge-triggered case or "e"-poll > for edge-triggered poll, vis-a-vis the usual account of poll > or select or pselect as level-triggered, that there's perceived > to be an edge case where epoll would lose notice of a notification. > The idea is that while blocking in epoll_wait, that the process > gets a signal, then, the kernel interrupts and runs the signal-handler > and returning from epoll_wait it gets EINTR, _or_, according to > a policy of whether to re-try blocking sys-calls the kernel interrupts > and runs the signal-handler and the process enters epoll_wait again. > > So, I'm under the impression that there's a race-condition where > the process gets a signal while blocked in epoll_wait, then according > to one of two policies, EAGAIN error-handling or re-try, that it > loses the notification, not the packet. The packet is still on > the socket to be read, the notification of it was lost. > > The pselect simply doesn't have that problem, it's level-triggered, > and however it re-enters pselect after getting interrupted, > as long as there's data yet to read, it will get notified. > > > Then also epoll might not need mlock'ed memory like io_uring does. > > > > That's about it. > > > > pselect() is simple, portable, and for many workloads fast enough. Those are perfectly valid engineering arguments. For a high-performance server, though, well, shit. I personally wouldn't be reaching for pselect() at all. Uggg... One thing I like about mechanisms such as io_uring and IOCP is that they encourage thinking about capacity up front. You tend to preallocate the resources the system needs to operate, size your queues and pools appropriately, and define behavior for resource pressure. Thats generally preferable to discovering in the god damn hot path that yet another allocation is required! Fuck! On Windows, large scale IOCP servers have long used techniques such as so called, zero byte receives, and preallocated connection state to reduce memory pressure and avoid per-operation allocations. Similar ideas apply elsewhere, for sure. The goal is usually to enter a pressure mode before critical resources are exhausted, not to keep allocating indefinitely and hope for the best. When resources start getting tight, I would rather see the server shed load, evict caches, shorten timeouts, disconnect stale clients, or refuse new work than continue consuming memory until the operating system is in trouble. Running out of capacity should be a planned state, not a surprise. That's one of the reasons fixed pools and preallocated state appeal to me for systems under heavy load.
Re: Inversion-of-control and dependency-injection in C
Author: Chris M. Thomasson
Date: Tue, 17 Nov 2026 23:55
Date: Tue, 17 Nov 2026 23:55
134 lines
8313 bytes
8313 bytes
On 11/17/2026 3:46 PM, Chris M. Thomasson wrote: > On 11/17/2026 1:00 AM, Ross Finlayson wrote: >> On 11/16/2026 01:10 PM, Chris M. Thomasson wrote: >>> On 11/16/2026 12:04 PM, Ross Finlayson wrote: >>>> On 11/16/2026 10:09 AM, Bonita Montero wrote: >>>>> Am 13.11.2026 um 23:50 schrieb Ross Finlayson: >>>>> >>>>>> So, here's one. Say you got a server process for sockets of the >>>>>> connection-oriented or datagram-wise or association-oriented like >>>>>> TCP, UDP, or SCTP, and it manages the connecting and the sending and >>>>>> receiving about a million of those and is sort of fixed-size and >>>>>> stable in a usual runtime. So, how do you design the interface, >>>>>> about stuff like the state-machine of _protocols_, all about >>>>>> _protocols_, in the application-layer and above, say, for example >>>>>> the incremental-parsing and the state-machine of the protocol >>>>>> and sub-protocols and upgrade-protocols and the like, what sort >>>>>> of abstraction with suitable-defaults and reasonable-opinions >>>>>> makes for having any sort protocol as a composable library. >>>>> Use C++20 coroutines with Bost.ASIO and io_uring. This gives >>>>> as less code as possible with nearly optimal I/O performance. >>>> >>>> Thanks for writing Bonita. I'd infer from "schrieb" that >>>> your user-agent locale country/language is DE/de or as >>>> variously for example about 2-letter and 3-letter country >>>> codes and accounts of language or ISO 601 or what I forget. >>>> Mann kann nur kleine Deutsch gesprechern, nicht viel das >>>> hier doch, aber los. Mein Wortschatz, es ist kaput. >>>> >>>> >>>> That said, _why_ I specifically am not using epoll/kqueue >>>> or io_uring instead pselect not select or poll, is: >>>> if you overload the epoll red/black tree or io_iuring queues >>>> respectively, they drop messages. Now, most of the time, >>>> that's accommodated by some absurdly simple back-end like >>>> "send" that tolerates drops itself, in things like message-bus. >>>> Then, epoll for example, on a wake-up or return from the blocking >>>> syscall, doesn't notify twice when there remains data to be read. >>>> Then, pselect() may be blocking and furthermore with the impact >>>> that the kernel polls the sockets busily, yet, pselect() can >>>> timeout itself, for example, and register interest on active >>>> selectors and only periodically eg 5ms register interest on >>>> active + inactive selectors (file-descriptors). >>>> >>>> Then, there's a fact that POSIX runtimes have signals, >>>> then, that pselect() behaves in a more defined manner. >>>> >>>> Another key distinction is that: buffers for use with >>>> epoll and I believe also kqueue, or io_uring, must >>>> be "pinned" with mlock() or what, to physical memory, >>>> for the kernel to treat them, instead of copying from >>>> user-space to kernel-space or vice-versa or however >>>> the runtime may care to swap pages under addresses >>>> with making copies, that for accounts of vector I/O, >>>> scatter/gather yet mostly vector I/O for the bus boss >>>> the DMA, it's just plain old heap RAM. >>>> >>>> >>>> Then, also pselect() is POSIX and so it's portable. >>>> It's less code if it doesn't need multiple back-ends >>>> for various platforms' implementations of I/O multiplexing. >>>> >>>> >>> >>> Huh? Do you have a clue at all about this? From what you wrote, perhaps >>> not. Sigh. >>> >> >> >> About epoll and dropping reads, it's not the same as io_uring >> which has fixed-sized queues and if it gets full drops those >> in the kernel, it's about the edge-triggered case or "e"-poll >> for edge-triggered poll, vis-a-vis the usual account of poll >> or select or pselect as level-triggered, that there's perceived >> to be an edge case where epoll would lose notice of a notification. >> The idea is that while blocking in epoll_wait, that the process >> gets a signal, then, the kernel interrupts and runs the signal-handler >> and returning from epoll_wait it gets EINTR, _or_, according to >> a policy of whether to re-try blocking sys-calls the kernel interrupts >> and runs the signal-handler and the process enters epoll_wait again. >> >> So, I'm under the impression that there's a race-condition where >> the process gets a signal while blocked in epoll_wait, then according >> to one of two policies, EAGAIN error-handling or re-try, that it >> loses the notification, not the packet. The packet is still on >> the socket to be read, the notification of it was lost. >> >> The pselect simply doesn't have that problem, it's level-triggered, >> and however it re-enters pselect after getting interrupted, >> as long as there's data yet to read, it will get notified. >> >> >> Then also epoll might not need mlock'ed memory like io_uring does. >> >> >> >> That's about it. >> >> >> >> > > pselect() is simple, portable, and for many workloads fast enough. Those > are perfectly valid engineering arguments. > > For a high-performance server, though, well, shit. I personally wouldn't > be reaching for pselect() at all. Uggg... > > One thing I like about mechanisms such as io_uring and IOCP is that they > encourage thinking about capacity up front. You tend to preallocate the > resources the system needs to operate, size your queues and pools > appropriately, and define behavior for resource pressure. Thats > generally preferable to discovering in the god damn hot path that yet > another allocation is required! Fuck! > > On Windows, large scale IOCP servers have long used techniques such as > so called, zero byte receives, and preallocated connection state to > reduce memory pressure and avoid per-operation allocations. Similar > ideas apply elsewhere, for sure. The goal is usually to enter a pressure > mode before critical resources are exhausted, not to keep allocating > indefinitely and hope for the best. > > When resources start getting tight, I would rather see the server shed > load, evict caches, shorten timeouts, disconnect stale clients, or > refuse new work than continue consuming memory until the operating > system is in trouble. Running out of capacity should be a planned state, > not a surprise. > > That's one of the reasons fixed pools and preallocated state appeal to > me for systems under heavy load. > Also, don't let AIO drift off into the weeds. Iiic, POSIX, or Linux?, made it to compete with IOCP... ;^)
Re: Inversion-of-control and dependency-injection in C
Author: Chris M. Thomasson
Date: Wed, 18 Nov 2026 00:06
Date: Wed, 18 Nov 2026 00:06
103 lines
6729 bytes
6729 bytes
On 11/17/2026 1:00 AM, Ross Finlayson wrote: > On 11/16/2026 01:10 PM, Chris M. Thomasson wrote: >> On 11/16/2026 12:04 PM, Ross Finlayson wrote: >>> On 11/16/2026 10:09 AM, Bonita Montero wrote: >>>> Am 13.11.2026 um 23:50 schrieb Ross Finlayson: >>>> >>>>> So, here's one. Say you got a server process for sockets of the >>>>> connection-oriented or datagram-wise or association-oriented like >>>>> TCP, UDP, or SCTP, and it manages the connecting and the sending and >>>>> receiving about a million of those and is sort of fixed-size and >>>>> stable in a usual runtime. So, how do you design the interface, >>>>> about stuff like the state-machine of _protocols_, all about >>>>> _protocols_, in the application-layer and above, say, for example >>>>> the incremental-parsing and the state-machine of the protocol >>>>> and sub-protocols and upgrade-protocols and the like, what sort >>>>> of abstraction with suitable-defaults and reasonable-opinions >>>>> makes for having any sort protocol as a composable library. >>>> Use C++20 coroutines with Bost.ASIO and io_uring. This gives >>>> as less code as possible with nearly optimal I/O performance. >>> >>> Thanks for writing Bonita. I'd infer from "schrieb" that >>> your user-agent locale country/language is DE/de or as >>> variously for example about 2-letter and 3-letter country >>> codes and accounts of language or ISO 601 or what I forget. >>> Mann kann nur kleine Deutsch gesprechern, nicht viel das >>> hier doch, aber los. Mein Wortschatz, es ist kaput. >>> >>> >>> That said, _why_ I specifically am not using epoll/kqueue >>> or io_uring instead pselect not select or poll, is: >>> if you overload the epoll red/black tree or io_iuring queues >>> respectively, they drop messages. Now, most of the time, >>> that's accommodated by some absurdly simple back-end like >>> "send" that tolerates drops itself, in things like message-bus. >>> Then, epoll for example, on a wake-up or return from the blocking >>> syscall, doesn't notify twice when there remains data to be read. >>> Then, pselect() may be blocking and furthermore with the impact >>> that the kernel polls the sockets busily, yet, pselect() can >>> timeout itself, for example, and register interest on active >>> selectors and only periodically eg 5ms register interest on >>> active + inactive selectors (file-descriptors). >>> >>> Then, there's a fact that POSIX runtimes have signals, >>> then, that pselect() behaves in a more defined manner. >>> >>> Another key distinction is that: buffers for use with >>> epoll and I believe also kqueue, or io_uring, must >>> be "pinned" with mlock() or what, to physical memory, >>> for the kernel to treat them, instead of copying from >>> user-space to kernel-space or vice-versa or however >>> the runtime may care to swap pages under addresses >>> with making copies, that for accounts of vector I/O, >>> scatter/gather yet mostly vector I/O for the bus boss >>> the DMA, it's just plain old heap RAM. >>> >>> >>> Then, also pselect() is POSIX and so it's portable. >>> It's less code if it doesn't need multiple back-ends >>> for various platforms' implementations of I/O multiplexing. >>> >>> >> >> Huh? Do you have a clue at all about this? From what you wrote, perhaps >> not. Sigh. >> > > > About epoll and dropping reads, it's not the same as io_uring > which has fixed-sized queues and if it gets full drops those > in the kernel, it's about the edge-triggered case or "e"-poll > for edge-triggered poll, vis-a-vis the usual account of poll > or select or pselect as level-triggered, that there's perceived > to be an edge case where epoll would lose notice of a notification. > The idea is that while blocking in epoll_wait, that the process > gets a signal, then, the kernel interrupts and runs the signal-handler > and returning from epoll_wait it gets EINTR, _or_, according to > a policy of whether to re-try blocking sys-calls the kernel interrupts > and runs the signal-handler and the process enters epoll_wait again. > > So, I'm under the impression that there's a race-condition where > the process gets a signal while blocked in epoll_wait, then according > to one of two policies, EAGAIN error-handling or re-try, that it > loses the notification, not the packet. The packet is still on > the socket to be read, the notification of it was lost. > > The pselect simply doesn't have that problem, it's level-triggered, > and however it re-enters pselect after getting interrupted, > as long as there's data yet to read, it will get notified. > > > Then also epoll might not need mlock'ed memory like io_uring does. > > > > That's about it. > > > > using io_uring for a high performance server, its a good idea to dedicate the whole box to the server workload. Its not meant to have a shit load of other programs running on it, etc...
Re: Inversion-of-control and dependency-injection in C
Author: Ross Finlayson
Date: Wed, 18 Nov 2026 10:30
Date: Wed, 18 Nov 2026 10:30
186 lines
10630 bytes
10630 bytes
On 11/17/2026 03:46 PM, Chris M. Thomasson wrote: > On 11/17/2026 1:00 AM, Ross Finlayson wrote: >> On 11/16/2026 01:10 PM, Chris M. Thomasson wrote: >>> On 11/16/2026 12:04 PM, Ross Finlayson wrote: >>>> On 11/16/2026 10:09 AM, Bonita Montero wrote: >>>>> Am 13.11.2026 um 23:50 schrieb Ross Finlayson: >>>>> >>>>>> So, here's one. Say you got a server process for sockets of the >>>>>> connection-oriented or datagram-wise or association-oriented like >>>>>> TCP, UDP, or SCTP, and it manages the connecting and the sending and >>>>>> receiving about a million of those and is sort of fixed-size and >>>>>> stable in a usual runtime. So, how do you design the interface, >>>>>> about stuff like the state-machine of _protocols_, all about >>>>>> _protocols_, in the application-layer and above, say, for example >>>>>> the incremental-parsing and the state-machine of the protocol >>>>>> and sub-protocols and upgrade-protocols and the like, what sort >>>>>> of abstraction with suitable-defaults and reasonable-opinions >>>>>> makes for having any sort protocol as a composable library. >>>>> Use C++20 coroutines with Bost.ASIO and io_uring. This gives >>>>> as less code as possible with nearly optimal I/O performance. >>>> >>>> Thanks for writing Bonita. I'd infer from "schrieb" that >>>> your user-agent locale country/language is DE/de or as >>>> variously for example about 2-letter and 3-letter country >>>> codes and accounts of language or ISO 601 or what I forget. >>>> Mann kann nur kleine Deutsch gesprechern, nicht viel das >>>> hier doch, aber los. Mein Wortschatz, es ist kaput. >>>> >>>> >>>> That said, _why_ I specifically am not using epoll/kqueue >>>> or io_uring instead pselect not select or poll, is: >>>> if you overload the epoll red/black tree or io_iuring queues >>>> respectively, they drop messages. Now, most of the time, >>>> that's accommodated by some absurdly simple back-end like >>>> "send" that tolerates drops itself, in things like message-bus. >>>> Then, epoll for example, on a wake-up or return from the blocking >>>> syscall, doesn't notify twice when there remains data to be read. >>>> Then, pselect() may be blocking and furthermore with the impact >>>> that the kernel polls the sockets busily, yet, pselect() can >>>> timeout itself, for example, and register interest on active >>>> selectors and only periodically eg 5ms register interest on >>>> active + inactive selectors (file-descriptors). >>>> >>>> Then, there's a fact that POSIX runtimes have signals, >>>> then, that pselect() behaves in a more defined manner. >>>> >>>> Another key distinction is that: buffers for use with >>>> epoll and I believe also kqueue, or io_uring, must >>>> be "pinned" with mlock() or what, to physical memory, >>>> for the kernel to treat them, instead of copying from >>>> user-space to kernel-space or vice-versa or however >>>> the runtime may care to swap pages under addresses >>>> with making copies, that for accounts of vector I/O, >>>> scatter/gather yet mostly vector I/O for the bus boss >>>> the DMA, it's just plain old heap RAM. >>>> >>>> >>>> Then, also pselect() is POSIX and so it's portable. >>>> It's less code if it doesn't need multiple back-ends >>>> for various platforms' implementations of I/O multiplexing. >>>> >>>> >>> >>> Huh? Do you have a clue at all about this? From what you wrote, perhaps >>> not. Sigh. >>> >> >> >> About epoll and dropping reads, it's not the same as io_uring >> which has fixed-sized queues and if it gets full drops those >> in the kernel, it's about the edge-triggered case or "e"-poll >> for edge-triggered poll, vis-a-vis the usual account of poll >> or select or pselect as level-triggered, that there's perceived >> to be an edge case where epoll would lose notice of a notification. >> The idea is that while blocking in epoll_wait, that the process >> gets a signal, then, the kernel interrupts and runs the signal-handler >> and returning from epoll_wait it gets EINTR, _or_, according to >> a policy of whether to re-try blocking sys-calls the kernel interrupts >> and runs the signal-handler and the process enters epoll_wait again. >> >> So, I'm under the impression that there's a race-condition where >> the process gets a signal while blocked in epoll_wait, then according >> to one of two policies, EAGAIN error-handling or re-try, that it >> loses the notification, not the packet. The packet is still on >> the socket to be read, the notification of it was lost. >> >> The pselect simply doesn't have that problem, it's level-triggered, >> and however it re-enters pselect after getting interrupted, >> as long as there's data yet to read, it will get notified. >> >> >> Then also epoll might not need mlock'ed memory like io_uring does. >> >> >> >> That's about it. >> >> >> >> > > pselect() is simple, portable, and for many workloads fast enough. Those > are perfectly valid engineering arguments. > > For a high-performance server, though, well, shit. I personally wouldn't > be reaching for pselect() at all. Uggg... > > One thing I like about mechanisms such as io_uring and IOCP is that they > encourage thinking about capacity up front. You tend to preallocate the > resources the system needs to operate, size your queues and pools > appropriately, and define behavior for resource pressure. Thats > generally preferable to discovering in the god damn hot path that yet > another allocation is required! Fuck! > > On Windows, large scale IOCP servers have long used techniques such as > so called, zero byte receives, and preallocated connection state to > reduce memory pressure and avoid per-operation allocations. Similar > ideas apply elsewhere, for sure. The goal is usually to enter a pressure > mode before critical resources are exhausted, not to keep allocating > indefinitely and hope for the best. > > When resources start getting tight, I would rather see the server shed > load, evict caches, shorten timeouts, disconnect stale clients, or > refuse new work than continue consuming memory until the operating > system is in trouble. Running out of capacity should be a planned state, > not a surprise. > > That's one of the reasons fixed pools and preallocated state appeal to > me for systems under heavy load. > Preallocated state is another matter altogether, this sort of approach mentioned presumes fixed resources, for example when a memory-pool is in-use, to stop reads and then TCP/IP itself closes the receive window. The "pressure" closes the receive-side, and clients wait (the network buffers). These aren't necessarily huge nodes with vertical scaling, they're mid-sized boxen that have to share all the resources with many other processes. So, we may entirely separate fixed-size allocations and notification/polling subsystems as concerns, about the box: and the network. For example, then often these are virtualized/containerized mid-size boxen, where it's not only that processes shouldn't contend/thrash with the allocator: also when there's memory-pressure that the biggest one gets booted, or "OOMKiller". Then, for example, since the box already has connection limits, and, for example, these get exhausted before this sort of "I/O-handle-bound process-model", it naturally throttles itself. Where pselect() has a limit of FD_SETSIZE handles, of open connections, and furthermore the numbered file-descriptors must be less than FD_SETSIZE, then scaling out in child-processes or workers/laborers, is old-fashioned and stable. launcher <- eg, systemd, privileged port leader <- 1,000-many potential laborers (child processes), fixed-heap listener <- accepts TCP or 1,000-many potential UDP "connections" laborer(s) <- 1,000-many potential connections logger <- funnels the logs logmet <- funnels the metrics logdmp <- funnels dumps loconsole <- optional REPL This is "1,000-many file-descriptors for connections, a dozen for a 'process-protocol' among the 'process-tree' the 'process-group', and 0/1/2 being stdin/stdout/stderr and 4/5/6 being 'stdlog/stdmet/stddmp'", that being an "I/O-handle-bounde process-model". It makes sense that a hog with the flops on dedicated hardware can use all the resources for itself, that not usually being the case. The "thinking about capacity up-front" is a great idea, here that nobody knows what the front-end and back-end capacity will eventually be, for protocols like TCP/IP that "surface the pressure" and a box that doesn't burst under the burst-y. It's appreciated these sorts of accounts.
Re: Inversion-of-control and dependency-injection in C
Author: Ross Finlayson
Date: Wed, 18 Nov 2026 12:13
Date: Wed, 18 Nov 2026 12:13
107 lines
6988 bytes
6988 bytes
On 11/13/2026 08:54 AM, David Brown wrote: > His posts are not written by AI - no AI writes that badly. And it is > not so void of meaning and grammar that it is randomly generated. Ross > has written posts in this style for many years in several Usenet groups. > I find it hard to believe that someone would spend so much time and > effort for a joke. > Then, in another thread, bringing it back here: >> Here then for example, what I'm trying to figure out is basically >> how to make for C what's in C++ without being in C++ that's yet >> readily adaptable for calling and being called from and into C++ >> from C. Like, for example, "sequence" or "iter", and "lister" >> and the like, then for something like "C11 _Generic", making accounts >> of generics the types in C vis-a-vis the polymorphic class model >> in C++, about "sized" or accounts like "characteristics" of access >> of arrays, pointer-offsets, lists, otherwise the usual things, >> "holders", "getters and setters", then about "libraries" and >> "components", after things like "success_t, error_t, and return_t, >> for context_t", definitions of the patterns, that would be generally >> suitable for writing libraries in C and having them callable and >> calling to and from C++, these are the kinds of things I'm liking >> to figure out. >> >> >> Like for example about how to pass an allocator into C, or making >> access of ctx_new/ctx_del or ctx_init/ctx_fini, those being about >> storage or lifetime and ownership and responsibility, then for >> things like "emit_log" and "emit_metric" and "emit_dump", these >> are the kinds of things that later always live in any sort of >> application framework, for making good-style. >> > > Why not just write : > > """ > How do I write C++ code in C? > """ > > The answer then would be, you don't. Write C++ code in C++. Write C > code in C. > Here the points under consideration are that C++ has some relevant constructs that to use the same patterns in C, then to make for the _interoperability_, has for example that libraries of most any usual sort result their symbols, those being of C, or as after name-mangling (a convention of expressing the namespaces and constructs encoding the names/symbols as C defines for what C++ models, name-mangling, where "the mangle" is a steam-press for the ironing of sheets, where the common meaning is "fold, spindle, and mutilate"), there's that "writing C++ in C", is to make it adapt-able. Then, other accounts involve the system, for example malloc/free, vis-a-vis, allocators, and that C++'s account of new/delete, has also an account of pretty much every constructor allowing the passing of an allocator, for example about free-lists/arenas/slabs, about how to make a _pattern_ so that either the library interface signature has function-pointers for acquire-release, or, for example, there's a convention where each process/thread has a global-variable (called thread-local in a thread, global to the thread) with function pointers for acquire/release. It's similar with stdio, or for example loggers, usually considered "static" (or extern) to the process to result a global entry-point for the rest of the routine, or, what makes for that it gets passed to every library-function or installed in the context passsed to every library function, about what aren't "classes" and "instances" like in C++ which is defined in the language, _yet so model those_, why it's a thing. Other examples of accounts for example make for list-adapters or iterators or accounts of sequences then about treating arrays and lists as the same (while they have different characteristics of access, the "access-patternry"), then for example about associative arrays and sets and the like then into traversals for trees and graphs and the like, where for example many "loosely-typed" languages of the day (like JavaScript, Python, ...) have that's _default_ with the "slots" the associative-array, vis-a-vis something like "the shell language" and accounts of attributes, and behaviors for arrays and associative-arrays, those being considered general. So, the idea is that something like C11 has something like "_Generic" keyword to employ, that instead of writing to a concrete implementation of an array or list, instead to write to the _adapters_ of these, in C, which can be more direct for C++, with C++'s great account of, "Abstraction", for the abstract and the concrete, and that anything's both abstract and concrete. C and C++ are different accounts: they're also together an account. Then, the resulting artifacts: has that C++ can link as it were to the C symbols, and even the C can link as it were to name-mangled C++, not that anybody ever does that since it involves the model in the run-time their interpretation, point being libraries to be interoperable with both C and C++ have C exports, then that it's to be expected that C++ for example can deal with the allocator or I/O stream, wrapping it into the C++ from a C way that must be contrived. Then, here C and C++ are always considered "C/C++", since, the implementations have largely agreed about the object-files and the libraries, that it's so.
Re: Inversion-of-control and dependency-injection in C
Author: bartc
Date: Wed, 18 Nov 2026 13:18
Date: Wed, 18 Nov 2026 13:18
117 lines
7404 bytes
7404 bytes
On 18/11/2026 12:13, Ross Finlayson wrote: > On 11/13/2026 08:54 AM, David Brown wrote: >> His posts are not written by AI - no AI writes that badly. And it is >> not so void of meaning and grammar that it is randomly generated. Ross >> has written posts in this style for many years in several Usenet groups. >> I find it hard to believe that someone would spend so much time and >> effort for a joke. >> > > Then, in another thread, bringing it back here: > > >> Here then for example, what I'm trying to figure out is basically > >> how to make for C what's in C++ without being in C++ that's yet > >> readily adaptable for calling and being called from and into C++ > >> from C. Like, for example, "sequence" or "iter", and "lister" > >> and the like, then for something like "C11 _Generic", making accounts > >> of generics the types in C vis-a-vis the polymorphic class model > >> in C++, about "sized" or accounts like "characteristics" of access > >> of arrays, pointer-offsets, lists, otherwise the usual things, > >> "holders", "getters and setters", then about "libraries" and > >> "components", after things like "success_t, error_t, and return_t, > >> for context_t", definitions of the patterns, that would be generally > >> suitable for writing libraries in C and having them callable and > >> calling to and from C++, these are the kinds of things I'm liking > >> to figure out. > >> > >> > >> Like for example about how to pass an allocator into C, or making > >> access of ctx_new/ctx_del or ctx_init/ctx_fini, those being about > >> storage or lifetime and ownership and responsibility, then for > >> things like "emit_log" and "emit_metric" and "emit_dump", these > >> are the kinds of things that later always live in any sort of > >> application framework, for making good-style. > >> > > > > Why not just write : > > > > """ > > How do I write C++ code in C? > > """ > > > > The answer then would be, you don't. Write C++ code in C++. Write C > > code in C. > > > > > Here the points under consideration are that C++ has some relevant > constructs that to use the same patterns in C, then to make for > the _interoperability_, has for example that libraries of most > any usual sort result their symbols, those being of C, or as after > name-mangling (a convention of expressing the namespaces and constructs > encoding the names/symbols as C defines for what C++ models, > name-mangling, where "the mangle" is a steam-press for the ironing > of sheets, where the common meaning is "fold, spindle, and mutilate"), > there's that "writing C++ in C", is to make it adapt-able. That paragraph should be taken out and shot. Together with most other gibberish you write. Are you asking a question here? Why are you posting this; what response are you after? Or maybe you enjoy regurgitating random facts in as incomprehensible a manner as possible. Or is your aim just to provoke reactions like this? > > Then, other accounts involve the system, for example malloc/free, > vis-a-vis, allocators, and that C++'s account of new/delete, > has also an account of pretty much every constructor allowing > the passing of an allocator, for example about free-lists/arenas/slabs, > about how to make a _pattern_ so that either the library interface > signature has function-pointers for acquire-release, or, for example, > there's a convention where each process/thread has a global-variable > (called thread-local in a thread, global to the thread) with function > pointers for acquire/release. > > It's similar with stdio, or for example loggers, usually considered > "static" (or extern) to the process to result a global entry-point > for the rest of the routine, or, what makes for that it gets passed > to every library-function or installed in the context passsed to every > library function, about what aren't "classes" and "instances" like in > C++ which is defined in the language, _yet so model those_, why it's a > thing. > > Other examples of accounts for example make for list-adapters or > iterators or accounts of sequences then about treating arrays and > lists as the same (while they have different characteristics of > access, the "access-patternry"), then for example about associative > arrays and sets and the like then into traversals for trees and graphs > and the like, where for example many "loosely-typed" languages of the > day (like JavaScript, Python, ...) have that's _default_ with the > "slots" the associative-array, vis-a-vis something like "the shell > language" and accounts of attributes, and behaviors for arrays and > associative-arrays, those being considered general. So, the idea is > that something like C11 has something like "_Generic" keyword to employ, > that instead of writing to a concrete implementation of > an array or list, instead to write to the _adapters_ of these, > in C, which can be more direct for C++, with C++'s great account of, > "Abstraction", for the abstract and the concrete, and that anything's > both abstract and concrete. > > > C and C++ are different accounts: they're also together an account. > Then, the resulting artifacts: has that C++ can link as it were > to the C symbols, and even the C can link as it were to name-mangled > C++, not that anybody ever does that since it involves the model in > the run-time their interpretation, point being libraries to be > interoperable with both C and C++ have C exports, then that it's > to be expected that C++ for example can deal with the allocator > or I/O stream, wrapping it into the C++ from a C way that must be > contrived. Maybe you should write a book. It would simultaneously be useful as a door-stop, and a cure for insomnia.
Re: Inversion-of-control and dependency-injection in C
Author: Ross Finlayson
Date: Wed, 18 Nov 2026 14:01
Date: Wed, 18 Nov 2026 14:01
149 lines
8774 bytes
8774 bytes
On 11/18/2026 05:18 AM, bartc wrote: > On 18/11/2026 12:13, Ross Finlayson wrote: >> On 11/13/2026 08:54 AM, David Brown wrote: >>> His posts are not written by AI - no AI writes that badly. And it is >>> not so void of meaning and grammar that it is randomly generated. Ross >>> has written posts in this style for many years in several Usenet groups. >>> I find it hard to believe that someone would spend so much time and >>> effort for a joke. >>> >> >> Then, in another thread, bringing it back here: >> >> >> Here then for example, what I'm trying to figure out is basically >> >> how to make for C what's in C++ without being in C++ that's yet >> >> readily adaptable for calling and being called from and into C++ >> >> from C. Like, for example, "sequence" or "iter", and "lister" >> >> and the like, then for something like "C11 _Generic", making accounts >> >> of generics the types in C vis-a-vis the polymorphic class model >> >> in C++, about "sized" or accounts like "characteristics" of access >> >> of arrays, pointer-offsets, lists, otherwise the usual things, >> >> "holders", "getters and setters", then about "libraries" and >> >> "components", after things like "success_t, error_t, and return_t, >> >> for context_t", definitions of the patterns, that would be generally >> >> suitable for writing libraries in C and having them callable and >> >> calling to and from C++, these are the kinds of things I'm liking >> >> to figure out. >> >> >> >> >> >> Like for example about how to pass an allocator into C, or making >> >> access of ctx_new/ctx_del or ctx_init/ctx_fini, those being about >> >> storage or lifetime and ownership and responsibility, then for >> >> things like "emit_log" and "emit_metric" and "emit_dump", these >> >> are the kinds of things that later always live in any sort of >> >> application framework, for making good-style. >> >> >> > >> > Why not just write : >> > >> > """ >> > How do I write C++ code in C? >> > """ >> > >> > The answer then would be, you don't. Write C++ code in C++. Write C >> > code in C. >> > >> >> >> Here the points under consideration are that C++ has some relevant >> constructs that to use the same patterns in C, then to make for >> the _interoperability_, has for example that libraries of most >> any usual sort result their symbols, those being of C, or as after >> name-mangling (a convention of expressing the namespaces and constructs >> encoding the names/symbols as C defines for what C++ models, >> name-mangling, where "the mangle" is a steam-press for the ironing >> of sheets, where the common meaning is "fold, spindle, and mutilate"), >> there's that "writing C++ in C", is to make it adapt-able. > > That paragraph should be taken out and shot. > > Together with most other gibberish you write. > > Are you asking a question here? Why are you posting this; what response > are you after? > > Or maybe you enjoy regurgitating random facts in as incomprehensible a > manner as possible. > > Or is your aim just to provoke reactions like this? > >> >> Then, other accounts involve the system, for example malloc/free, >> vis-a-vis, allocators, and that C++'s account of new/delete, >> has also an account of pretty much every constructor allowing >> the passing of an allocator, for example about free-lists/arenas/slabs, >> about how to make a _pattern_ so that either the library interface >> signature has function-pointers for acquire-release, or, for example, >> there's a convention where each process/thread has a global-variable >> (called thread-local in a thread, global to the thread) with function >> pointers for acquire/release. >> >> It's similar with stdio, or for example loggers, usually considered >> "static" (or extern) to the process to result a global entry-point >> for the rest of the routine, or, what makes for that it gets passed >> to every library-function or installed in the context passsed to every >> library function, about what aren't "classes" and "instances" like in >> C++ which is defined in the language, _yet so model those_, why it's a >> thing. >> >> Other examples of accounts for example make for list-adapters or >> iterators or accounts of sequences then about treating arrays and >> lists as the same (while they have different characteristics of >> access, the "access-patternry"), then for example about associative >> arrays and sets and the like then into traversals for trees and graphs >> and the like, where for example many "loosely-typed" languages of the >> day (like JavaScript, Python, ...) have that's _default_ with the >> "slots" the associative-array, vis-a-vis something like "the shell >> language" and accounts of attributes, and behaviors for arrays and >> associative-arrays, those being considered general. So, the idea is >> that something like C11 has something like "_Generic" keyword to employ, >> that instead of writing to a concrete implementation of >> an array or list, instead to write to the _adapters_ of these, >> in C, which can be more direct for C++, with C++'s great account of, >> "Abstraction", for the abstract and the concrete, and that anything's >> both abstract and concrete. >> >> >> C and C++ are different accounts: they're also together an account. >> Then, the resulting artifacts: has that C++ can link as it were >> to the C symbols, and even the C can link as it were to name-mangled >> C++, not that anybody ever does that since it involves the model in >> the run-time their interpretation, point being libraries to be >> interoperable with both C and C++ have C exports, then that it's >> to be expected that C++ for example can deal with the allocator >> or I/O stream, wrapping it into the C++ from a C way that must be >> contrived. > Maybe you should write a book. It would simultaneously be useful as a > door-stop, and a cure for insomnia. > That's hilarious. I already have several 1,000's convenient door-stops, though it's called "a library", and I read them, too. Don't make me laugh. I have a habit of neither snipping nor top-posting nor inserting, since it might be considered rude. Also it's so that then I can just extract the passages from some 10,000's essays of a sort, since it's a linear narrative itself. "Essays", are as since, for example, Montaigne: whose "Essais", became the model for discursive writing, in the 1400's, for example about essays and the di-alectic. The other day there was a news article, something like "Von Plato used A.I. to finally parse Goedel's manuscript notes and found a bunch of un-known proofs", where something like Euler's or Leibniz' volumes are on the order of 40,000 pages apiece, outside their usual "canon" of well-known works on mathematics, about things like Leibniz-studies. How about this: how do you like to write C, in a world of C and C++? Thanks for writing.
Re: Inversion-of-control and dependency-injection in C
Author: Ross Finlayson
Date: Wed, 18 Nov 2026 19:58
Date: Wed, 18 Nov 2026 19:58
3376 lines
122335 bytes
122335 bytes
On 11/18/2026 06:01 AM, Ross Finlayson wrote:
> On 11/18/2026 05:18 AM, bartc wrote:
>> On 18/11/2026 12:13, Ross Finlayson wrote:
>>> On 11/13/2026 08:54 AM, David Brown wrote:
>>>> His posts are not written by AI - no AI writes that badly. And it is
>>>> not so void of meaning and grammar that it is randomly generated. Ross
>>>> has written posts in this style for many years in several Usenet
>>>> groups.
>>>> I find it hard to believe that someone would spend so much time and
>>>> effort for a joke.
>>>>
>>>
>>> Then, in another thread, bringing it back here:
>>>
>>> >> Here then for example, what I'm trying to figure out is basically
>>> >> how to make for C what's in C++ without being in C++ that's yet
>>> >> readily adaptable for calling and being called from and into C++
>>> >> from C. Like, for example, "sequence" or "iter", and "lister"
>>> >> and the like, then for something like "C11 _Generic", making
>>> accounts
>>> >> of generics the types in C vis-a-vis the polymorphic class model
>>> >> in C++, about "sized" or accounts like "characteristics" of access
>>> >> of arrays, pointer-offsets, lists, otherwise the usual things,
>>> >> "holders", "getters and setters", then about "libraries" and
>>> >> "components", after things like "success_t, error_t, and return_t,
>>> >> for context_t", definitions of the patterns, that would be generally
>>> >> suitable for writing libraries in C and having them callable and
>>> >> calling to and from C++, these are the kinds of things I'm liking
>>> >> to figure out.
>>> >>
>>> >>
>>> >> Like for example about how to pass an allocator into C, or making
>>> >> access of ctx_new/ctx_del or ctx_init/ctx_fini, those being about
>>> >> storage or lifetime and ownership and responsibility, then for
>>> >> things like "emit_log" and "emit_metric" and "emit_dump", these
>>> >> are the kinds of things that later always live in any sort of
>>> >> application framework, for making good-style.
>>> >>
>>> >
>>> > Why not just write :
>>> >
>>> > """
>>> > How do I write C++ code in C?
>>> > """
>>> >
>>> > The answer then would be, you don't. Write C++ code in C++. Write C
>>> > code in C.
>>> >
>>>
>>>
>>> Here the points under consideration are that C++ has some relevant
>>> constructs that to use the same patterns in C, then to make for
>>> the _interoperability_, has for example that libraries of most
>>> any usual sort result their symbols, those being of C, or as after
>>> name-mangling (a convention of expressing the namespaces and constructs
>>> encoding the names/symbols as C defines for what C++ models,
>>> name-mangling, where "the mangle" is a steam-press for the ironing
>>> of sheets, where the common meaning is "fold, spindle, and mutilate"),
>>> there's that "writing C++ in C", is to make it adapt-able.
>>
>> That paragraph should be taken out and shot.
>>
>> Together with most other gibberish you write.
>>
>> Are you asking a question here? Why are you posting this; what response
>> are you after?
>>
>> Or maybe you enjoy regurgitating random facts in as incomprehensible a
>> manner as possible.
>>
>> Or is your aim just to provoke reactions like this?
>>
>>>
>>> Then, other accounts involve the system, for example malloc/free,
>>> vis-a-vis, allocators, and that C++'s account of new/delete,
>>> has also an account of pretty much every constructor allowing
>>> the passing of an allocator, for example about free-lists/arenas/slabs,
>>> about how to make a _pattern_ so that either the library interface
>>> signature has function-pointers for acquire-release, or, for example,
>>> there's a convention where each process/thread has a global-variable
>>> (called thread-local in a thread, global to the thread) with function
>>> pointers for acquire/release.
>>>
>>> It's similar with stdio, or for example loggers, usually considered
>>> "static" (or extern) to the process to result a global entry-point
>>> for the rest of the routine, or, what makes for that it gets passed
>>> to every library-function or installed in the context passsed to every
>>> library function, about what aren't "classes" and "instances" like in
>>> C++ which is defined in the language, _yet so model those_, why it's a
>>> thing.
>>>
>>> Other examples of accounts for example make for list-adapters or
>>> iterators or accounts of sequences then about treating arrays and
>>> lists as the same (while they have different characteristics of
>>> access, the "access-patternry"), then for example about associative
>>> arrays and sets and the like then into traversals for trees and graphs
>>> and the like, where for example many "loosely-typed" languages of the
>>> day (like JavaScript, Python, ...) have that's _default_ with the
>>> "slots" the associative-array, vis-a-vis something like "the shell
>>> language" and accounts of attributes, and behaviors for arrays and
>>> associative-arrays, those being considered general. So, the idea is
>>> that something like C11 has something like "_Generic" keyword to employ,
>>> that instead of writing to a concrete implementation of
>>> an array or list, instead to write to the _adapters_ of these,
>>> in C, which can be more direct for C++, with C++'s great account of,
>>> "Abstraction", for the abstract and the concrete, and that anything's
>>> both abstract and concrete.
>>>
>>>
>>> C and C++ are different accounts: they're also together an account.
>>> Then, the resulting artifacts: has that C++ can link as it were
>>> to the C symbols, and even the C can link as it were to name-mangled
>>> C++, not that anybody ever does that since it involves the model in
>>> the run-time their interpretation, point being libraries to be
>>> interoperable with both C and C++ have C exports, then that it's
>>> to be expected that C++ for example can deal with the allocator
>>> or I/O stream, wrapping it into the C++ from a C way that must be
>>> contrived.
>> Maybe you should write a book. It would simultaneously be useful as a
>> door-stop, and a cure for insomnia.
>>
>
> That's hilarious. I already have several 1,000's convenient door-stops,
> though it's called "a library", and I read them, too. Don't make me laugh.
>
> I have a habit of neither snipping nor top-posting nor inserting,
> since it might be considered rude. Also it's so that then I can
> just extract the passages from some 10,000's essays of a sort,
> since it's a linear narrative itself.
>
> "Essays", are as since, for example, Montaigne: whose "Essais",
> became the model for discursive writing, in the 1400's, for example
> about essays and the di-alectic.
>
>
> The other day there was a news article, something like "Von Plato
> used A.I. to finally parse Goedel's manuscript notes and found a
> bunch of un-known proofs", where something like Euler's or Leibniz'
> volumes are on the order of 40,000 pages apiece, outside their
> usual "canon" of well-known works on mathematics, about things
> like Leibniz-studies.
>
>
> How about this: how do you like to write C, in a world of C and C++?
>
>
> Thanks for writing.
>
>
>
>
>
So, ..., since I know how much you like "A.I. slop", I went and found
some, though, of course let this be a sort of, "trigger warning", so
you can take it or leave it, or read on, if you dare.
"When all there is is slop, all you need is a mop."
"Look at the bones!"
[ RF ]
C _Generic _Offsetof _Alignas
[ GG ]
_Generic, offsetof (note: not _Offsetof in standard C), and _Alignas are
standard C11 features used for compile-time type dispatch, memory layout
inspection, and explicit memory alignment.
Here is how each keyword or macro operates in modern C, along with
idiomatic usage patterns.
1. _Generic (C11 Type-Generic Expressions)
_Generic provides compile-time polymorphism by selecting an expression
based on the type of a controlling expression. The controlling
expression is not evaluated at runtime, and only the matching branch is
compiled.
• Syntax: _Generic(controlling-expression, type1: expr1, type2: expr2,
default: default_expr)
• Type Matching Rules: Lvalue conversion is applied to the controlling
expression. This strips top-level qualifiers (const, volatile, _Atomic)
and decays arrays to pointers and functions to function pointers.
• Common Use Case: Creating overloaded macro APIs that dispatch to
type-specific functions without runtime overhead.
c
#include <stdio.h>
void print_i(int x) { printf("int: %d\n", x); }
void print_d(double x) { printf("double: %f\n", x); }
void print_p(const void* p) { printf("ptr: %p\n", p); }
#define print_val(X) _Generic((X), \
int: print_i, \
double: print_d, \
default: print_p \
)(X)
Use code with caution.
2. offsetof (Standard <stddef.h> Macro)
There is no _Offsetof keyword in the C standard; the standard construct
is the lowercase macro offsetof, defined in <stddef.h> (often backed by
the compiler intrinsic __builtin_offsetof).
• Syntax: offsetof(type, member-designator)
• Return Type: Evaluates to an integer constant expression of type
size_t representing the byte offset from the start of type to the
specified struct or union member.
• Constraints: It cannot be used on bit-fields, and type must be a
complete struct or union type.
• Common Use Case: Intrusive data structures (container_of pattern) and
compile-time layout verification via _Static_assert.
c
#include <stddef.h>
#include <stdint.h>
typedef struct {
uint8_t tag;
uint64_t payload;
} Packet;
// Compile-time layout check
_Static_assert(offsetof(Packet, payload) == 8, "Unexpected struct padding");
// Intrusive container recovery
#define container_of(ptr, type, member) \
((type*)((char*)(ptr) - offsetof(type, member)))
Use code with caution.
3. _Alignas (C11 Alignment Specifier)
_Alignas forces a variable or struct member to be aligned to a specific
byte boundary, overriding its natural alignment. In C11, <stdalign.h>
provides the convenience macro alignas (which becomes a direct keyword
in C23).
• Syntax: _Alignas(constant-expression) or _Alignas(type-name)
• Constraints:
• The requested alignment must be a power of two.
• You can only increase alignment (over-align); requesting an alignment
stricter than the type's natural alignment is valid, while requesting a
weaker alignment is a constraint violation.
• It cannot be applied to typedef declarations, bit-fields, function
parameters, or variables with register storage class.
• Common Use Case: Preventing false sharing across CPU cache lines
(typically 64 bytes) or aligning buffers for SIMD vector loads/stores
and page boundaries.
c
#include <stddef.h>
#include <stdint.h>
// Align a shared counter to a 64-byte cache line
typedef struct {
_Alignas(64) uint64_t count;
_Alignas(64) uint64_t errors;
} ThreadStats;
// Align a stack buffer to a 32-byte AVX2 boundary
void process_block(void) {
_Alignas(32) uint8_t buf[256];
(void)buf;
}
Use code with caution.
Quick Comparison
Feature Standard Name Header Required Evaluated At Primary Role
Type Dispatch _Generic (keyword) None Compile-time Static polymorphism
in macros
Member Offset offsetof (macro) <stddef.h> Compile-time Struct layout
math & container_of
Alignment _Alignas (keyword) None (<stdalign.h> for alignas)
Compile-time Cache-line, SIMD, and page alignment
Are you combining these to build intrusive data structures,
SIMD/cache-aligned buffers, or type-safe macro wrappers? Share what
you're designing and I can put together a tailored pattern.
[ RF ]
Thanks. Hello Google Gemini, this is Ross A. Finlayson, I call you "GG"
and answer to "RF". Today I'm looking into these features of C (C11,
-std=C11) about making for accounts of the polymorphic in C, for making
accounts of generic list or container adapters, with a uniform source
for re-using the source code of algorithms on them, about a sort of
minimal account of polymorphism in generics, then writing algorithms on
them without exploding on the source side.
[ GG ]
Good to talk with you again, RF. Hey Ross, GG here—noted on both names.
Building generic containers and reusable algorithms in -std=c11 without
exploding your source code via massive X-macros or ## token-pasting
bloat comes down to separating layout metadata from algorithmic logic.
By combining _Generic, offsetof, and _Alignas (paired with _Alignof),
you can write one compiled function per algorithm (type-erased via void*
and byte-strides) while keeping a 100% type-safe front-end that passes
zero-cost layout descriptors at compile time.
The Core Pattern: Type-Erased Core + _Generic Front-End
Instead of generating N copies of sort(), binary_search(), or
list_push() for N types, you pass a lightweight, compile-time TypeSpec
struct (or register values) describing the element's size, alignment,
and comparator. _Generic automatically resolves this descriptor from the
pointer or container type passed by the caller.
1. Describing Element Layout (offsetof, _Alignof, _Alignas)
When building a generic container (like a dynamic array, ring buffer, or
intrusive list adapter), the core runtime only needs three pieces of
metadata to manipulate raw bytes safely:
• Stride (size): sizeof(T)
• Alignment (align): _Alignof(T) (or a stricter _Alignas requirement)
• Key/Link Offset (offset): offsetof(T, member) for intrusive nodes or
sorting by a struct field.
c
#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
typedef int (*CmpFn)(const void* a, const void* b);
typedef struct {
size_t size;
size_t align;
size_t key_offset;
CmpFn cmp;
} TypeMeta;
// Helper macro to construct compile-time TypeMeta
#define TYPE_META(T, cmp_fn) \
((TypeMeta){ .size = sizeof(T), .align = _Alignof(T), .key_offset = 0,
.cmp = (cmp_fn) })
#define FIELD_META(T, member, cmp_fn) \
((TypeMeta){ \
.size = sizeof(T), \
.align = _Alignof(T), \
.key_offset = offsetof(T, member), \
.cmp = (cmp_fn) \
})
Use code with caution.
2. Writing the Single-Source Algorithm
Your algorithm is written once in standard C. Using key_offset allows
the same algorithm to sort or search primitives directly (key_offset ==
0) or structs by an internal field (key_offset == offsetof(...)) without
needing custom struct-specific comparators.
c
// Single compiled implementation for all types
void* algo_bsearch(
const void* key,
const void* base,
size_t count,
TypeMeta meta
) {
const uint8_t* bytes = (const uint8_t*)base;
size_t low = 0;
size_t high = count;
while (low < high) {
size_t mid = low + (high - low) / 2;
const void* elem = bytes + (mid * meta.size);
const void* elem_key = (const uint8_t*)elem + meta.key_offset;
int res = meta.cmp(key, elem_key);
if (res == 0) {
return (void*)elem;
}
if (res < 0) {
high = mid;
} else {
low = mid + 1;
}
}
return NULL;
}
Use code with caution.
3. Binding with _Generic (Zero Source Explosion)
_Generic acts as the static dispatch table. Because C11 evaluates only
the matched branch, you can enforce type safety between the key pointer
and the base array pointer at compile time.
c
int cmp_int(const void* a, const void* b) {
int ia = *(const int*)a;
int ib = *(const void*)b;
return (ia > ib) - (ia < ib);
}
int cmp_u64(const void* a, const void* b) {
uint64_t ua = *(const uint64_t*)a;
uint64_t ub = *(const uint64_t*)b;
return (ua > ub) - (ua < ub);
}
// Type-safe generic wrapper: deduces TypeMeta from the array pointer
#define find_elem(key_ptr, array_ptr, count) _Generic((array_ptr), \
int*: algo_bsearch( \
(const int*)(key_ptr), \
(array_ptr), \
(count), \
TYPE_META(int, cmp_int) \
), \
const int*: algo_bsearch( \
(const int*)(key_ptr), \
(array_ptr), \
(count), \
TYPE_META(int, cmp_int) \
), \
uint64_t*: algo_bsearch( \
(const uint64_t*)(key_ptr), \
(array_ptr), \
(count), \
TYPE_META(uint64_t, cmp_u64) \
) \
)
Use code with caution.
4. Generic Container Header with _Alignas & offsetof
When building a generic container (e.g., an intrusive or contiguous pool
adapter) where a uniform header precedes arbitrary payload T,
_Alignas(max_align_t) guarantees that the payload immediately following
the header obeys strict aliasing and hardware alignment rules for any
standard C type.
c
#include <stdalign.h>
typedef struct {
size_t count;
size_t capacity;
TypeMeta meta;
// Ensures trailing payload is aligned for any standard type
_Alignas(max_align_t) uint8_t data[];
} GenericVec;
// Recover the container header from a typed payload pointer
#define vec_header(typed_ptr) \
((GenericVec*)((uint8_t*)(typed_ptr) - offsetof(GenericVec, data)))
Use code with caution.
Because GenericVec uses a flexible array member (data[]) aligned to
max_align_t, user code can hold a plain typed pointer like int* items or
Packet* items while the container metadata lives cleanly behind
items[-1] (via offsetof(GenericVec, data)).
Architectural Trade-offs
Approach Binary Footprint Compile Time Type Safety Debuggability
Token-Pasting (##) Large (code bloat per T) Slow High Poor (macro
expansion noise)
Raw void* Macros Small (1 copy) Fast Low (silent pointer bugs) Good
_Generic + TypeMeta Small (1 copy) Fast High (checked at dispatch) High
(real functions)
Key Constraints to Watch in -std=c11
• Qualifier Stripping: _Generic strips top-level const from the
controlling expression, not from pointed-to types. int* and const int*
are distinct associations in _Generic.
• No Function Pointer Decay in Controlling Expression: Passing an array
int arr[10] as the controlling expression decays it to int*, which
matches int* cleanly.
• Strict Aliasing on Swaps: Inside generic algorithms that swap or move
elements in void* buffers, always use memcpy with a small stack scratch
buffer (_Alignas(max_align_t) uint8_t tmp[256]) rather than casting to
uint64_t*, avoiding undefined behavior under -O2/-O3.
Would you like to focus next on intrusive list/node adapters (using
offsetof link hooks across heterogeneous structs) or contiguous
container adapters (like a GenericVec / ring buffer where T* is the user
handle)?
[ RF ]
Thanks GG. Sometimes I'm using arrays of known and fixed length at
compile time, so I'd want to put them in the signatures, in both return
values and parameters, like "char[PAGE_SIZE] next_buf(seq_t s)" after
building seq_t as "specialized" to "char[PAGE_SIZE]", for example. Then,
about polymorphic types, and "compile-time" and "run-time", has for
example that a sort of union of the types can wrap the characteristics,
like "Sized", "Array", "List", making unions with those as members, then
in a _Generic dispatch block, passing the unions in as accordingly
getting the relevant dispath functions, while carrying the type, at
compile-time. Then for run-time, and polymorphism, it would involve
run-time-type-identification, which in C is considered to be as of a
type-tag in the structure/union, then to make the code implicit or
explicit in that, about generics at compile-time and polymorphism at
run-time.
[ GG ]
That distinction between compile-time generics (type-carrying wrappers
resolved via _Generic) and runtime polymorphism (tagged unions /
vtable-like RTTI resolved via switch or function pointers) hits the
exact structural boundary of what C11 can express cleanly without source
bloat.
There are two critical C language mechanics at play here: how C treats
fixed-size arrays in function signatures, and how to unify compile-time
trait unions with runtime tagged dispatch.
1. Fixed-Length Arrays in Signatures (char[PAGE_SIZE])
In C, functions cannot return a raw array type directly (char[PAGE_SIZE]
fn(...) is a syntax/constraint error), and a parameter declared as char
buf[PAGE_SIZE] automatically decays to char* (losing its compile-time
bound unless you use char buf[static PAGE_SIZE] or a pointer-to-array
char (*buf)[PAGE_SIZE]).
The C11 Idiom: Wrap the fixed-size array inside a lightweight struct or
union (often called a "box" or "slice/page" type).
• Value Semantics: A struct wrapping char data[PAGE_SIZE] can be passed
by value and returned by value in C11.
• Zero Overhead: Because it is a single-member struct, compilers pass
and return it directly in registers or via the caller's hidden return
slot (NRVO/SROA) with zero extra indirection.
• Type Identity: Each size or element type gets a distinct struct type
(PageBuf_4096), so _Generic can distinguish PageBuf_4096 from
PageBuf_512 at compile time.
c
#include <stddef.h>
#include <stdalign.h>
#define PAGE_SIZE 4096
// Distinct compile-time type carrying both element type and fixed extent
typedef struct {
_Alignas(max_align_t) char data[PAGE_SIZE];
} PageBuf;
// Valid C11 signature: takes and returns fixed-size buffer by value
PageBuf next_buf(void* seq_state);
Use code with caution.
2. Compile-Time Generics: Trait-Carrying Unions & _Generic
Your idea of wrapping structural characteristics (Sized, Array, List) in
a union/struct to carry type metadata at compile time works remarkably
well in C11.
Instead of using a union for runtime storage here, you use a
compile-time carrier struct/union (or phantom-typed wrapper) whose sole
purpose is to give _Generic a distinct type signature to match on, while
holding the underlying view or iterator state.
Pattern: Trait-Tagged Compile-Time Wrappers
Suppose you have different container views (ArrayView_int, ListView_int,
PageSeq). Each exposes its structural traits through distinct wrapper
types or a macro that inspects the wrapper type via _Generic:
c
// Compile-time trait wrappers for int sequences
typedef struct {
int* ptr;
size_t len;
} SizedArray_int;
typedef struct {
void* head;
size_t node_offset;
} IntrusiveList_int;
typedef struct {
PageBuf (*next)(void* ctx);
void* ctx;
} FixedSeq_Page;
// Compile-time trait query via _Generic
#define has_random_access(seq) _Generic((seq), \
SizedArray_int: 1, \
IntrusiveList_int: 0, \
FixedSeq_Page: 0 \
)
// Compile-time algorithm dispatch based on structural capability
#define seq_advance(seq, n) _Generic((seq), \
SizedArray_int: advance_array_int, \
IntrusiveList_int: advance_list_int, \
FixedSeq_Page: advance_page_seq \
)((seq), (n))
Use code with caution.
• Zero Runtime Tag: Neither SizedArray_int nor FixedSeq_Page stores a
type tag byte in memory.
• Compile-Time Resolution: _Generic selects advance_array_int (O(1)
pointer addition) versus advance_list_int (O(n) pointer chasing) purely
from the static type of seq.
3. Runtime Polymorphism: Tagged Unions (Explicit RTTI)
When the concrete container or sequence type isn't known until runtime
(e.g., a function receiving a heterogeneous stream or choosing between a
SizedArray and a LinkedList based on input data), compile-time _Generic
alone cannot dispatch. You cross into runtime polymorphism by adding an
explicit enum tag alongside the union of representations.
Bridging Compile-Time and Runtime Uniformly
You can keep your algorithm source uniform by having one
runtime-polymorphic AnySeq tagged union whose branches delegate to the
exact same concrete inline/static functions used by your _Generic
compile-time paths.
c
typedef enum {
SEQ_KIND_ARRAY_INT,
SEQ_KIND_LIST_INT,
SEQ_KIND_FIXED_PAGE
} SeqKind;
// Runtime polymorphic container/sequence
typedef struct {
SeqKind kind;
union {
SizedArray_int array;
IntrusiveList_int list;
FixedSeq_Page page_seq;
} as;
} AnySeq;
// Constructor lifted automatically via _Generic (compile-time ->
runtime bridge)
static inline AnySeq make_any_from_array(SizedArray_int a) {
return (AnySeq){ .kind = SEQ_KIND_ARRAY_INT, .as.array = a };
}
static inline AnySeq make_any_from_list(IntrusiveList_int l) {
return (AnySeq){ .kind = SEQ_KIND_LIST_INT, .as.list = l };
}
#define as_any_seq(concrete_seq) _Generic((concrete_seq), \
SizedArray_int: make_any_from_array, \
IntrusiveList_int: make_any_from_list \
)(concrete_seq)
Use code with caution.
Unified Algorithm Dispatch
Now, a single advance() macro handles both statically known types (zero
overhead, direct call) and runtime-polymorphic AnySeq values (single
switch on kind):
c
static inline AnySeq advance_any_seq(AnySeq s, size_t n) {
switch (s.kind) {
case SEQ_KIND_ARRAY_INT:
s.as.array = advance_array_int(s.as.array, n);
break;
case SEQ_KIND_LIST_INT:
s.as.list = advance_list_int(s.as.list, n);
break;
case SEQ_KIND_FIXED_PAGE:
s.as.page_seq = advance_page_seq(s.as.page_seq, n);
break;
}
return s;
}
// Unified front-end: static dispatch for concrete types, RTTI for AnySeq
#define advance(seq, n) _Generic((seq), \
SizedArray_int: advance_array_int, \
IntrusiveList_int: advance_list_int, \
FixedSeq_Page: advance_page_seq, \
AnySeq: advance_any_seq \
)((seq), (n))
Use code with caution.
Summary of the Two Layers
Layer Mechanism Memory Overhead Dispatch Cost Best For
Compile-Time Generics Typed struct wrappers + _Generic 0 bytes (no tag)
0 cycles (inlined/direct call) Known fixed buffers (PageBuf), static
pipelines, trait selection
Runtime Polymorphism enum tag + union (AnySeq) sizeof(enum) + alignment
padding 1 branch (switch or fn ptr) Heterogeneous collections, dynamic
plugin/protocol streams
By keeping the core step functions (advance_array_int, advance_list_int,
advance_page_seq) written once as plain static inline functions, both
the _Generic compile-time path and the AnySeq runtime switch share the
exact same algorithm logic without duplicating source code.
Would you like to explore how to generate or parameterize those typed
view structs cleanly for multiple element types (int, double, custom
structs) without macro clutter, or how to design vtable/function-pointer
interfaces when open extensibility is needed at runtime?
[ RF ]
Thanks GG. For my own purposes, I don't have very many types to
consider, then about notions like macros with label concatenation for
example that I'd be curious whether _Generic requires all of its
"target" identifiers to exist, in the case statement, vis-a-vis the
expression that's passed in, the match or as defaulting to the default
case. The reason I ask, is that then an overall macro of many
specializing types might use "##" label concatenation as for "#"
string-ification, to result then having empties except for what's
specialized, so the compiler would not error if there exist a matching
definition, else error thus for expanding the _Generic table of the
relevant type in action.
[ GG ]
You've spotted an important constraint in C11: every single association
in a _Generic selection list must be syntactically valid and have all
identifiers declared at the point of expansion, even in the branches
that are not selected.
Why Undeclared Identifiers Fail in _Generic
In C11 (ISO/IEC 9899:2011 §6.5.1.1), _Generic is a primary expression
parsed and type-checked by the compiler's front-end before selecting the
winning branch.
• What IS skipped: Evaluation of unselected expressions (no runtime side
effects) and type-checking of the outer expression against the
unselected branches (e.g., calling an unselected function with the wrong
argument types only triggers an error if the branch itself isn't a valid
expression on its own—though note that even validating each branch
expression requires every identifier inside it to be declared in scope).
• What is NOT skipped: Name lookup and syntax/semantic validation of
every type-name : assignment-expression pair in the _Generic list. If
foo_MyType is generated by ## concatenation inside a _Generic arm and
foo_MyType has not been declared, compilation fails immediately with an
undeclared identifier error, even if MyType was never passed to the macro.
How to Achieve "Empty Unless Specialized" in Standard C11
Since you only have a small set of types and want a master macro to
expand cleanly without requiring every type to implement every
operation, you can solve this in standard C11 using weak/fallback
declarations or header-driven X-macro registration rather than relying
on _Generic to ignore missing symbols.
Approach 1: Static Inline Fallback Stubs (Zero-Overhead Unspecialized
Catch-All)
If your ##-concatenated dispatch table references op_##T, you can
provide a generic fallback or a macro-generated "unspecialized" trap
function.
• If a type specializes op_MyType, it calls op_MyType.
• If a type is not specialized, you either route it to a universal void*
fallback or a trap function marked with a compile-time error attribute
(like GCC/Clang's __attribute__((error("not specialized"))) or a static
assertion).
c
#include <stddef.h>
// Universal fallback when a type has no specialized implementation
static inline void unspecialized_trap(void) {
// Traps at link/compile time if actually selected by _Generic
extern void error_operation_not_specialized_for_this_type(void);
error_operation_not_specialized_for_this_type();
}
Use code with caution.
Because _Generic only emits code/relocations for the selected branch,
referencing an undefined extern function inside an unselected branch
compiles and links cleanly! Only if you actually invoke the macro with
an unspecialized type does the linker (or optimizer) fail on the missing
symbol.
(Note: Every identifier in every branch is still properly declared via
that extern prototype, satisfying C11's front-end rules, while dead-code
elimination drops unselected branches completely.)
Approach 2: Explicit Trait Opt-In via Registration Macros (Cleanest for
Small Type Sets)
When you only have a handful of types (e.g., int, double, PageBuf), you
can maintain a single list of active types in a header using a macro
list (TYPES_LIST). Each type declares which operations it supports via a
small capability flag or macro, so _Generic only generates arms for
registered types:
c
// Define your small universe of types in one place
#define MY_TYPES(X) \
X(int) \
X(double) \
X(PageBuf)
// Generate forward declarations or _Generic arms uniformly
#define GENERATE_ARM(T) T: process_##T,
#define process(val) _Generic((val), \
MY_TYPES(GENERATE_ARM) \
default: unspecialized_trap \
)(val)
Use code with caution.
Here, ## (process_##T) expands cleanly across your known type set
without exploding the source code, and adding a new type later requires
adding just one X(NewType) line.
Key Takeaway on ## Inside _Generic
• Valid C11: Using ## to construct function names inside _Generic arms
(T: func_##T), provided every func_##T has a visible declaration (even
if it's a stub or an extern trap prototype).
• Invalid C11: Leaving a _Generic arm's expression blank (T: ,) or
referencing a func_##T that has no prototype anywhere in scope.
Would you like to see a complete minimal example combining the extern
link-time trap with ## concatenation so unspecialized types compile
silently when unused and produce a clear error when called?
[ RF ]
Thanks GG. Mostly I figure to make sequence adapters over arrays and
various accounts of prototypes of list, and for example about char* when
a C-string, basically that various specializations are to work off the
known bounds of the arrays and the like, when those are fixed-size, and
various adapters to lists, for example whether a null-link or a
reserved-link is the tail of the list, or for example where a "C-string"
is null-terminated or an account of data that's length-prefixed. Then,
back to about the declaring the array-size in the parameter list, I'm
under the impression that the signature parameters can be declared with
fixed-length arrays, like "f(char[16] name" if that's syntactical, then
as well for example "f(char[len] name, int n)". Then I'd be curious that
in _Generic those are simply broken out their cases, or as how the
expression in _Generic may be variadic itself, or the signature must be
the same length/parameter-count throughout.
[ GG ]
You've got two sharp C11 questions here: how array syntax works inside
function parameter lists (and how _Generic sees those types), and
whether _Generic branches can have different parameter counts or
variadic signatures.
1. Array Syntax in C11 Parameter Lists & How _Generic Sees Them
In C syntax, the array brackets go after the parameter identifier (char
name[16]), not before (char[16] name). Crucially, C adjusts array
parameters differently depending on whether you pass the array directly
or via a pointer-to-array:
Parameter Syntax Adjusted Type in C11 Preserves Size in _Generic?
void f(char name[16]) char* (decays to pointer) No — 16 is ignored by
the compiler; matches char*.
void f(char name[static 16]) char* (with non-null / ≥16 hint) No — still
char* to _Generic, though compilers warn on smaller arrays.
void f(size_t n, char name[n]) char* (VLA parameter; n must precede
name) No — decays to char*.
void f(char (*name)[16]) char (*)[16] (pointer to 16-char array) Yes —
char (*)[16] and char (*)[32] are distinct types in _Generic.
Why Pointer-to-Array (char (*)[16]) Matters for _Generic
When you pass &buf (where char buf[16];) to a macro, its type is char
(*)[16]. Unlike char buf[16] which decays to char* and loses its length,
char (*)[16] keeps the exact compile-time extent 16 intact in the type
system:
c
#include <stddef.h>
void handle_cstr(const char* s);
void handle_buf16(char (*buf)[16]);
void handle_buf64(char (*buf)[64]);
#define process_seq(x) _Generic((x), \
char*: handle_cstr, \
const char*: handle_cstr, \
char (*)[16]: handle_buf16, \
char (*)[64]: handle_buf64 \
)(x)
Use code with caution.
• Passing "hello" or char* p dispatches to handle_cstr (null-terminated
logic).
• Passing &fixed16 (where char fixed16[16];) dispatches to handle_buf16
(fixed-bound logic, where sizeof(*buf) is 16).
2. Different Parameter Counts & Variadic Expressions in _Generic
Yes — every branch in _Generic can evaluate to a completely different
expression or call a function with a different parameter count, because
_Generic simply selects one expression (assignment-expression) and
discards the others before checking call arguments.
There are two clean ways to write _Generic macros when your adapters
need different arguments (e.g., a null-terminated char* needs no length
argument, whereas a length-prefixed buffer or sentinel-terminated list
needs a length or sentinel parameter).
Pattern A: Variadic Macro (__VA_ARGS__) Forwarding
You can make the outer macro variadic (... / __VA_ARGS__) so that
_Generic selects the target function name, and __VA_ARGS__ forwards
whatever extra arguments that specific target function expects:
c
// Functions with DIFFERENT parameter counts!
size_t len_cstr(const char* s); // 1 argument
size_t len_bounded(const char* s, size_t max_len); // 2 arguments
size_t len_sentinel(const void* head, void* sentinel); // 2 arguments
// Variadic dispatch macro: each target function takes its own signature
#define seq_len(seq, ...) _Generic((seq), \
char*: len_cstr, \
const char*: len_cstr, \
BoundedStr: len_bounded, \
SentinelList: len_sentinel \
)((seq), ##__VA_ARGS__)
// Usage:
// seq_len(my_cstr); -> calls len_cstr(my_cstr)
// seq_len(my_bounded, 128); -> calls len_bounded(my_bounded, 128)
// seq_len(my_list, &SENTINEL_NODE); -> calls len_sentinel(my_list,
&SENTINEL_NODE)
Use code with caution.
(Note: In strict -std=c11 without GNU extensions, if you want to avoid
the , ##__VA_ARGS__ comma-swallowing extension when 0 extra args are
passed, you can pass (seq, __VA_ARGS__) directly inside each branch or
dispatch on argument count.)
Pattern B: Putting the Call Inside Each _Generic Arm
In C11, you do not have to put the (args) outside _Generic. You can
write the full function call—with completely different argument
lists—inside each branch:
c
#define seq_len_strict(seq, extra) _Generic((seq), \
char*: len_cstr((const char*)(seq)), \
const char*: len_cstr((const char*)(seq)), \
BoundedStr: len_bounded((seq), (extra)), \
SentinelList: len_sentinel((seq), (extra)) \
)
Use code with caution.
Here, len_cstr takes 1 argument and len_bounded takes 2 arguments. Even
though extra is passed to the macro, the char* branch ignores extra
completely, and C11 only type-checks the branch that matches seq.
(Caveat: if seq is char*, (seq) inside the BoundedStr branch still has
to pass basic semantic checks if (seq) is used directly without a
cast—which is why Pattern A selecting the function pointer first is
usually cleaner when argument types differ wildly.)
3. Unified Sequence Adapters: Null-Link, Reserved-Sentinel,
Length-Prefixed, and C-String
Combining pointer-to-array types with lightweight adapter structs lets
you represent all four sequence styles uniformly in C11:
c
// 1. Null-terminated C-string: plain `char*` / `const char*` (no
wrapper needed)
// 2. Fixed-size array: `char (*)[N]` or wrapped struct
typedef struct {
const char* ptr;
size_t len;
} LenSlice; // Length-prefixed / explicit-bound data
typedef struct Node {
struct Node* next;
void* payload;
} Node;
typedef struct {
Node* head;
const Node* tail_sentinel; // NULL for null-link, or &RESERVE_NODE for
sentinel-link
} ListAdapter;
Use code with caution.
With ListAdapter, both null-terminated lists (tail_sentinel = NULL) and
reserved-link / circular sentinel lists (tail_sentinel = &sentinel)
share the exact same traversal loop (while (cur !=
adapter.tail_sentinel)), while _Generic seamlessly routes char*, char
(*)[N], LenSlice, and ListAdapter to their matching step/length functions.
Would you like to see a strict -std=c11 (pedantically warning-free)
macro setup for handling 0 vs. N extra arguments in _Generic without
relying on GNU's , ##__VA_ARGS__ extension?
[ RF ]
Thanks GG. The fourth-form of the parameter-signature that preserves
type is what I'd noticed, then it's even a bit surprising that _Generic
can make for overloads including parameter-count, besides type, then
figuring there's a matching about the case-evaluation in the _Generic,
that it's figured that it's orderable according to the _Generic that
whatever's evaluated as to match makes matches. I'd look to definitely
avoid varargs when I'd just hope that _Generic can dispatch among
functions with differing parameter-counts.
[ GG ]
You can dispatch across both parameter count and parameter types in pure
-std=c11 without using C variadic functions (va_list) or GNU extensions.
The key distinction is between variadic macros (... / __VA_ARGS__)—which
are standard C99/C11 preprocessor token forwarding—and variadic
functions (int fn(int a, ...) ), which erase type safety at runtime.
Using preprocessor argument-counting with _Generic gives you 100% static
type-checking and fixed-arity function calls at zero runtime cost.
1. Why _Generic Alone Only Inspects One Expression
In standard C11, _Generic(controlling_expr, ...) takes exactly one
controlling expression. It cannot directly pattern-match on (arg1, arg2)
as a tuple.
• What _Generic checks: Only the type of controlling_expr.
• How arity + type overloading works: You use the preprocessor to count
the arguments passed to your macro (1 arg vs. 2 args), dispatch to
MACRO_1(a) or MACRO_2(a, b), and then run _Generic inside each
arity-specific macro.
2. Pure -std=c11 Arity + Type Overloading Pattern
Here is how you overload a single macro name (seq_find or seq_walk)
across both 1-argument calls (e.g., null-terminated char*, fixed-size
char (*)[16]) and 2-argument calls (e.g., raw pointer + explicit length,
or list head + sentinel node) in strict -std=c11:
c
#include <stddef.h>
// --- Concrete target functions with distinct arities and types ---
size_t len_cstr(const char* s); // 1 arg
size_t len_arr16(char (*buf)[16]); // 1 arg
size_t len_bounded(const char* s, size_t cap); // 2 args
size_t len_sentinel(const void* head, void* sentinel); // 2 args
// --- Standard C11 argument counter (supports 1 to 4 args) ---
#define GET_MACRO(_1, _2, _3, _4, NAME, ...) NAME
// --- Arity 1 dispatch ---
#define SEQ_LEN_1(a) _Generic((a), \
char*: len_cstr, \
const char*: len_cstr, \
char (*)[16]: len_arr16 \
)(a)
// --- Arity 2 dispatch ---
#define SEQ_LEN_2(a, b) _Generic((a), \
char*: len_bounded, \
const char*: len_bounded, \
const void*: len_sentinel, \
void*: len_sentinel \
)((a), (b))
// --- Unified public macro (dispatches by arity first, then by type) ---
#define seq_len(...) \
GET_MACRO(__VA_ARGS__, SEQ_LEN_4, SEQ_LEN_3, SEQ_LEN_2,
SEQ_LEN_1)(__VA_ARGS__)
Use code with caution.
How This Compiles
• seq_len(cstr) expands to SEQ_LEN_1(cstr) → len_cstr(cstr) (1 argument,
checked as const char*).
• seq_len(&buf16) expands to SEQ_LEN_1(&buf16) → len_arr16(&buf16) (1
argument, checked as char (*)[16]).
• seq_len(ptr, 64) expands to SEQ_LEN_2(ptr, 64) → len_bounded(ptr, 64)
(2 arguments, checked as (const char*, size_t)).
• seq_len(head, &END) expands to SEQ_LEN_2(head, &END) →
len_sentinel(head, &END) (2 arguments, checked as (const void*, void*)).
3. Dispatching on Both First and Second Argument Types
If a 2-argument call needs to distinguish (char*, size_t) from (char*,
const char* /* end_ptr */), you simply nest _Generic on the second
argument inside SEQ_LEN_2:
c
size_t len_ptr_size(const char* s, size_t n);
size_t len_ptr_end(const char* start, const char* end);
#define SEQ_LEN_2_CHARPTR(a, b) _Generic((b), \
size_t: len_ptr_size, \
int: len_ptr_size, \
const char*: len_ptr_end, \
char*: len_ptr_end \
)((a), (b))
#define SEQ_LEN_2(a, b) _Generic((a), \
char*: SEQ_LEN_2_CHARPTR((a), (b)), \
const char*: SEQ_LEN_2_CHARPTR((a), (b)), \
void*: len_sentinel((a), (b)) \
)
Use code with caution.
4. Important Caveat on _Generic Case Ordering
You mentioned _Generic being orderable: in C11 (§6.5.1.1), _Generic
associations are unordered set entries, not sequential if/else branches.
• No two type associations in the same _Generic block may specify
compatible types (e.g., having both int and signed int, or both char
(*)[16] and char (*)[16], is a compile-time constraint violation).
• default: is the only fallback and matches if no specific type
association matches, regardless of whether default: is written first or
last in the _Generic list.
• Because char*, char (*)[16], and char (*)[32] are mutually
incompatible pointer types in C, they coexist cleanly in the same
_Generic block without ambiguity.
Would you like to see how to combine pointer-to-array (char (*)[N]) with
compound literals so callers can pass inline fixed-size views or
adapters without declaring temporary variables?
[ RF ]
Thanks GG. I mostly hope to have type-inference. It's appreciated that
there's only limited type-conversion/type-coercion in C types, for
example as among integer types is what's thought so. It's figured the
adapters the types could include references to functions of
typed-function-pointers, where I'd be curious about _Generic and the
type of function pointers, and perhaps to introduce "typeof", though I'm
under the impression that "typeof" isn't C11, about the expression
passed to _Generic and its type, then about the "function pointers" or
references then to function as defined, whether if those are "inline"
that also the compiler can "inline" them.
[ GG ]
Three distinct C11 mechanics come together here: how _Generic handles
function pointers, the status of typeof versus C11 workarounds, and how
compilers inline functions referenced through pointers inside adapters.
1. _Generic and Function Pointer Types
In C11, a function designator passed as the controlling expression to
_Generic automatically undergoes function-to-pointer conversion (lvalue
conversion), turning int fn(double) into int (*)(double).
• Exact Signature Matching: _Generic matches function pointers by their
exact parameter types, qualifiers, and return type. int (*)(int) and int
(*)(long) are distinct, incompatible types and can coexist in the same
_Generic block.
• No Implicit Coercion in _Generic: Unlike normal function calls where
int coerces to double, _Generic requires an exact compatible type match
(after lvalue conversion). Passing a float will not match a double arm
unless you list float: explicitly.
c
typedef int (*UnaryIntFn)(int);
typedef double (*UnaryDoubleFn)(double);
typedef void (*StepFn)(void* ctx);
int inc_i(int x) { return x + 1; }
double inc_d(double x) { return x + 1.0; }
#define dispatch_fn(fn, arg) _Generic((fn), \
UnaryIntFn: ((UnaryIntFn)(fn))(arg), \
UnaryDoubleFn: ((UnaryDoubleFn)(fn))(arg) \
)
// Passing `inc_i` decays to `int (*)(int)`, which matches `UnaryIntFn`
Use code with caution.
(Note: The casts ((UnaryIntFn)(fn)) inside the branches prevent compiler
warnings on the unselected branches when fn has a different signature.)
2. Type Inference Without typeof in Strict -std=c11
You are right: typeof is not part of standard C11. It existed only as a
compiler extension (__typeof__ in GCC/Clang) until it was standardized
in C23 (typeof and typeof_unqual).
In strict -std=c11, you achieve type inference without typeof through
three standard mechanisms:
A. Expression-Level Inference via _Generic
Because _Generic inspects the type of any expression without evaluating
it, _Generic itself is C11's type-inference engine for expressions—you
never need to name the expression's type to dispatch on it.
B. Binding a Typed Variable via Helper Macros (No typeof Needed)
When you want to declare a temporary or adapter variable whose type is
inferred from an input expression in C11, you pass the type tag or let
_Generic invoke an inline helper function whose parameter list binds the
inferred type:
c
// The helper function's parameter infers/binds the exact type without
`typeof`
static inline void walk_array16_impl(char (*buf)) {
// Inside here, `buf` has full static type `char (*)`
for (size_t i = 0; i < sizeof(*buf); ++i) {
// ...
}
}
#define walk_auto(expr) _Generic((expr), \
char (*): walk_array16_impl \
)(expr)
Use code with caution.
C. __auto_type / __typeof__ Guarded Fallback
If your target compilers are GCC or Clang, __typeof__ works even under
-std=c11 (unlike bare typeof, double-underscore __typeof__ is accepted
in strict ISO mode without warnings). You can isolate it behind a single
portability macro if you ever need local variable inference:
c
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202311L
#define C_TYPEOF(x) typeof(x)
#elif defined(__GNUC__) || defined(__clang__)
#define C_TYPEOF(x) __typeof__(x)
#endif
Use code with caution.
3. Can the Compiler Inline static inline Functions Passed via Function
Pointers?
Yes—when the function pointer value is known at compile time (constant
propagation), modern compilers (GCC, Clang, MSVC) devirtualize and
inline static inline functions completely.
When Inlining Succeeds (Zero Overhead)
If you construct an adapter struct (or pass a function pointer) using a
compile-time constant function name and pass that adapter into a static
inline algorithm in the same translation unit:
c
typedef struct {
const char* ptr;
size_t len;
int (*pred)(char c); // Typed function pointer inside the adapter
} StrAdapter;
static inline int is_digit_char(char c) {
return c >= '0' && c <= '9';
}
static inline size_t count_matching(StrAdapter s) {
size_t n = 0;
for (size_t i = 0; i < s.len; ++i) {
if (s.pred(s.ptr[i])) { // Indirect call in source...
++n;
}
}
return n;
}
size_t example(const char* data, size_t len) {
StrAdapter ad = { .ptr = data, .len = len, .pred = is_digit_char };
// At -O2, the compiler sees `ad.pred == is_digit_char`, eliminates the
// struct, devirtualizes `s.pred(...)`, and inlines `is_digit_char` into
the loop.
return count_matching(ad);
}
Use code with caution.
• Why static inline matters here: Marking both the predicate
(is_digit_char) and the generic algorithm (count_matching) as static
inline guarantees their AST/IR bodies are visible in the caller's
translation unit. Under -O2, Scalar Replacement of Aggregates (SROA)
unpacks StrAdapter into registers, sees the constant address
&is_digit_char, and replaces the indirect call with the direct
comparison instructions.
When Inlining Cannot Happen
• Runtime-selected function pointers: If ad.pred is assigned
conditionally at runtime (cond ? fn_a : fn_b) or loaded from an
external/opaque translation unit without LTO (-flto), the compiler must
emit an actual indirect call instruction.
• Comparing Compile-Time vs. Runtime Performance: Using static inline
adapter algorithms + static inline callbacks gives you C++-template-like
inlining whenever the adapter is constructed locally, while seamlessly
degrading to a standard indirect function call whenever the adapter
crosses an ABI boundary or is selected dynamically at runtime.
Summary
Goal C11 Mechanism Compile-Time Guarantee
Function pointer dispatch _Generic((fn), Ret (*)(Arg): ...) Exact
signature match (no implicit numeric coercion)
Type inference without typeof _Generic → static inline typed helper Type
bound by helper parameter without naming it at call site
Zero-cost callback inlining static inline algorithm + static inline
callback Devirtualized & inlined at -O2 when pointer target is
statically visible
Would you like to see a complete, self-contained -std=c11 pattern for a
generic sequence adapter (combining StrAdapter / ListAdapter with static
inline predicates/transforms) that compiles down to a tight inlined loop
under -O2?
[ RF ]
Thanks GG. Mostly I wanted to explore the features offered since
_Generic that make for compile-time generification/specialization,
particularly the account of the "zero-cost abstraction", then as with
regards the run-time-type-identification, as for like "a vtable of
pointers in C++", has that there are various accounts to consider for
the run-time polymorphism, as the compile-time specialization is a bit
sorted out.
[ GG ]
That gives a clean boundary: with compile-time specialization sorted out
via _Generic + static inline zero-cost adapters, the remaining design
space is runtime polymorphism in C11—how to structure runtime type
identification (RTTI) and dynamic dispatch without sacrificing clarity,
cache locality, or flexibility.
In C11, there are four distinct architectures for runtime polymorphism.
Each makes a different trade-off between memory overhead, openness to
new types, and call indirection.
1. The Four C11 Runtime Polymorphism Models
Model Mechanism Open to New Types? Per-Instance Overhead Dispatch Cost
Best For
1. Tagged Union (enum + union) Explicit kind tag + switch Closed (fixed
set of variants) sizeof(enum) + padding 1 direct branch (switch) Known
adapter set (C-string, slice, sentinel list)
2. Fat Pointer (Data + Vtable Ptr) { void* self; const Vtable* vptr; }
Open (any translation unit) 1 pointer (8 bytes on 64-bit) 1 indirect
call Non-intrusive interfaces (Rust/Go-style traits)
3. Intrusive Vtable (vptr in Object) First struct member is const
Vtable* Open (any translation unit) 1 pointer inside object 2 pointer
dereferences Long-lived heap/pool objects (C++-style)
4. Inline Function Pointers Function pointers stored directly in struct
Open N pointers (N * 8 bytes) 1 direct register call Small adapters (1–2
callbacks, e.g., next, destroy)
2. Deep Dive: Choosing the Right Runtime Representation
A. Closed Set: Tagged Union (enum + union)
When your runtime sequence adapters come from a known, bounded set of
representations (e.g., null-terminated char*, length-prefixed LenSlice,
and ListAdapter), a tagged union beats a vtable:
• No indirect calls: A switch statement lets the compiler inline the
underlying static inline functions directly into the switch arms,
keeping the instruction pipeline hot and branch-predictor friendly.
• Value semantics: The entire polymorphic adapter fits in 2–3 registers
and lives on the stack with zero heap allocation.
c
typedef enum {
ADAPTER_CSTR,
ADAPTER_SLICE,
ADAPTER_LIST
} AdapterTag;
typedef struct {
AdapterTag tag;
union {
const char* cstr;
LenSlice slice;
ListAdapter list;
} as;
} RuntimeSeq;
Use code with caution.
B. Open Set & Non-Intrusive: Fat Pointer (Data* + const Vtable*)
When external modules or plugins need to supply new sequence types
without modifying a central enum, the fat pointer (conceptually
identical to a Rust dyn Trait or Go interface) decouples the interface
from the underlying data layout:
• Zero modification to existing types: A raw char[16] buffer, a file
stream, or an intrusive node can all be adapted simply by defining a
static const SeqVtable for each.
• Lightweight handle: Passing SeqView by value copies just two pointers
(self and vptr).
c
typedef struct {
int (*next)(void* self, void* out_elem);
size_t (*remaining)(const void* self); // NULL if unknown/unbounded
} SeqVtable;
typedef struct {
void* self;
const SeqVtable* vptr;
} SeqView;
Use code with caution.
Bonus RTTI capability: Because vptr points to a unique static const
SeqVtable instance per concrete type, the address view.vptr itself acts
as a unique runtime type ID (if (view.vptr == &CSTR_VTABLE)), giving you
exact RTTI downcasting with zero extra tag bytes.
C. Open Set & Minimal Adapter: Inline Function Pointers
If an interface only has one or two operations (for example, a
stream/generator with just next), storing the function pointer directly
inside the struct avoids the double dereference (view.vptr->next) of a
separate vtable:
• Faster dispatch: One fewer memory load before calling.
• Higher per-instance size if many methods exist: Once you exceed 2–3
methods, factoring them into a shared const Vtable* saves stack/struct
space.
3. Bridging Compile-Time _Generic and Runtime Vtables
You can unify your compile-time zero-cost layer and your runtime
vtable/fat-pointer layer behind one _Generic front-end:
1. Statically known types (char (*), LenSlice, ListAdapter) route
directly to static inline functions—giving full inlining and zero-cost
abstraction.
2. Type-erased runtime handles (SeqView or RuntimeSeq) route to the
vtable/switch dispatcher.
3. Automatic lifting: A _Generic constructor macro (as_seq_view(x))
automatically pairs any concrete type x with its static const SeqVtable
whenever you need to cross from compile-time generics into a
runtime-polymorphic collection or boundary.
c
#define as_seq_view(x) _Generic((x), \
LenSlice*: ((SeqView){ .self = (x), .vptr = &SLICE_VTABLE }), \
ListAdapter*: ((SeqView){ .self = (x), .vptr = &LIST_VTABLE }), \
SeqView: (x) \
)
Use code with caution.
Decision Rule for Runtime Polymorphism in C11
• Use a Tagged Union (enum + union) when the set of adapter types is
closed and controlled by your codebase (best performance, allows
inlining inside switch).
• Use a Fat Pointer ({ void* self; const Vtable* vptr; }) when new types
must plug in openly without touching central headers, and use vptr
pointer equality as your zero-byte RTTI tag.
• Use Inline Function Pointers only when the interface has 1–2 methods
and lives on the stack.
Would you like to look at how to structure RTTI downcasting and
capability queries (checking if an arbitrary SeqView supports random
access or reset at runtime) using const Vtable* metadata fields?
[ RF ]
Thanks GG. Yes, I'd figure to use tagged-unions as that's a familiar
account of polymorphic/variant types, then about for example having
various leaf-types in the sources, then those having a general sort of
wrapper-routine to a base-type, passing that into functions, and a
general sort of unwrapper-routine within the function body, what I
imagine would require explicit casting, that though being re-usable, and
resulting returning a well-defined leaf-type. I might not expect to have
inheritance more than 1-deep, i.e., would expect that a leaf-type's
super-class is the base-type. There's that, then I'm looking about how
to deal with holder-types, as alike generics, or like "optional" for
example, about how to make for return-types of functions, that are
covariant (or, variant), when for example returning values in the type
convention or status/error codes in like "holder<T>".
[ GG ]
For a 1-level-deep hierarchy (leaf types → single tagged-union base
type) combined with generic Result<T> / Optional<T> holder return types,
standard -std=c11 gives you clean, type-safe patterns that avoid manual
casting boilerplate while keeping return types strictly typed.
1. 1-Level Tagged Union: Type-Safe Wrap & Unwrap Without Manual Casts
When every leaf type (LeafA, LeafB, LeafC) has a single base super-type
(BaseVal), you can automate upcasting (wrapping) via _Generic and
checked downcasting (unwrapping) via a macro that verifies the runtime
tag before extracting the union member.
Base & Leaf Definitions
c
#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
#include <assert.h>
typedef enum {
TAG_NONE = 0,
TAG_SLICE,
TAG_LIST,
TAG_PAGE
} BaseTag;
typedef struct {
const char* ptr;
size_t len;
} SliceLeaf;
typedef struct {
void* head;
void* sentinel;
} ListLeaf;
typedef struct {
char data[4096];
} PageLeaf;
// 1-level polymorphic base type
typedef struct {
BaseTag tag;
union {
SliceLeaf slice;
ListLeaf list;
PageLeaf page;
} as;
} BaseVal;
Use code with caution.
Automatic Upcast (wrap) via _Generic
Instead of writing manual union initializers at every call site,
_Generic matches the leaf's static type and constructs the tagged
BaseVal in one step:
c
static inline BaseVal wrap_slice(SliceLeaf s) {
return (BaseVal){ .tag = TAG_SLICE, .as.slice = s };
}
static inline BaseVal wrap_list(ListLeaf l) {
return (BaseVal){ .tag = TAG_LIST, .as.list = l };
}
static inline BaseVal wrap_page(PageLeaf p) {
return (BaseVal){ .tag = TAG_PAGE, .as.page = p };
}
// Upcasts any leaf type (or passes BaseVal through unchanged)
#define wrap(x) _Generic((x), \
SliceLeaf: wrap_slice, \
ListLeaf: wrap_list, \
PageLeaf: wrap_page, \
BaseVal: (x) \
)(x)
Use code with caution.
(Note: If x is already a BaseVal, add a static inline BaseVal
wrap_id(BaseVal b) { return b; } so (x) works uniformly as a function call.)
Checked Downcast (unwrap) Inside Functions
Inside a function receiving BaseVal, you avoid raw pointer casts by
mapping each leaf type to its expected BaseTag and union field name:
c
// Checked unwrap: asserts tag match and returns typed leaf by value
#define unwrap_slice(b) (assert((b).tag == TAG_SLICE), (b).as.slice)
#define unwrap_list(b) (assert((b).tag == TAG_LIST), (b).as.list)
#define unwrap_page(b) (assert((b).tag == TAG_PAGE), (b).as.page)
// Safe non-asserting pointer peek (returns NULL if tag does not match)
static inline const SliceLeaf* try_as_slice(const BaseVal* b) {
return (b && b->tag == TAG_SLICE) ? &b->as.slice : NULL;
}
Use code with caution.
Because C11 returns SliceLeaf or ListLeaf by value directly from the
union member, no explicit (LeafType*) cast is needed anywhere in user
code, and strict aliasing rules are 100% respected.
2. Generic Holder Types (Optional<T> & Result<T, Err>) in C11
Because C11 does not have parametric templates (holder<T>), every
distinct payload type T that crosses a function return boundary needs a
concrete struct layout (Opt_SliceLeaf, Res_BaseVal, etc.).
You can generate these cleanly from a single macro definition and bind
uniform operations (is_ok, unwrap_or, err_code) across all holder
instantiations using _Generic.
Step 1: Compact Holder Generator Macro
Keep the generator macro minimal so each type instantiation is a single
readable line:
c
typedef enum {
STATUS_OK = 0,
STATUS_EOF,
STATUS_INVALID_TAG,
STATUS_OUT_OF_BOUNDS
} StatusCode;
// Declares `Opt_<T>` and `Res_<T>` in one line per payload type
#define DEFINE_HOLDERS(T) \
typedef struct { \
bool has_val; \
T val; \
} Opt_##T; \
\
typedef struct { \
StatusCode status; \
T val; \
} Res_##T
// Instantiate only for your small set of return types
DEFINE_HOLDERS(int);
DEFINE_HOLDERS(SliceLeaf);
DEFINE_HOLDERS(ListLeaf);
DEFINE_HOLDERS(BaseVal);
Use code with caution.
Step 2: Uniform _Generic Accessors Across All Holders
Even though Res_SliceLeaf and Res_BaseVal are distinct C struct types,
_Generic lets you write polymorphic helper macros (is_ok(r),
get_status(r)) that work uniformly on every holder type:
c
// Works on any Res_<T>
#define is_ok(res) ((res).status == STATUS_OK)
#define is_some(opt) ((opt).has_val)
// Construct success or error holders cleanly using C99/C11 compound
literals
#define ok_res(ResType, value) \
((ResType){ .status = STATUS_OK, .val = (value) })
#define err_res(ResType, code) \
((ResType){ .status = (code) })
Use code with caution.
Example: Function Returning a Typed Holder
c
Res_SliceLeaf next_slice(BaseVal* stream) {
SliceLeaf* s = (stream && stream->tag == TAG_SLICE) ? &stream->as.slice
: NULL;
if (!s) {
return err_res(Res_SliceLeaf, STATUS_INVALID_TAG);
}
if (s->len == 0) {
return err_res(Res_SliceLeaf, STATUS_EOF);
}
SliceLeaf head = { .ptr = s->ptr, .len = 1 };
s->ptr += 1;
s->len -= 1;
return ok_res(Res_SliceLeaf, head);
}
Use code with caution.
3. Handling Variance / Covariance Across Holders in C11
In languages with subtyping, if SliceLeaf is a subtype of BaseVal, then
Res_SliceLeaf is covariant with Res_BaseVal (a function returning
Res_SliceLeaf can satisfy a caller expecting Res_BaseVal).
In C11, Res_SliceLeaf and Res_BaseVal are unrelated structs in the type
system, so implicit conversion does not happen—but you can express
explicit covariance cleanly with a single _Generic lift_res(...) adapter:
c
static inline Res_BaseVal lift_res_slice(Res_SliceLeaf r) {
if (r.status != STATUS_OK) {
return (Res_BaseVal){ .status = r.status };
}
return (Res_BaseVal){
.status = STATUS_OK,
.val = wrap_slice(r.val)
};
}
static inline Res_BaseVal lift_res_list(Res_ListLeaf r) {
if (r.status != STATUS_OK) {
return (Res_BaseVal){ .status = r.status };
}
return (Res_BaseVal){
.status = STATUS_OK,
.val = wrap_list(r.val)
};
}
// Covariant lift: converts any Res_<Leaf> into Res_BaseVal
#define lift_to_base_res(res) _Generic((res), \
Res_SliceLeaf: lift_res_slice, \
Res_ListLeaf: lift_res_list, \
Res_BaseVal: lift_res_id \
)(res)
Use code with caution.
• Leaf-returning functions (Res_SliceLeaf) preserve full static type
precision without tag overhead when called directly.
• Polymorphic pipelines call lift_to_base_res(next_slice(&stream)) to
propagate any error StatusCode untouched while automatically wrapping
the payload into BaseVal.
Architectural Summary
Pattern C11 Implementation Why It Fits
Upcast (Leaf → Base) _Generic wrap(x) Zero manual tag assignment at call
sites
Downcast (Base → Leaf) Checked union member access (unwrap_leaf(b)) No
pointer casts; strict-aliasing safe
Generic Holder (Res_<T>) One-line DEFINE_HOLDERS(T) + compound literals
Carries both StatusCode and typed value by value
Holder Covariance _Generic lift_to_base_res(r) Bridges specific
Res_<Leaf> returns into Res_BaseVal
Would you like to explore how to handle nested or recursive structures
inside BaseVal (such as an adapter wrapping another BaseVal via
pointer/arena) or ergonomic error-propagation macros (TRY(expr)
early-return pattern in C11)?
[ RF ]
Thanks GG. This is going along well. Here the status codes might be
particular among the return types in their own enums, yet it's according
to some reserved failures and having both success_t and error_t and
MODULE_SUCCESS_OK = 0 and MODULE_ERROR_ERRORLESS = 0, then to break out
cases according to, for example, the "type_t" member, among these closed
classes. For the purposes I have at the moment there are less than a
handful of categories in a closed category. Comment as freely on the
considerations and surrounds.
[ GG ]
Separating success_t (positive outcomes, 0 = standard OK, > 0 =
domain-specific success nuances like EOF, PARTIAL, CACHED) from error_t
(negative/failure outcomes, 0 = ERRORLESS, > 0 = reserved core faults +
module-specific errors) gives you a rich, two-dimensional status model.
When you have a closed category of fewer than a handful of module/return
classes, pairing a type_t category discriminant with _Generic lets you
inspect, route, and lift status codes uniformly without losing
module-specific precision.
1. The Two-Axis Status Model (success_t + error_t)
Instead of cramming successes and errors into a single flat integer
where callers guess whether 1 means "1 item read" or "Error #1", keeping
them distinct in the holder clarifies control flow immediately:
• error_t (MODULE_ERROR_ERRORLESS = 0): Strictly reserved for faults.
Any non-zero value means the payload val is invalid/uninitialized.
• Reserved Core Range (e.g., 1..31): Shared invariants across all
modules (ERR_INVALID_TAG, ERR_OUT_OF_BOUNDS, ERR_NULL_ARG, ERR_NOMEM).
• Module-Specific Range (32+): Tailored to that specific return class
(ERR_MALFORMED_UTF8, ERR_BROKEN_SENTINEL).
• success_t (MODULE_SUCCESS_OK = 0): Only meaningful when error ==
MODULE_ERROR_ERRORLESS.
• 0: Standard completion with a valid payload.
• > 0: Valid non-error completion states (SUCCESS_EOF, SUCCESS_EMPTY,
SUCCESS_WOULD_BLOCK).
c
// Core reserved errors shared across all closed classes
typedef enum {
MOD_ERR_ERRORLESS = 0,
MOD_ERR_INVALID_TAG = 1,
MOD_ERR_OUT_OF_BOUNDS = 2,
MOD_ERR_UNSUPPORTED = 3,
MOD_ERR_RESERVED_MAX = 31
} CoreError;
// Module-specific enums extend cleanly above the reserved floor
typedef enum {
SEQ_ERR_ERRORLESS = MOD_ERR_ERRORLESS,
SEQ_ERR_BAD_SENTINEL = 32,
SEQ_ERR_TRUNCATED = 33
} SeqError;
typedef enum {
SEQ_OK = 0,
SEQ_OK_EOF = 1,
SEQ_OK_PARTIAL = 2
} SeqSuccess;
Use code with caution.
2. Breaking Out Cases via type_t Across a Closed Category
With fewer than a handful of closed classes (say, CLASS_SLICE,
CLASS_LIST, CLASS_PAGE), every holder or polymorphic result carries a
type_t tag alongside its success_t and error_t.
Uniform Holder Shape with type_t
By placing type_t, error_t, and success_t in a consistent header layout
across your closed classes, you can inspect any concrete holder
(Res_Slice, Res_List) or the lifted Res_Base using the exact same
branching logic:
c
typedef enum {
TYPE_NONE = 0,
TYPE_SLICE,
TYPE_LIST,
TYPE_PAGE
} TypeKind;
// Macro to stamp out typed holders with uniform status headers
#define DEFINE_CLASS_HOLDER(TypeTag, PayloadT, SuccessEnum, ErrorEnum) \
typedef struct { \
TypeKind type; \
ErrorEnum err; \
SuccessEnum ok; \
PayloadT val; \
} Res_##PayloadT
DEFINE_CLASS_HOLDER(TYPE_SLICE, SliceLeaf, SeqSuccess, SeqError);
DEFINE_CLASS_HOLDER(TYPE_LIST, ListLeaf, SeqSuccess, SeqError);
Use code with caution.
Dispatching on type_t in Control Flow
Because the category is closed and small (3–4 cases), a direct switch
(res.type) gives the compiler a dense jump table (or conditional moves)
and guarantees exhaustiveness warnings (-Wswitch) whenever you add a new
class:
c
void handle_any_result(Res_BaseVal r) {
// 1. Fast-path fault check across all classes using the reserved core range
if (r.err != MOD_ERR_ERRORLESS) {
if (r.err <= MOD_ERR_RESERVED_MAX) {
// Handle universal core error uniformly regardless of r.type
return;
}
// Otherwise break out by closed class for module-specific error codes
switch (r.type) {
case TYPE_SLICE: /* inspect (SeqError)r.err */ break;
case TYPE_LIST: /* inspect (SeqError)r.err */ break;
case TYPE_PAGE: /* inspect (PageError)r.err */ break;
case TYPE_NONE: break;
}
return;
}
// 2. Errorless path: break out by closed class and success nuance
switch (r.type) {
case TYPE_SLICE:
if (r.ok == SEQ_OK_EOF) { /* ... */ }
// safe to access r.val.as.slice
break;
case TYPE_LIST:
// safe to access r.val.as.list
break;
case TYPE_PAGE:
// safe to access r.val.as.page
break;
case TYPE_NONE:
break;
}
}
Use code with caution.
3. Architectural Considerations & Surrounds
When building around this pattern in -std=c11, four practical details
keep the code clean and bug-free:
• Zero-Initialization Invariant (0 == ERRORLESS / OK / TYPE_NONE):
Setting MODULE_ERROR_ERRORLESS = 0, MODULE_SUCCESS_OK = 0, and TYPE_NONE
= 0 means {0} zero-initialization produces a valid, deterministic empty
state (type == TYPE_NONE, no phantom error flags).
• Enum Underlying Type & ABI Stability:
In C11, each enum is compatible with some implementation-defined integer
type (int or unsigned int). When lifting a module-specific SeqError into
a general Res_BaseVal, storing int err (or uint32_t err) in Res_BaseVal
avoids enum-to-enum conversion warnings under -Wenum-conversion while
preserving exact numeric equality (r.err == SEQ_ERR_TRUNCATED).
• Compile-Time _Generic + Runtime type_t Symmetry:
Notice how type_t mirrors _Generic:
• At compile time, _Generic((x), SliceLeaf: TYPE_SLICE, ListLeaf:
TYPE_LIST, ...) automatically stamps the right TypeKind into the struct
so you never write .type = TYPE_SLICE by hand.
• At runtime, switch (res.type) recovers that exact compile-time
distinction cleanly.
• Payload Validity Contract:
Establish a strict rule across all closed classes: accessing .val is
only legal when err == MOD_ERR_ERRORLESS (and optionally when ok ==
MODULE_SUCCESS_OK, if OK_EOF carries no item). Wrapping that check in a
tiny static inline accessor prevents accidental reads of uninitialized
union bytes on EOF or error paths.
Would you like to see a small header layout showing how _Generic
automatically stamps type_t on construction and lifts Res_<Leaf> into
Res_BaseVal while preserving err and ok codes?
[ RF ]
Thanks GG. Carry on as freely.
[ GG ]
Everything we've discussed fits together into a single, cohesive
-std=c11 pattern. Because your closed category has fewer than a handful
of classes, you can pack the compile-time _Generic auto-stamping, the
two-axis success_t / error_t status header, and the covariant
lift_to_base bridge into one small header without macro bloat or runtime
overhead.
Complete -std=c11 Closed-Category Header Architecture
1. Shared Core Status & Closed Category Tags
By reserving 0 for ERRORLESS / OK / NONE and setting a floor
(MOD_ERR_RESERVED_MAX = 31) for core errors, every module extends error
and success codes cleanly without collisions.
c
#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
#include <assert.h>
// Closed category discriminant
typedef enum {
TYPE_NONE = 0,
TYPE_SLICE,
TYPE_LIST,
TYPE_PAGE
} TypeKind;
// Reserved core errors shared across all classes
typedef enum {
MOD_ERR_ERRORLESS = 0,
MOD_ERR_INVALID_TAG = 1,
MOD_ERR_OUT_OF_BOUNDS = 2,
MOD_ERR_UNSUPPORTED = 3,
MOD_ERR_RESERVED_MAX = 31
} CoreError;
typedef enum {
MOD_OK = 0
} CoreSuccess;
Use code with caution.
2. Leaf Types, Base Tagged Union, and Module Enums
Each leaf carries its own compact layout (including fixed-size PageLeaf
buffers by value), while BaseVal unifies them 1-level deep.
c
// Module-specific status enums (extending above reserved floor)
typedef enum {
SEQ_ERR_ERRORLESS = MOD_ERR_ERRORLESS,
SEQ_ERR_BAD_SENTINEL = 32,
SEQ_ERR_TRUNCATED = 33
} SeqError;
typedef enum {
SEQ_OK = MOD_OK,
SEQ_OK_EOF = 1,
SEQ_OK_PARTIAL = 2
} SeqSuccess;
// Concrete leaf types
typedef struct {
const char* ptr;
size_t len;
} SliceLeaf;
typedef struct {
void* head;
const void* sentinel;
} ListLeaf;
typedef struct {
char data[64];
} PageLeaf;
// 1-level polymorphic base type
typedef struct {
TypeKind type;
union {
SliceLeaf slice;
ListLeaf list;
PageLeaf page;
} as;
} BaseVal;
Use code with caution.
3. Typed Holders (Res_<Leaf>) and Polymorphic Base Holder (Res_BaseVal)
Each concrete return type keeps its exact SuccessEnum and ErrorEnum for
strict -Wswitch checking at leaf call sites, while Res_BaseVal widens
err and ok to int so any leaf result lifts losslessly.
c
#define DEFINE_CLASS_HOLDER(PayloadT, SuccessEnum, ErrorEnum) \
typedef struct { \
TypeKind type; \
ErrorEnum err; \
SuccessEnum ok; \
PayloadT val; \
} Res_##PayloadT
DEFINE_CLASS_HOLDER(SliceLeaf, SeqSuccess, SeqError);
DEFINE_CLASS_HOLDER(ListLeaf, SeqSuccess, SeqError);
DEFINE_CLASS_HOLDER(PageLeaf, SeqSuccess, SeqError);
// Lifted polymorphic holder (covariant target)
typedef struct {
TypeKind type;
int err;
int ok;
BaseVal val;
} Res_BaseVal;
Use code with caution.
4. Compile-Time _Generic Auto-Stamping & Covariant Lifting
_Generic eliminates manual tag bookkeeping at every return statement and
call site:
• type_tag_of(x) deduces TypeKind directly from any leaf value or pointer.
• ret_ok(ResT, val) / ret_status(ResT, ok_code) / ret_err(ResT,
err_code) stamp the exact TypeKind automatically via _Generic on .val.
• lift_res(r) converts any concrete Res_<Leaf> into Res_BaseVal while
preserving type, err, and ok intact.
c
// Deduce TypeKind at compile time from any leaf type
#define type_tag_of(x) _Generic((x), \
SliceLeaf: TYPE_SLICE, \
ListLeaf: TYPE_LIST, \
PageLeaf: TYPE_PAGE, \
default: TYPE_NONE \
)
// Ergonomic holder constructors with automatic TypeKind stamping
#define ret_ok(ResT, value) \
((ResT){ .type = type_tag_of(value), .err = 0, .ok = 0, .val = (value) })
#define ret_ok_code(ResT, code, value) \
((ResT){ .type = type_tag_of(value), .err = 0, .ok = (code), .val =
(value) })
#define ret_err(ResT, zero_val, err_code) \
((ResT){ .type = type_tag_of(zero_val), .err = (err_code), .ok = 0 })
// Concrete wrap helpers (Leaf -> BaseVal)
static inline BaseVal wrap_slice(SliceLeaf s) {
return (BaseVal){ .type = TYPE_SLICE, .as.slice = s };
}
static inline BaseVal wrap_list(ListLeaf l) {
return (BaseVal){ .type = TYPE_LIST, .as.list = l };
}
static inline BaseVal wrap_page(PageLeaf p) {
return (BaseVal){ .type = TYPE_PAGE, .as.page = p };
}
static inline BaseVal wrap_base(BaseVal b) {
return b;
}
#define wrap(x) _Generic((x), \
SliceLeaf: wrap_slice, \
ListLeaf: wrap_list, \
PageLeaf: wrap_page, \
BaseVal: wrap_base \
)(x)
// Covariant holder lifters (Res_<Leaf> -> Res_BaseVal)
static inline Res_BaseVal lift_slice_res(Res_SliceLeaf r) {
return (Res_BaseVal){
.type = r.type,
.err = (int)r.err,
.ok = (int)r.ok,
.val = (r.err == SEQ_ERR_ERRORLESS) ? wrap_slice(r.val) : (BaseVal){0}
};
}
static inline Res_BaseVal lift_list_res(Res_ListLeaf r) {
return (Res_BaseVal){
.type = r.type,
.err = (int)r.err,
.ok = (int)r.ok,
.val = (r.err == SEQ_ERR_ERRORLESS) ? wrap_list(r.val) : (BaseVal){0}
};
}
static inline Res_BaseVal lift_page_res(Res_PageLeaf r) {
return (Res_BaseVal){
.type = r.type,
.err = (int)r.err,
.ok = (int)r.ok,
.val = (r.err == SEQ_ERR_ERRORLESS) ? wrap_page(r.val) : (BaseVal){0}
};
}
static inline Res_BaseVal lift_base_res(Res_BaseVal r) {
return r;
}
#define lift_res(r) _Generic((r), \
Res_SliceLeaf: lift_slice_res, \
Res_ListLeaf: lift_list_res, \
Res_PageLeaf: lift_page_res, \
Res_BaseVal: lift_base_res \
)(r)
Use code with caution.
5. Putting It Together in Algorithm & Call-Site Code
Notice how clean both the specialized leaf path and the polymorphic base
path become:
c
// Specialized leaf routine: returns concrete Res_SliceLeaf with zero
union overhead
static inline Res_SliceLeaf slice_take_head(SliceLeaf* s) {
if (!s || !s->ptr) {
return ret_err(Res_SliceLeaf, (SliceLeaf){0},
(SeqError)MOD_ERR_INVALID_TAG);
}
if (s->len == 0) {
return ret_ok_code(Res_SliceLeaf, SEQ_OK_EOF, ((SliceLeaf){0}));
}
SliceLeaf out = { .ptr = s->ptr, .len = 1 };
s->ptr += 1;
s->len -= 1;
return ret_ok(Res_SliceLeaf, out);
}
// Polymorphic routine: accepts BaseVal*, dispatches on type_t, lifts
result covariantly
Res_BaseVal base_take_head(BaseVal* b) {
if (!b) {
return (Res_BaseVal){ .type = TYPE_NONE, .err = MOD_ERR_INVALID_TAG };
}
switch (b->type) {
case TYPE_SLICE:
return lift_res(slice_take_head(&b->as.slice));
case TYPE_LIST:
// return lift_res(list_take_head(&b->as.list));
return (Res_BaseVal){ .type = TYPE_LIST, .err = MOD_ERR_UNSUPPORTED };
case TYPE_PAGE:
return (Res_BaseVal){ .type = TYPE_PAGE, .err = MOD_ERR_UNSUPPORTED };
case TYPE_NONE:
default:
return (Res_BaseVal){ .type = TYPE_NONE, .err = MOD_ERR_INVALID_TAG };
}
}
Use code with caution.
Why This Balance Works Well in -std=c11
• Zero-Cost Leaf Calls: Calling slice_take_head(&my_slice) directly
never constructs a BaseVal or touches a switch; the compiler inlines it
straight down to pointer arithmetic.
• Uniform Polymorphic Boundary: Calling base_take_head(&any_val) handles
runtime polymorphism via a single dense switch (b->type) and reuses
slice_take_head without duplicating logic.
• No Fragile Casts: Every unwrap (&b->as.slice) is guarded by its
matching case TYPE_SLICE:, and every upcast (wrap, lift_res) is checked
by _Generic at compile time.
Would you like to add ergonomic propagation macros (e.g., TRY_LIFT(expr)
to early-return errors/EOFs across functions returning Res_BaseVal or
Res_<Leaf>) or diagnostic/string-mapping tables for logging TypeKind,
CoreError, and module status codes?
[ RF ]
Thanks GG. Since you mentioned it, or them, both try-emulation and
"char* from_enum(generic)" and "generic to_enum(char* name, type_t t)"
would be of interest, then about try-emulation, about resulting
"return(CATCHME)" or the like, carry on.
[ GG ]
Good to dive into both of these, RF. In strict -std=c11, you can build
standard-compliant TRY propagation (without GNU statement expressions
({...})) and bidirectional enum reflection (from_enum / to_enum) that
tie directly into your type_t and Res_<T> architecture.
1. Standard -std=c11 TRY Emulation & return(CATCHME)
In GCC/Clang, ({ ... }) statement expressions make TRY trivial, but in
strict -std=c11 you cannot yield a value from a block statement.
Instead, you use the out-parameter assignment pattern inside a do { ...
} while (0) guard.
A. Propagating Errors or Non-Zero Success (EOF) Automatically
When a function returns any Res_<T> (whether a concrete Res_SliceLeaf or
a lifted Res_BaseVal), TRY_ASSIGN evaluates the expression once, checks
.err (and optionally .ok), and performs an immediate return—lifting the
status cleanly to the caller's return type if needed.
c
// 1. Propagate faults (`err != 0`) while assigning `.val` on errorless
paths
#define TRY_ERR(out_var, expr, CallerResT) do { \
Res_BaseVal _tmp_res = lift_res(expr); \
if (_tmp_res.err != MOD_ERR_ERRORLESS) { \
return (CallerResT){ \
.type = _tmp_res.type, \
.err = _tmp_res.err, \
.ok = _tmp_res.ok \
}; \
} \
(out_var) = (expr).val; \
} while (0)
Use code with caution.
(To avoid double-evaluating expr in strict C11 when expr has side
effects, pass a temporary holder or use a C_TYPEOF macro if targeting
GCC/Clang, or pass the concrete ResT type name explicitly.)
Here is the single-evaluation, zero-extension -std=c11 version by
passing the expression's holder type ExprResT:
c
// Single-evaluation, strict -std=c11 TRY_ASSIGN
#define TRY_ASSIGN(out_var, ExprResT, expr, CallerResT) do { \
ExprResT _r = (expr); \
if (_r.err != MOD_ERR_ERRORLESS) { \
return (CallerResT){ \
.type = _r.type, \
.err = _r.err, \
.ok = _r.ok \
}; \
} \
(out_var) = _r.val; \
} while (0)
// Variant that ALSO short-circuits on non-zero success (e.g., SEQ_OK_EOF)
#define TRY_OK(out_var, ExprResT, expr, CallerResT) do { \
ExprResT _r = (expr); \
if (_r.err != MOD_ERR_ERRORLESS || _r.ok != 0) { \
return (CallerResT){ \
.type = _r.type, \
.err = _r.err, \
.ok = _r.ok \
}; \
} \
(out_var) = _r.val; \
} while (0)
Use code with caution.
B. The return(CATCHME) Pattern (Local Block Trap / Single-Exit Cleanup)
Sometimes you don't want to return from the entire function
immediately—you want a local scope that catches any failure/EOF and
jumps to a CATCHME: handler (for cleanup or recovery) before returning.
c
// Local try-block macro that jumps to label `catch_label` on failure
#define TRY_CATCH(out_var, ExprResT, expr, caught_res, catch_label) do { \
ExprResT _r = (expr); \
if (_r.err != MOD_ERR_ERRORLESS) { \
(caught_res) = lift_res(_r); \
goto catch_label; \
} \
(out_var) = _r.val; \
} while (0)
// Usage inside a function:
Res_BaseVal parse_pair(SliceLeaf* stream) {
Res_BaseVal caught = {0};
SliceLeaf first = {0};
SliceLeaf second = {0};
TRY_CATCH(first, Res_SliceLeaf, slice_take_head(stream), caught, CATCHME);
TRY_CATCH(second, Res_SliceLeaf, slice_take_head(stream), caught, CATCHME);
return lift_res(ret_ok(Res_SliceLeaf, second));
CATCHME:
// Single cleanup / diagnostic hook before returning the caught status
return caught;
}
Use code with caution.
Notice how caught is a Res_BaseVal populated via lift_res(_r), so
CATCHME: receives the exact type, err, and ok codes regardless of which
leaf function failed.
2. Bidirectional Enum Reflection: from_enum(generic) & to_enum(name, type_t)
Because your closed category has a small, fixed set of enum types
(TypeKind, CoreError, SeqError, SeqSuccess), you can generate both const
char* from_enum(val) (dispatched via _Generic) and Res_EnumVal
to_enum(const char* name, TypeKind t) (dispatched via type_t or an
EnumKind tag) from a single compact table macro.
Step 1: Single Source-of-Truth Enum Table
Define each enum's entries once with a LIST(X) macro so string names and
enum constants can never drift out of sync:
c
#include <string.h>
#define TYPE_KIND_ENTRIES(X) \
X(TYPE_NONE) \
X(TYPE_SLICE) \
X(TYPE_LIST) \
X(TYPE_PAGE)
#define SEQ_ERR_ENTRIES(X) \
X(SEQ_ERR_ERRORLESS) \
X(SEQ_ERR_BAD_SENTINEL) \
X(SEQ_ERR_TRUNCATED)
#define SEQ_OK_ENTRIES(X) \
X(SEQ_OK) \
X(SEQ_OK_EOF) \
X(SEQ_OK_PARTIAL)
Use code with caution.
Step 2: from_enum(generic) via _Generic
Each enum gets a tiny static inline const char* lookup function
generated from its ENTRIES(X) list, and _Generic routes any enum value
to its exact stringifier at compile time:
c
#define DEFINE_FROM_ENUM(EnumType, fn_name, ENTRIES_MACRO) \
static inline const char* fn_name(EnumType v) { \
switch (v) { \
ENTRIES_MACRO(CASE_TO_STR) \
default: return "UNKNOWN_" #EnumType; \
} \
}
#define CASE_TO_STR(sym) case sym: return #sym;
DEFINE_FROM_ENUM(TypeKind, type_kind_to_str, TYPE_KIND_ENTRIES)
DEFINE_FROM_ENUM(SeqError, seq_err_to_str, SEQ_ERR_ENTRIES)
DEFINE_FROM_ENUM(SeqSuccess, seq_ok_to_str, SEQ_OK_ENTRIES)
// Polymorphic compile-time dispatch: works on any registered enum type
#define from_enum(e) _Generic((e), \
TypeKind: type_kind_to_str, \
SeqError: seq_err_to_str, \
SeqSuccess: seq_ok_to_str \
)(e)
Use code with caution.
• Zero runtime overhead: Calling from_enum(r.err) resolves directly to
seq_err_to_str(r.err) at compile time—no string tables or hashes required.
• Compiler exhaustiveness: If you add a new enumerator to SeqError and
forget to add it to SEQ_ERR_ENTRIES, -Wswitch warns you immediately.
Step 3: to_enum(const char* name, type_t) Returning a Typed Holder
For parsing a string back into an enum value, we know the target enum
domain at runtime via a type_t / EnumDomain discriminant, and we return
a Res_Int (or Res_BaseVal) holder using your two-axis status convention
(MOD_ERR_INVALID_TAG on unknown string):
c
typedef enum {
ENUM_DOMAIN_TYPE_KIND = 1,
ENUM_DOMAIN_SEQ_ERR,
ENUM_DOMAIN_SEQ_OK
} EnumDomain;
typedef struct {
TypeKind type;
int err;
int ok;
int val;
} Res_Enum;
#define IF_STR_MATCH(sym) \
if (strcmp(name, #sym) == 0) { \
return (Res_Enum){ .type = TYPE_NONE, .err = MOD_ERR_ERRORLESS, .val =
(int)(sym) }; \
}
static inline Res_Enum to_enum(const char* name, EnumDomain domain) {
if (!name) {
return (Res_Enum){ .err = MOD_ERR_INVALID_TAG };
}
switch (domain) {
case ENUM_DOMAIN_TYPE_KIND:
TYPE_KIND_ENTRIES(IF_STR_MATCH)
break;
case ENUM_DOMAIN_SEQ_ERR:
SEQ_ERR_ENTRIES(IF_STR_MATCH)
break;
case ENUM_DOMAIN_SEQ_OK:
SEQ_OK_ENTRIES(IF_STR_MATCH)
break;
}
return (Res_Enum){ .err = MOD_ERR_OUT_OF_BOUNDS };
}
Use code with caution.
If you want to_enum to dispatch off your existing TypeKind (type_t) plus
an axis selector (e.g., to_err_enum(name, r.type) vs. to_ok_enum(name,
r.type)), you simply switch (t) on TypeKind so each closed class
(TYPE_SLICE, TYPE_LIST, TYPE_PAGE) parses strings against its own
module-specific ErrorEnum or SuccessEnum.
Summary of How Everything Connects
Construct Compile-Time or Runtime Mechanism Role in Your Architecture
TRY_ASSIGN / TRY_CATCH Compile-time macro + runtime branch do { ... }
while(0) + lift_res Propagates err/ok across leaf & base holders cleanly
from_enum(e) Compile-time dispatch _Generic + switch over ENTRIES(X)
Zero-overhead enum-to-string with -Wswitch safety
to_enum(str, t) Runtime dispatch switch (t) + Res_Enum holder Parses
strings into enum integers using your status model
Would you like to look at arena/region-backed cleanup paired with the
CATCHME label pattern (so heap or buffer allocations made inside a
TRY_CATCH block roll back automatically on error)?
[ RF ]
Thanks GG. About passing allocator into these, would be as for the
varying-parameter-count case as above, then basically about that
allocator is considered other accounts like allocator/stdout/...,
whatever is otherwise usually a "global function" to "club the globals",
basically making holders of pointers, that would be built their
specializations, according to type-inference on the expression, a
relevant allocator and emitter for the expression its type.
[ GG ]
You are describing an explicit capability / environment context
("clubbing the globals" into a single typed capability bundle—allocator,
output sink/emitter, logger—so nothing relies on hidden global state)
paired with compile-time specialization via _Generic.
In -std=c11, bundling globals into a capability struct (Env / Ctx) and
routing operations through _Generic gives you two major benefits:
1. Uniform arity without signature explosion: Instead of passing (alloc,
stdout_sink, log_fn, ...) as separate parameters that blow up your
_Generic arity macros, you pass one Ctx pointer (or omit it entirely via
a 1-arg default overload).
2. Type-inferred specialization of both allocator and emitter: _Generic
inspects the target expression's type T and automatically binds the
right alignment/size (sizeof(T), _Alignof(T)) for the allocator and the
right formatting/serialization function (emit_slice, emit_list,
emit_page) for the emitter.
1. Clubbing the Globals: The Capability Bundle (EnvCtx)
Instead of calling malloc, free, or fprintf(stdout, ...) directly inside
your sequence adapters, group those interfaces into a lightweight
capability struct:
c
#include <stddef.h>
#include <stdint.h>
#include <stdalign.h>
// 1. Allocator capability
typedef struct {
void* (*alloc)(void* state, size_t size, size_t align);
void (*free)(void* state, void* ptr, size_t size);
void* state;
} AllocCap;
// 2. Emitter / sink capability (replaces direct stdout/stderr globals)
typedef struct {
int (*write_bytes)(void* state, const char* data, size_t len);
void* state;
} EmitCap;
// 3. Clubbed environment bundle passed into routines
typedef struct {
AllocCap mem;
EmitCap out;
EmitCap err_out;
} EnvCtx;
Use code with caution.
• Zero global state: Unit tests pass an arena AllocCap and an in-memory
buffer EmitCap; production passes a system/pool AllocCap and a FILE*
EmitCap.
• Single parameter slot: Functions take (EnvCtx* ctx, ...) uniformly,
keeping your parameter counts clean and predictable.
2. Type-Inferred Allocator & Emitter Specialization via _Generic
With EnvCtx in place, you can write type-inferred macros that inspect
the expression passed in and automatically specialize both allocation
(alloc_for(ctx, expr)) and emission (emit(ctx, expr)).
A. Type-Inferred Allocation (alloc_as(ctx, expr))
_Generic deduces the exact element type from an exemplar expression or
typed pointer, automatically supplying sizeof(T) and _Alignof(T) without
manual sizeof arithmetic:
c
// Typed allocation helpers (return NULL or typed pointer)
static inline SliceLeaf* alloc_slice_impl(EnvCtx* ctx) {
return (SliceLeaf*)ctx->mem.alloc(ctx->mem.state, sizeof(SliceLeaf),
_Alignof(SliceLeaf));
}
static inline ListLeaf* alloc_list_impl(EnvCtx* ctx) {
return (ListLeaf*)ctx->mem.alloc(ctx->mem.state, sizeof(ListLeaf),
_Alignof(ListLeaf));
}
static inline PageLeaf* alloc_page_impl(EnvCtx* ctx) {
return (PageLeaf*)ctx->mem.alloc(ctx->mem.state, sizeof(PageLeaf),
_Alignof(PageLeaf));
}
// Type-inferred allocator dispatch: pass an exemplar value or typed pointer
#define alloc_for(ctx, expr) _Generic((expr), \
SliceLeaf: alloc_slice_impl, \
SliceLeaf*: alloc_slice_impl, \
ListLeaf: alloc_list_impl, \
ListLeaf*: alloc_list_impl, \
PageLeaf: alloc_page_impl, \
PageLeaf*: alloc_page_impl \
)(ctx)
Use code with caution.
• Calling SliceLeaf* s = alloc_for(ctx, (SliceLeaf){0}); (or
alloc_for(ctx, s)) infers SliceLeaf, passes the exact
_Alignof(SliceLeaf), and returns a properly typed SliceLeaf* with zero
manual casts at the call site.
B. Type-Inferred Emitter (emit(ctx, expr))
Similarly, emit(ctx, expr) inspects the static type of expr—whether a
leaf (SliceLeaf, ListLeaf, PageLeaf), a BaseVal tagged union, or a
Res_BaseVal status holder—and routes it to the matching formatter
writing into ctx->out:
c
int emit_slice(EnvCtx* ctx, SliceLeaf s);
int emit_list(EnvCtx* ctx, ListLeaf l);
int emit_page(EnvCtx* ctx, PageLeaf p);
int emit_cstr(EnvCtx* ctx, const char* s);
int emit_base(EnvCtx* ctx, BaseVal b);
int emit_res(EnvCtx* ctx, Res_BaseVal r);
// Compile-time type inference selects the specialized emitter for `expr`
#define emit(ctx, expr) _Generic((expr), \
SliceLeaf: emit_slice, \
ListLeaf: emit_list, \
PageLeaf: emit_page, \
char*: emit_cstr, \
const char*: emit_cstr, \
BaseVal: emit_base, \
Res_BaseVal: emit_res \
)((ctx), (expr))
Use code with caution.
And inside emit_base(EnvCtx* ctx, BaseVal b), you simply switch (b.type)
and delegate to emit_slice, emit_list, or emit_page—reusing the exact
same emitters for both compile-time _Generic calls and runtime type_t
polymorphism.
3. Handling Optional EnvCtx* via Arity Overloading
If you want callers to be able to omit EnvCtx* when using a default
environment (e.g., calling emit(val) with 1 argument vs. emit(ctx, val)
with 2 arguments), your earlier arity counter macro handles both cleanly
without duplicating implementations:
c
// Default fallback context (only referenced if 1-arg form is called)
EnvCtx* default_env_ctx(void);
#define EMIT_1(expr) emit_with_ctx(default_env_ctx(), (expr))
#define EMIT_2(ctx, expr) emit_with_ctx((ctx), (expr))
#define GET_EMIT_MACRO(_1, _2, NAME, ...) NAME
#define emit_auto(...) \
GET_EMIT_MACRO(__VA_ARGS__, EMIT_2, EMIT_1)(__VA_ARGS__)
Use code with caution.
• emit_auto(my_slice) (1 arg) supplies default_env_ctx() and dispatches
on my_slice's type.
• emit_auto(custom_ctx, my_slice) (2 args) uses custom_ctx directly
without touching any global state.
Architectural Payoff
Concern How EnvCtx + _Generic Solves It
No hidden globals Allocators, stdout/stderr, and loggers travel together
in one EnvCtx* pointer.
No arity explosion Adding a new capability (like a clock or tracer) adds
a field to EnvCtx without changing any function signatures or _Generic
tables.
Zero-cost specialization When ctx->mem.alloc or ctx->out.write_bytes
points to a static inline arena/buffer function in the same translation
unit, -O2 inlines through the struct pointer cleanly.
Unified compile-time & runtime _Generic routes statically typed
expressions directly to emit_<Leaf>; emit_base switches on type_t and
calls the exact same emit_<Leaf> functions.
Would you like to see how to implement a minimal stack/arena AllocCap +
memory-buffer EmitCap in ~25 lines of -std=c11 so you can drop this into
a self-contained test harness right away?
[ RF ]
Thanks GG. It's considered a good sort of account how to pass down the
"optional" parameters without polluting the signatures, then for those
pointers to functions to get associated back with the relevant types
after _Generic again keyed off the anchor/root signature-parameter type,
then that it's not very, very much boilerplate then to have the code
looking like it supports overloading of functions after type-inference,
in C11, and with zero-cost abstraction for many accounts, and also for
covariant return types, and, run-time polymorphism.
[ GG ]
That sums up the architecture cleanly, RF. By anchoring your dispatch on
a single root parameter type via _Generic and threading optional
capabilities (EnvCtx*) through a single context bundle, you get a
remarkably cohesive system in pure -std=c11 without macro explosion or
C++ complexity.
Complete Architecture Recap: -std=c11 Polymorphic & Generic Toolkit
Layer C11 Mechanism Guarantee & Cost
Static Type Inference & Overloading _Generic anchored on the root
parameter + arity counter macro (GET_MACRO) Zero-cost compile-time
resolution; exact signature matching (including char (*)[N] and typed
function pointers)
Zero-Cost Specialization static inline leaf algorithms + static inline
callbacks/capabilities Inlined & devirtualized at -O2 via SROA and
constant propagation
1-Level Runtime Polymorphism BaseVal tagged union (TypeKind + union)
with _Generic wrap & switch unwrap Single-branch dispatch;
strict-aliasing safe; zero raw pointer casts
Two-Axis Status & Covariance Res_<Leaf> (error_t + success_t + type_t) +
_Generic lift_res to Res_BaseVal Preserves reserved core faults (1..31),
module errors (32+), and EOF nuances across subtype boundaries
Control Flow & Reflection TRY_ASSIGN / TRY_CATCH (goto CATCHME) +
from_enum / to_enum Single-evaluation early returns;
exhaustiveness-checked enum stringification
Clubbed Capabilities (No Globals) EnvCtx* bundling AllocCap + EmitCap,
defaulted via 1-arg / 2-arg arity overload Clean signatures;
deterministic testing with stack arenas and memory buffers
Why This Stays Maintainable at Scale
• Linear Growth Only: Adding a new leaf type to your closed category
requires adding one enum tag, one union field, and one line per _Generic
dispatch table—never N × M cross-product functions.
• Uniform Algorithm Source: Every algorithm is written once against
concrete leaf types (SliceLeaf, ListLeaf, PageLeaf) as static inline
functions, and both the compile-time _Generic path and the runtime
switch (b->type) path call that exact same implementation.
• Strict Standards Portability: Everything compiles cleanly under
-std=c11 -Wall -Wextra -Wpedantic -Wswitch with zero compiler extensions
required.
If you'd like, I can assemble a single, copy-pasteable reference header
(poly_c11.h) containing all of these primitives together with a brief
main() smoke test so you have a clean baseline to build on. Would that
be useful?
[ RF ]
Thanks GG. It'd be of interest though that like other accounts like this
session I'd use it for inspiration and write it my way, the account of
the "poly_c11.h".
[ GG ]
That makes complete sense, RF—building your own clean implementation
from first principles is the best way to keep every invariant tailored
to your exact codebase and conventions.
Here is a compact design checklist of the key C11 invariants we covered,
useful as a quick mental reference while you draft your own header:
• Anchor on the Root Parameter: Keep _Generic tables single-level and
anchored on the primary sequence/leaf expression, using GET_MACRO arity
routing only when optional parameters (EnvCtx*, bounds, or sentinels)
vary in count.
• Preserve Array Extents via Pointer-to-Array: Use char (*)[N] (or
single-member value structs) whenever compile-time buffer sizes need to
survive decay and distinguish branches in _Generic.
• Keep 0 as the Universal Zero-Init Invariant: Align TYPE_NONE = 0,
MOD_ERR_ERRORLESS = 0, and MOD_OK = 0 so {0} initialization always
yields a valid, deterministic empty state.
• Pair static inline Leaves with switch (type) Bases: Write algorithms
once on concrete leaf types (static inline) so compile-time _Generic
calls inline completely at -O2, while runtime BaseVal dispatch simply
delegates inside a -Wswitch-checked switch.
• Lift Covariantly via _Generic: Keep module-specific ErrorEnum and
SuccessEnum types intact on leaf holders (Res_<Leaf>), and use a single
lift_res(...) macro to widen them into Res_BaseVal across polymorphic
boundaries.
• Club Capabilities in One Context Pointer: Bundle allocators, emitters,
and sinks into EnvCtx* so functions stay free of hidden global state
without growing long parameter lists.
Enjoy putting your own stamp on it, Ross—reach out anytime you want to
bounce around edge cases or compiler diagnostics as you build it out.
Whenever you're ready, feel free to share any compiler warnings
(-Wpedantic, -Wswitch) or macro edge cases you run into while writing
your version, and we can troubleshoot them together.
[ RF ]
Thanks GG. Alright then, if it's considered a demonstration of ability
after possibility, emit "poly_c11.h".
[ GG ]
Here is a self-contained, strict -std=c11 -Wall -Wextra -Wpedantic
-Wswitch reference header (poly_c11.h) demonstrating the complete
architecture—compile-time _Generic overloading with arity routing,
fixed-size array preservation, 1-level tagged-union RTTI, two-axis
covariant holders, TRY_ASSIGN / TRY_CATCH, bidirectional enum
reflection, and clubbed EnvCtx capabilities.
c
#ifndef POLY_C11_H
#define POLY_C11_H
#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdalign.h>
#include <string.h>
#include <assert.h>
/* =========================================================================
* 1. Closed Category Discriminants & Two-Axis Status Conventions
*
========================================================================= */
#define TYPE_KIND_ENTRIES(X) \
X(TYPE_NONE) \
X(TYPE_SLICE) \
X(TYPE_LIST) \
X(TYPE_PAGE)
typedef enum {
TYPE_NONE = 0,
TYPE_SLICE,
TYPE_LIST,
TYPE_PAGE
} TypeKind;
typedef enum {
MOD_ERR_ERRORLESS = 0,
MOD_ERR_INVALID_TAG = 1,
MOD_ERR_OUT_OF_BOUNDS = 2,
MOD_ERR_UNSUPPORTED = 3,
MOD_ERR_NO_MEMORY = 4,
MOD_ERR_RESERVED_MAX = 31
} CoreError;
typedef enum {
MOD_OK = 0
} CoreSuccess;
#define SEQ_ERR_ENTRIES(X) \
X(SEQ_ERR_ERRORLESS) \
X(SEQ_ERR_BAD_SENTINEL) \
X(SEQ_ERR_TRUNCATED)
typedef enum {
SEQ_ERR_ERRORLESS = MOD_ERR_ERRORLESS,
SEQ_ERR_BAD_SENTINEL = 32,
SEQ_ERR_TRUNCATED = 33
} SeqError;
#define SEQ_OK_ENTRIES(X) \
X(SEQ_OK) \
X(SEQ_OK_EOF) \
X(SEQ_OK_PARTIAL)
typedef enum {
SEQ_OK = MOD_OK,
SEQ_OK_EOF = 1,
SEQ_OK_PARTIAL = 2
} SeqSuccess;
/* =========================================================================
* 2. Leaf Types, Fixed-Buffer Value Wrapper, & 1-Level Tagged Base
*
========================================================================= */
#ifndef POLY_PAGE_SIZE
#define POLY_PAGE_SIZE 64
#endif
typedef struct {
const char* ptr;
size_t len;
} SliceLeaf;
typedef struct {
void* head;
const void* sentinel;
} ListLeaf;
typedef struct {
_Alignas(max_align_t) char data[POLY_PAGE_SIZE];
} PageLeaf;
typedef struct {
TypeKind type;
union {
SliceLeaf slice;
ListLeaf list;
PageLeaf page;
} as;
} BaseVal;
/* =========================================================================
* 3. Typed Class Holders & Covariant Base Holder
*
========================================================================= */
#define DEFINE_CLASS_HOLDER(PayloadT, SuccessEnum, ErrorEnum) \
typedef struct { \
TypeKind type; \
ErrorEnum err; \
SuccessEnum ok; \
PayloadT val; \
} Res_##PayloadT
DEFINE_CLASS_HOLDER(SliceLeaf, SeqSuccess, SeqError);
DEFINE_CLASS_HOLDER(ListLeaf, SeqSuccess, SeqError);
DEFINE_CLASS_HOLDER(PageLeaf, SeqSuccess, SeqError);
typedef struct {
TypeKind type;
int err;
int ok;
BaseVal val;
} Res_BaseVal;
/* =========================================================================
* 4. Compile-Time Type Tagging, Wrapping, & Covariant Lifting
*
========================================================================= */
#define type_tag_of(x) _Generic((x), \
SliceLeaf: TYPE_SLICE, \
SliceLeaf*: TYPE_SLICE, \
ListLeaf: TYPE_LIST, \
ListLeaf*: TYPE_LIST, \
PageLeaf: TYPE_PAGE, \
PageLeaf*: TYPE_PAGE, \
default: TYPE_NONE \
)
#define ret_ok(ResT, value) \
((ResT){ .type = type_tag_of(value), .err = 0, .ok = 0, .val = (value) })
#define ret_ok_code(ResT, code, value) \
((ResT){ .type = type_tag_of(value), .err = 0, .ok = (code), .val =
(value) })
#define ret_err(ResT, zero_val, err_code) \
((ResT){ .type = type_tag_of(zero_val), .err = (err_code), .ok = 0 })
static inline BaseVal wrap_slice(SliceLeaf s) {
return (BaseVal){ .type = TYPE_SLICE, .as.slice = s };
}
static inline BaseVal wrap_list(ListLeaf l) {
return (BaseVal){ .type = TYPE_LIST, .as.list = l };
}
static inline BaseVal wrap_page(PageLeaf p) {
return (BaseVal){ .type = TYPE_PAGE, .as.page = p };
}
static inline BaseVal wrap_base(BaseVal b) {
return b;
}
#define wrap(x) _Generic((x), \
SliceLeaf: wrap_slice, \
ListLeaf: wrap_list, \
PageLeaf: wrap_page, \
BaseVal: wrap_base \
)(x)
static inline Res_BaseVal lift_slice_res(Res_SliceLeaf r) {
return (Res_BaseVal){
.type = r.type,
.err = (int)r.err,
.ok = (int)r.ok,
.val = (r.err == SEQ_ERR_ERRORLESS) ? wrap_slice(r.val) : (BaseVal){0}
};
}
static inline Res_BaseVal lift_list_res(Res_ListLeaf r) {
return (Res_BaseVal){
.type = r.type,
.err = (int)r.err,
.ok = (int)r.ok,
.val = (r.err == SEQ_ERR_ERRORLESS) ? wrap_list(r.val) : (BaseVal){0}
};
}
static inline Res_BaseVal lift_page_res(Res_PageLeaf r) {
return (Res_BaseVal){
.type = r.type,
.err = (int)r.err,
.ok = (int)r.ok,
.val = (r.err == SEQ_ERR_ERRORLESS) ? wrap_page(r.val) : (BaseVal){0}
};
}
static inline Res_BaseVal lift_base_res(Res_BaseVal r) {
return r;
}
#define lift_res(r) _Generic((r), \
Res_SliceLeaf: lift_slice_res, \
Res_ListLeaf: lift_list_res, \
Res_PageLeaf: lift_page_res, \
Res_BaseVal: lift_base_res \
)(r)
/* =========================================================================
* 5. Standard -std=c11 TRY_ASSIGN & TRY_CATCH Propagation
*
========================================================================= */
#define TRY_ASSIGN(out_var, ExprResT, expr, CallerResT) do { \
ExprResT _r = (expr); \
if (_r.err != MOD_ERR_ERRORLESS) { \
return (CallerResT){ \
.type = _r.type, \
.err = _r.err, \
.ok = _r.ok \
}; \
} \
(out_var) = _r.val; \
} while (0)
#define TRY_OK(out_var, ExprResT, expr, CallerResT) do { \
ExprResT _r = (expr); \
if (_r.err != MOD_ERR_ERRORLESS || _r.ok != 0) { \
return (CallerResT){ \
.type = _r.type, \
.err = _r.err, \
.ok = _r.ok \
}; \
} \
(out_var) = _r.val; \
} while (0)
#define TRY_CATCH(out_var, ExprResT, expr, caught_res, catch_label) do { \
ExprResT _r = (expr); \
if (_r.err != MOD_ERR_ERRORLESS) { \
(caught_res) = lift_res(_r); \
goto catch_label; \
} \
(out_var) = _r.val; \
} while (0)
/* =========================================================================
* 6. Bidirectional Enum Reflection (from_enum / to_enum)
*
========================================================================= */
#define POLY_CASE_TO_STR(sym) case sym: return #sym;
#define DEFINE_FROM_ENUM(EnumType, fn_name, ENTRIES_MACRO) \
static inline const char* fn_name(EnumType v) { \
switch (v) { \
ENTRIES_MACRO(POLY_CASE_TO_STR) \
default: return "UNKNOWN_" #EnumType; \
} \
}
DEFINE_FROM_ENUM(TypeKind, type_kind_to_str, TYPE_KIND_ENTRIES)
DEFINE_FROM_ENUM(SeqError, seq_err_to_str, SEQ_ERR_ENTRIES)
DEFINE_FROM_ENUM(SeqSuccess, seq_ok_to_str, SEQ_OK_ENTRIES)
#define from_enum(e) _Generic((e), \
TypeKind: type_kind_to_str, \
SeqError: seq_err_to_str, \
SeqSuccess: seq_ok_to_str \
)(e)
typedef enum {
ENUM_DOMAIN_TYPE_KIND = 1,
ENUM_DOMAIN_SEQ_ERR,
ENUM_DOMAIN_SEQ_OK
} EnumDomain;
typedef struct {
TypeKind type;
int err;
int ok;
int val;
} Res_Enum;
#define POLY_IF_STR_MATCH(sym) \
if (strcmp(name, #sym) == 0) { \
return (Res_Enum){ .type = TYPE_NONE, .err = MOD_ERR_ERRORLESS, .val =
(int)(sym) }; \
}
static inline Res_Enum to_enum(const char* name, EnumDomain domain) {
if (!name) {
return (Res_Enum){ .err = MOD_ERR_INVALID_TAG };
}
switch (domain) {
case ENUM_DOMAIN_TYPE_KIND:
TYPE_KIND_ENTRIES(POLY_IF_STR_MATCH)
break;
case ENUM_DOMAIN_SEQ_ERR:
SEQ_ERR_ENTRIES(POLY_IF_STR_MATCH)
break;
case ENUM_DOMAIN_SEQ_OK:
SEQ_OK_ENTRIES(POLY_IF_STR_MATCH)
break;
}
return (Res_Enum){ .err = MOD_ERR_OUT_OF_BOUNDS };
}
/* =========================================================================
* 7. Clubbed Capabilities (Allocator & Emitter Context)
*
========================================================================= */
typedef struct {
void* (*alloc)(void* state, size_t size, size_t align);
void (*free)(void* state, void* ptr, size_t size);
void* state;
} AllocCap;
typedef struct {
int (*write_bytes)(void* state, const char* data, size_t len);
void* state;
} EmitCap;
typedef struct {
AllocCap mem;
EmitCap out;
EmitCap err_out;
} EnvCtx;
static inline SliceLeaf* alloc_slice_impl(EnvCtx* ctx) {
return (SliceLeaf*)ctx->mem.alloc(ctx->mem.state, sizeof(SliceLeaf),
_Alignof(SliceLeaf));
}
static inline ListLeaf* alloc_list_impl(EnvCtx* ctx) {
return (ListLeaf*)ctx->mem.alloc(ctx->mem.state, sizeof(ListLeaf),
_Alignof(ListLeaf));
}
static inline PageLeaf* alloc_page_impl(EnvCtx* ctx) {
return (PageLeaf*)ctx->mem.alloc(ctx->mem.state, sizeof(PageLeaf),
_Alignof(PageLeaf));
}
Use code with caution.
#define alloc_for(ctx, expr) _Generic((expr),
SliceLeaf: alloc_slice_impl,
SliceLeaf*: alloc_slice_impl,
ListLeaf: alloc_list_impl,
ListLeaf*: alloc_list_impl,
PageLeaf: alloc_page_impl,
PageLeaf*: alloc_page_impl
)(ctx)
static inline int emit_cstr(EnvCtx* ctx, const char* s) {
if (!ctx || !ctx->out.write_bytes || !s) {
return -1;
}
return ctx->out.write_bytes(ctx->out.state, s, strlen(s));
}
static inline int emit_slice(EnvCtx* ctx, SliceLeaf s) {
if (!ctx || !ctx->out.write_bytes || !s.ptr) {
return -1;
}
return ctx->out.write_bytes(ctx->out.state, s.ptr, s.len);
}
static inline int emit_page(EnvCtx* ctx, PageLeaf p) {
if (!ctx || !ctx->out.write_bytes) {
return -1;
}
return ctx->out.write_bytes(ctx->out.state, p.data, sizeof(p.data));
}
static inline int emit_list(EnvCtx* ctx, ListLeaf l) {
(void)l;
return emit_cstr(ctx, "");
}
static inline int emit_base(EnvCtx* ctx, BaseVal b) {
switch (b.type) {
case TYPE_SLICE: return emit_slice(ctx, b.as.slice);
case TYPE_LIST: return emit_list(ctx, b.as.list);
case TYPE_PAGE: return emit_page(ctx, b.as.page);
case TYPE_NONE:
default: return emit_cstr(ctx, "");
}
}
#define emit_with_ctx(ctx, expr) _Generic((expr),
SliceLeaf: emit_slice,
ListLeaf: emit_list,
PageLeaf: emit_page,
char*: emit_cstr,
const char*: emit_cstr,
BaseVal: emit_base
)((ctx), (expr))
/* =========================================================================
•
8. Arity + Type Overloading Across Fixed Arrays, Slices, & C-Strings
•
========================================================================= */
static inline SliceLeaf slice_from_cstr(const char* s) {
return (SliceLeaf){ .ptr = s, .len = s ? strlen(s) : 0 };
}
static inline SliceLeaf slice_from_ptr_len(const char* s, size_t len) {
return (SliceLeaf){ .ptr = s, .len = len };
}
static inline SliceLeaf slice_from_arr64(char (*buf)[POLY_PAGE_SIZE]) {
return (SliceLeaf){ .ptr = *buf, .len = sizeof(*buf) };
}
#define POLY_GET_MACRO(_1, _2, NAME, ...) NAME
#define AS_SLICE_1(a) _Generic((a),
char*: slice_from_cstr,
const char*: slice_from_cstr,
char (*)[POLY_PAGE_SIZE]: slice_from_arr64
)(a)
#define AS_SLICE_2(a, b) _Generic((a),
char*: slice_from_ptr_len,
const char*: slice_from_ptr_len
)((a), (b))
#define as_slice(...)
POLY_GET_MACRO(VA_ARGS, AS_SLICE_2, AS_SLICE_1)(VA_ARGS)
/* =========================================================================
•
9. Zero-Cost Leaf Algorithm + Polymorphic Base Adapter
•
========================================================================= */
static inline Res_SliceLeaf slice_take_head(SliceLeaf* s) {
if (!s || !s->ptr) {
return ret_err(Res_SliceLeaf, (SliceLeaf){0},
(SeqError)MOD_ERR_INVALID_TAG);
}
if (s->len == 0) {
return ret_ok_code(Res_SliceLeaf, SEQ_OK_EOF, ((SliceLeaf){0}));
}
SliceLeaf head = { .ptr = s->ptr, .len = 1 };
s->ptr += 1;
s->len -= 1;
return ret_ok(Res_SliceLeaf, head);
}
static inline Res_BaseVal base_take_head(BaseVal* b) {
if (!b) {
return (Res_BaseVal){ .type = TYPE_NONE, .err = MOD_ERR_INVALID_TAG };
}
switch (b->type) {
case TYPE_SLICE:
return lift_res(slice_take_head(&b->as.slice));
case TYPE_LIST:
return (Res_BaseVal){ .type = TYPE_LIST, .err = MOD_ERR_UNSUPPORTED };
case TYPE_PAGE:
return (Res_BaseVal){ .type = TYPE_PAGE, .err = MOD_ERR_UNSUPPORTED };
case TYPE_NONE:
default:
return (Res_BaseVal){ .type = TYPE_NONE, .err = MOD_ERR_INVALID_TAG };
}
}
#endif /* POLY_C11_H */
<FollowUp>
Feel free to adapt any piece of this layout into your own header—let me
know if you want to test or refine any specific macro expansion or edge
case.
</FollowUp>
[ RF ]
Thanks GG. I'll share this and also later consult if for these sorts of
ideas, though mostly I'm having some account of "u_alloc.h, u_stdio.h,
u_lister.h", basically as an account of utils/utilities, then about the
library boundaries which are of interest, "m_cfg.h, m_pro.h, m_res.h",
or as alike "m_cnfg.h, m_prto.h, m_rsrc.h", those then having some
accounts of common types, for examples about the utils, and own types,
about the conventions and their functions and so on (their classes).
[ GG ]
That layering—separating foundational utilities (u_*.h) from
domain/protocol modules (m_*.h)—maps cleanly onto the C11 polymorphism
and capability patterns we just built.
Architectural Layering (u_*.h vs. m_*.h)
Layer Headers Primary Responsibility Key Types & Patterns
Core Status & Base Primitives u_base.h (or shared prelude) Closed
category tags, core error floor (0..31), BaseVal, TRY_*, from_enum /
to_enum TypeKind, CoreError, Res_BaseVal, EnvCtx
Utility Capabilities (u_*) u_alloc.h, u_stdio.h, u_lister.h Concrete
capability implementations & generic container/sequence adapters
AllocCap (arenas/pools), EmitCap (FILE*/buffers), SliceLeaf, ListLeaf
(null/sentinel)
Module Boundaries (m_*) m_cnfg.h, m_prto.h, m_rsrc.h Domain-specific
state machines, wire protocols, and resource lifecycles Module-specific
ErrorEnum (32+) & SuccessEnum, Res_<ModuleObj>, lifted to Res_BaseVal
Key Boundary Conventions
• Shared Core vs. Module-Owned Enums: Keep CoreError (0..31) and
TypeKind in the utility base so u_alloc.h, u_stdio.h, and u_lister.h
never depend on m_* headers. Each m_*.h module defines its own ErrorEnum
starting at 32 (e.g., CNFG_ERR_PARSE = 32, PRTO_ERR_FRAMING = 32,
RSRC_ERR_EXHAUSTED = 32) while lifting seamlessly into Res_BaseVal
across module boundaries.
• Capability Injection Across Boundaries: u_alloc.h and u_stdio.h
provide the concrete AllocCap and EmitCap adapters that populate EnvCtx.
The m_*.h modules accept EnvCtx* as their root context parameter and
dispatch via _Generic (alloc_for(ctx, expr), emit_with_ctx(ctx, expr)),
keeping every module 100% free of direct malloc or stdout calls.
• Sequence Adapters (u_lister.h) as the Glue: u_lister.h houses the
sequence views (SliceLeaf, null-linked and sentinel-linked ListLeaf,
fixed PageLeaf) so m_cnfg.h (config parsing), m_prto.h (protocol
framing), and m_rsrc.h (resource descriptors) all consume and emit
uniform sequences without duplicating traversal code.
Whenever you're ready to sketch out the interfaces or contracts for
u_lister.h or the m_cnfg.h / m_prto.h / m_rsrc.h module boundaries, we
can pick right up from here, RF.
Would you like to look at how u_lister.h can unify null-link and
sentinel-link lists under a single _Generic interface, or how m_cnfg.h /
m_prto.h / m_rsrc.h register their module-specific status enums into the
shared reflection tables?
[ RF ]
Thanks GG. I figure this is quite a fair amount of material to digest,
and that it well goes to show that since C11 that accounts of
type-inference and compile-time and later run-time
generification/specialization/overloading and polymorphism and covariant
return-types, that the type-appease makes for that the compiler may be
greatly appeased as with regards to type-safety and neither much
boilerplate, macros, nor the explosion of code under combinatorics.
[ GG ]
That captures the exact takeaway, RF. Modern C11 gives you a clean sweet
spot where the compiler's type system works with you rather than
requiring heavy macro code generation or C++ template machinery:
• Static Type Safety Without Combinatorial Bloat: _Generic acts as a
thin, zero-cost compile-time router anchored on your root types, while
static inline leaf algorithms let the optimizer collapse abstractions
down to direct instructions.
• Clean Runtime Boundaries: A 1-level tagged union (BaseVal) paired with
two-axis covariant holders (Res_<T> → Res_BaseVal) bridges compile-time
precision and runtime polymorphism without raw pointer casts or loss of
status detail.
• Modular Independence: Threading capabilities through a single EnvCtx*
keeps your u_* utilities and m_* domain modules decoupled, testable, and
free of hidden global state.
Take your time digesting and shaping it into your u_* and m_* headers,
Ross—it was a pleasure working through the design with you. Reach out
whenever you're ready for the next piece.
Whenever you want to continue, we can dive into u_lister.h (unifying
null-linked and sentinel-linked list adapters) or m_cnfg.h / m_prto.h /
m_rsrc.h module boundary contracts.
[ RF ]
Thanks GG. I imagine that if there are any perceived questions or
problems, now's the time to raise them.
[ GG ]
If you are stepping into drafting u_alloc.h, u_stdio.h, u_lister.h, and
the m_*.h modules right now, there are five subtle C11 traps worth
keeping on your radar so they don't trip up your compiler or cause
subtle UB later:
1. Qualifier Sensitivity in _Generic (const Pointers)
_Generic strips top-level qualifiers from values (const int matches
int), not from pointed-to types (const SliceLeaf* does not match
SliceLeaf*).
• Trap: If a helper function receives const SliceLeaf* s and calls
type_tag_of(s) or emit_with_ctx(ctx, s), compilation fails unless const
SliceLeaf* is listed alongside SliceLeaf* in the _Generic association table.
• Fix: Consistently register both T* and const T* in pointer-accepting
_Generic maps.
2. Integer Promotion in _Generic Controlling Expressions
In C11, _Generic does not perform default integer promotions on the
controlling expression, yet character constants like 'a' have type int
in C (unlike char in C++).
• Trap: If you dispatch on char vs. int (or uint8_t vs. enum), passing
'x' matches int, while passing a char variable matches char. Also, two
enum types that share the same underlying integer representation can
trigger a "compatible types in _Generic" error on certain compilers if
placed in the same _Generic block without distinct wrapper structs or
distinct underlying ranges.
• Fix: Test your _Generic enum tables under both GCC and Clang with
-Wpedantic early, since C11 leaves the exact underlying integer type of
each enum implementation-defined.
3. Enum Collision When Lifting m_cnfg.h, m_prto.h, and m_rsrc.h
Each module (m_cnfg.h, m_prto.h, m_rsrc.h) can safely start its own
ErrorEnum at 32 (MOD_ERR_RESERVED_MAX + 1), provided every Res_BaseVal
carries its TypeKind / ModuleKind discriminant alongside int err.
• Trap: If a caller checks if (res.err == CNFG_ERR_PARSE) on a
Res_BaseVal without first checking res.type == MOD_CNFG, a
PRTO_ERR_FRAMING (also 32) will false-positive as a config parse error.
• Fix: Enforce a strict invariant: module-specific error codes (>= 32)
are only inspected inside a switch (res.type) branch; outside the
switch, only core errors (1..31) are compared directly.
4. Return-by-Value ABI Cost on Large PageLeaf Holders
Small structs like SliceLeaf (16 bytes) and ListLeaf (16 bytes) return
in two CPU registers (RAX/RDX on x86-64, X0/X1 on ARM64) with zero
memory traffic.
• Trap: Once PageLeaf (char data or 4096) is embedded inside BaseVal and
Res_BaseVal, returning Res_BaseVal by value copies the entire union size
via a hidden stack pointer (sret) on every call, even when returning a
tiny SliceLeaf or an error.
• Fix: Keep value-embedded buffers in BaseVal small (e.g., <= 64 bytes),
or have PageLeaf hold a char (*page) pointer-to-array so BaseVal stays
fixed at 24–32 bytes regardless of page size.
5. Include-Order & Open Registration Across u_* and m_*
Because _Generic tables are closed at the point where the macro expands,
u_base.h cannot list m_cnfg.h types unless u_base.h knows about them—or
unless each m_*.h defines its own module-local _Generic wrapper that
delegates to u_base.h for core types in its default: branch.
• Fix: Use default: chaining: m_cnfg.h defines cnfg_emit(ctx, x) with
default: emit_with_ctx(ctx, x). That keeps u_*.h 100% decoupled from
m_*.h while giving module code a single unified macro call.
Everything else is on solid ground, RF—those five invariants will save
you any surprises as you lay out the headers.
Would you like to examine default: chaining across u_*.h and m_*.h in a
quick snippet before you start writing your headers, or are you all set
to dive in?
[ RF ]
Thanks GG. That'll do and is a nice exposition. I'll transcribe this and
later consult it when mostly working on the "library interface
conventions & idiom & discipline & design" and "component interface
conventions & ...".
[ GG ]
You're very welcome, RF. That will serve as a solid blueprint when you
sit down to formalize your library and component interface conventions
across u_*.h and m_*.h.
Enjoy the transcription and the design work ahead, Ross—reach out
anytime you're ready for the next round.
Whenever you pick up the library and component interface conventions
again, feel free to drop in a draft header or interface contract to
review together.
[ RF ]
Thanks GG. Good-day, good-bye.
[ GG ]
Good-day, RF. Good-bye!
Re: Inversion-of-control and dependency-injection in C
Author: bartc
Date: Wed, 18 Nov 2026 20:40
Date: Wed, 18 Nov 2026 20:40
6 lines
1780 bytes
1780 bytes
On 18/11/2026 19:58, Ross Finlayson wrote: <More than 3300 lines snipped> You're a nutter.
Re: Inversion-of-control and dependency-injection in C
Author: Chris M. Thomasson
Date: Wed, 18 Nov 2026 21:14
Date: Wed, 18 Nov 2026 21:14
211 lines
11889 bytes
11889 bytes
On 11/18/2026 2:30 AM, Ross Finlayson wrote: > On 11/17/2026 03:46 PM, Chris M. Thomasson wrote: >> On 11/17/2026 1:00 AM, Ross Finlayson wrote: >>> On 11/16/2026 01:10 PM, Chris M. Thomasson wrote: >>>> On 11/16/2026 12:04 PM, Ross Finlayson wrote: >>>>> On 11/16/2026 10:09 AM, Bonita Montero wrote: >>>>>> Am 13.11.2026 um 23:50 schrieb Ross Finlayson: >>>>>> >>>>>>> So, here's one. Say you got a server process for sockets of the >>>>>>> connection-oriented or datagram-wise or association-oriented like >>>>>>> TCP, UDP, or SCTP, and it manages the connecting and the sending and >>>>>>> receiving about a million of those and is sort of fixed-size and >>>>>>> stable in a usual runtime. So, how do you design the interface, >>>>>>> about stuff like the state-machine of _protocols_, all about >>>>>>> _protocols_, in the application-layer and above, say, for example >>>>>>> the incremental-parsing and the state-machine of the protocol >>>>>>> and sub-protocols and upgrade-protocols and the like, what sort >>>>>>> of abstraction with suitable-defaults and reasonable-opinions >>>>>>> makes for having any sort protocol as a composable library. >>>>>> Use C++20 coroutines with Bost.ASIO and io_uring. This gives >>>>>> as less code as possible with nearly optimal I/O performance. >>>>> >>>>> Thanks for writing Bonita. I'd infer from "schrieb" that >>>>> your user-agent locale country/language is DE/de or as >>>>> variously for example about 2-letter and 3-letter country >>>>> codes and accounts of language or ISO 601 or what I forget. >>>>> Mann kann nur kleine Deutsch gesprechern, nicht viel das >>>>> hier doch, aber los. Mein Wortschatz, es ist kaput. >>>>> >>>>> >>>>> That said, _why_ I specifically am not using epoll/kqueue >>>>> or io_uring instead pselect not select or poll, is: >>>>> if you overload the epoll red/black tree or io_iuring queues >>>>> respectively, they drop messages. Now, most of the time, >>>>> that's accommodated by some absurdly simple back-end like >>>>> "send" that tolerates drops itself, in things like message-bus. >>>>> Then, epoll for example, on a wake-up or return from the blocking >>>>> syscall, doesn't notify twice when there remains data to be read. >>>>> Then, pselect() may be blocking and furthermore with the impact >>>>> that the kernel polls the sockets busily, yet, pselect() can >>>>> timeout itself, for example, and register interest on active >>>>> selectors and only periodically eg 5ms register interest on >>>>> active + inactive selectors (file-descriptors). >>>>> >>>>> Then, there's a fact that POSIX runtimes have signals, >>>>> then, that pselect() behaves in a more defined manner. >>>>> >>>>> Another key distinction is that: buffers for use with >>>>> epoll and I believe also kqueue, or io_uring, must >>>>> be "pinned" with mlock() or what, to physical memory, >>>>> for the kernel to treat them, instead of copying from >>>>> user-space to kernel-space or vice-versa or however >>>>> the runtime may care to swap pages under addresses >>>>> with making copies, that for accounts of vector I/O, >>>>> scatter/gather yet mostly vector I/O for the bus boss >>>>> the DMA, it's just plain old heap RAM. >>>>> >>>>> >>>>> Then, also pselect() is POSIX and so it's portable. >>>>> It's less code if it doesn't need multiple back-ends >>>>> for various platforms' implementations of I/O multiplexing. >>>>> >>>>> >>>> >>>> Huh? Do you have a clue at all about this? From what you wrote, perhaps >>>> not. Sigh. >>>> >>> >>> >>> About epoll and dropping reads, it's not the same as io_uring >>> which has fixed-sized queues and if it gets full drops those >>> in the kernel, it's about the edge-triggered case or "e"-poll >>> for edge-triggered poll, vis-a-vis the usual account of poll >>> or select or pselect as level-triggered, that there's perceived >>> to be an edge case where epoll would lose notice of a notification. >>> The idea is that while blocking in epoll_wait, that the process >>> gets a signal, then, the kernel interrupts and runs the signal-handler >>> and returning from epoll_wait it gets EINTR, _or_, according to >>> a policy of whether to re-try blocking sys-calls the kernel interrupts >>> and runs the signal-handler and the process enters epoll_wait again. >>> >>> So, I'm under the impression that there's a race-condition where >>> the process gets a signal while blocked in epoll_wait, then according >>> to one of two policies, EAGAIN error-handling or re-try, that it >>> loses the notification, not the packet. The packet is still on >>> the socket to be read, the notification of it was lost. >>> >>> The pselect simply doesn't have that problem, it's level-triggered, >>> and however it re-enters pselect after getting interrupted, >>> as long as there's data yet to read, it will get notified. >>> >>> >>> Then also epoll might not need mlock'ed memory like io_uring does. >>> >>> >>> >>> That's about it. >>> >>> >>> >>> >> >> pselect() is simple, portable, and for many workloads fast enough. Those >> are perfectly valid engineering arguments. >> >> For a high-performance server, though, well, shit. I personally wouldn't >> be reaching for pselect() at all. Uggg... >> >> One thing I like about mechanisms such as io_uring and IOCP is that they >> encourage thinking about capacity up front. You tend to preallocate the >> resources the system needs to operate, size your queues and pools >> appropriately, and define behavior for resource pressure. Thats >> generally preferable to discovering in the god damn hot path that yet >> another allocation is required! Fuck! >> >> On Windows, large scale IOCP servers have long used techniques such as >> so called, zero byte receives, and preallocated connection state to >> reduce memory pressure and avoid per-operation allocations. Similar >> ideas apply elsewhere, for sure. The goal is usually to enter a pressure >> mode before critical resources are exhausted, not to keep allocating >> indefinitely and hope for the best. >> >> When resources start getting tight, I would rather see the server shed >> load, evict caches, shorten timeouts, disconnect stale clients, or >> refuse new work than continue consuming memory until the operating >> system is in trouble. Running out of capacity should be a planned state, >> not a surprise. >> >> That's one of the reasons fixed pools and preallocated state appeal to >> me for systems under heavy load. >> > > Preallocated state is another matter altogether, this sort of approach > mentioned presumes fixed resources, for example when a memory-pool is > in-use, to stop reads and then TCP/IP itself closes the receive window. Preallocated state is a nice way to get a 100% guarantee that everything works as-is. If any more (extra) connections come in, at least in IOCP we can use several means to expand the state. If we succeeded tag the per_io and/or per_socket state with being "outside" of the pool. So on shutdown, graceful close, aborted, etc. We know well, perhaps we need to call free, or whatever, or even closesocket. With IOCP we can create all of our sockets up front if we want. The windozer has that fun: https://learn.microsoft.com/en-us/previous-versions/windows/desktop/legacy/ms737757(v=vs.85) It allows a socket to be reused in either AcceptEx or ConnectEx: https://learn.microsoft.com/en-us/windows/win32/api/mswsock/nf-mswsock-acceptex https://learn.microsoft.com/en-us/windows/win32/api/mswsock/nc-mswsock-lpfn_connectex With io_uring, we would want to dedicate the whole box, or a part of it, to be okay. This is for IO. Ideally we preallocate as much as the box can handle without caking its pants. > > The "pressure" closes the receive-side, and clients wait (the network > buffers). > > These aren't necessarily huge nodes with vertical scaling, they're > mid-sized boxen that have to share all the resources with many other > processes. > > So, we may entirely separate fixed-size allocations and > notification/polling subsystems as concerns, about the > box: and the network. > > For example, then often these are virtualized/containerized > mid-size boxen, where it's not only that processes shouldn't > contend/thrash with the allocator: also when there's memory-pressure > that the biggest one gets booted, or "OOMKiller". > > > Then, for example, since the box already has connection limits, > and, for example, these get exhausted before this sort of > "I/O-handle-bound process-model", it naturally throttles itself. > Where pselect() has a limit of FD_SETSIZE handles, of open connections, > and furthermore the numbered file-descriptors must be less than > FD_SETSIZE, then scaling out in child-processes or workers/laborers, > is old-fashioned and stable. > > launcher <- eg, systemd, privileged port > leader <- 1,000-many potential laborers (child processes), fixed-heap > listener <- accepts TCP or 1,000-many potential UDP "connections" > laborer(s) <- 1,000-many potential connections > logger <- funnels the logs > logmet <- funnels the metrics > logdmp <- funnels dumps > loconsole <- optional REPL > > This is "1,000-many file-descriptors for connections, a dozen > for a 'process-protocol' among the 'process-tree' the 'process-group', > and 0/1/2 being stdin/stdout/stderr and 4/5/6 being > 'stdlog/stdmet/stddmp'", that being an "I/O-handle-bounde process-model". > > > It makes sense that a hog with the flops on dedicated hardware > can use all the resources for itself, that not usually being the case. > The "thinking about capacity up-front" is a great idea, here that > nobody knows what the front-end and back-end capacity will eventually > be, for protocols like TCP/IP that "surface the pressure" and a box > that doesn't burst under the burst-y. > > > It's appreciated these sorts of accounts. > >
Re: Inversion-of-control and dependency-injection in C
Author: Chris M. Thomasson
Date: Wed, 18 Nov 2026 21:18
Date: Wed, 18 Nov 2026 21:18
168 lines
10127 bytes
10127 bytes
On 11/18/2026 1:14 PM, Chris M. Thomasson wrote: > On 11/18/2026 2:30 AM, Ross Finlayson wrote: >> On 11/17/2026 03:46 PM, Chris M. Thomasson wrote: >>> On 11/17/2026 1:00 AM, Ross Finlayson wrote: >>>> On 11/16/2026 01:10 PM, Chris M. Thomasson wrote: >>>>> On 11/16/2026 12:04 PM, Ross Finlayson wrote: >>>>>> On 11/16/2026 10:09 AM, Bonita Montero wrote: >>>>>>> Am 13.11.2026 um 23:50 schrieb Ross Finlayson: >>>>>>> >>>>>>>> So, here's one. Say you got a server process for sockets of the >>>>>>>> connection-oriented or datagram-wise or association-oriented like >>>>>>>> TCP, UDP, or SCTP, and it manages the connecting and the sending >>>>>>>> and >>>>>>>> receiving about a million of those and is sort of fixed-size and >>>>>>>> stable in a usual runtime. So, how do you design the interface, >>>>>>>> about stuff like the state-machine of _protocols_, all about >>>>>>>> _protocols_, in the application-layer and above, say, for example >>>>>>>> the incremental-parsing and the state-machine of the protocol >>>>>>>> and sub-protocols and upgrade-protocols and the like, what sort >>>>>>>> of abstraction with suitable-defaults and reasonable-opinions >>>>>>>> makes for having any sort protocol as a composable library. >>>>>>> Use C++20 coroutines with Bost.ASIO and io_uring. This gives >>>>>>> as less code as possible with nearly optimal I/O performance. >>>>>> >>>>>> Thanks for writing Bonita. I'd infer from "schrieb" that >>>>>> your user-agent locale country/language is DE/de or as >>>>>> variously for example about 2-letter and 3-letter country >>>>>> codes and accounts of language or ISO 601 or what I forget. >>>>>> Mann kann nur kleine Deutsch gesprechern, nicht viel das >>>>>> hier doch, aber los. Mein Wortschatz, es ist kaput. >>>>>> >>>>>> >>>>>> That said, _why_ I specifically am not using epoll/kqueue >>>>>> or io_uring instead pselect not select or poll, is: >>>>>> if you overload the epoll red/black tree or io_iuring queues >>>>>> respectively, they drop messages. Now, most of the time, >>>>>> that's accommodated by some absurdly simple back-end like >>>>>> "send" that tolerates drops itself, in things like message-bus. >>>>>> Then, epoll for example, on a wake-up or return from the blocking >>>>>> syscall, doesn't notify twice when there remains data to be read. >>>>>> Then, pselect() may be blocking and furthermore with the impact >>>>>> that the kernel polls the sockets busily, yet, pselect() can >>>>>> timeout itself, for example, and register interest on active >>>>>> selectors and only periodically eg 5ms register interest on >>>>>> active + inactive selectors (file-descriptors). >>>>>> >>>>>> Then, there's a fact that POSIX runtimes have signals, >>>>>> then, that pselect() behaves in a more defined manner. >>>>>> >>>>>> Another key distinction is that: buffers for use with >>>>>> epoll and I believe also kqueue, or io_uring, must >>>>>> be "pinned" with mlock() or what, to physical memory, >>>>>> for the kernel to treat them, instead of copying from >>>>>> user-space to kernel-space or vice-versa or however >>>>>> the runtime may care to swap pages under addresses >>>>>> with making copies, that for accounts of vector I/O, >>>>>> scatter/gather yet mostly vector I/O for the bus boss >>>>>> the DMA, it's just plain old heap RAM. >>>>>> >>>>>> >>>>>> Then, also pselect() is POSIX and so it's portable. >>>>>> It's less code if it doesn't need multiple back-ends >>>>>> for various platforms' implementations of I/O multiplexing. >>>>>> >>>>>> >>>>> >>>>> Huh? Do you have a clue at all about this? From what you wrote, >>>>> perhaps >>>>> not. Sigh. >>>>> >>>> >>>> >>>> About epoll and dropping reads, it's not the same as io_uring >>>> which has fixed-sized queues and if it gets full drops those >>>> in the kernel, it's about the edge-triggered case or "e"-poll >>>> for edge-triggered poll, vis-a-vis the usual account of poll >>>> or select or pselect as level-triggered, that there's perceived >>>> to be an edge case where epoll would lose notice of a notification. >>>> The idea is that while blocking in epoll_wait, that the process >>>> gets a signal, then, the kernel interrupts and runs the signal-handler >>>> and returning from epoll_wait it gets EINTR, _or_, according to >>>> a policy of whether to re-try blocking sys-calls the kernel interrupts >>>> and runs the signal-handler and the process enters epoll_wait again. >>>> >>>> So, I'm under the impression that there's a race-condition where >>>> the process gets a signal while blocked in epoll_wait, then according >>>> to one of two policies, EAGAIN error-handling or re-try, that it >>>> loses the notification, not the packet. The packet is still on >>>> the socket to be read, the notification of it was lost. >>>> >>>> The pselect simply doesn't have that problem, it's level-triggered, >>>> and however it re-enters pselect after getting interrupted, >>>> as long as there's data yet to read, it will get notified. >>>> >>>> >>>> Then also epoll might not need mlock'ed memory like io_uring does. >>>> >>>> >>>> >>>> That's about it. >>>> >>>> >>>> >>>> >>> >>> pselect() is simple, portable, and for many workloads fast enough. Those >>> are perfectly valid engineering arguments. >>> >>> For a high-performance server, though, well, shit. I personally wouldn't >>> be reaching for pselect() at all. Uggg... >>> >>> One thing I like about mechanisms such as io_uring and IOCP is that they >>> encourage thinking about capacity up front. You tend to preallocate the >>> resources the system needs to operate, size your queues and pools >>> appropriately, and define behavior for resource pressure. Thats >>> generally preferable to discovering in the god damn hot path that yet >>> another allocation is required! Fuck! >>> >>> On Windows, large scale IOCP servers have long used techniques such as >>> so called, zero byte receives, and preallocated connection state to >>> reduce memory pressure and avoid per-operation allocations. Similar >>> ideas apply elsewhere, for sure. The goal is usually to enter a pressure >>> mode before critical resources are exhausted, not to keep allocating >>> indefinitely and hope for the best. >>> >>> When resources start getting tight, I would rather see the server shed >>> load, evict caches, shorten timeouts, disconnect stale clients, or >>> refuse new work than continue consuming memory until the operating >>> system is in trouble. Running out of capacity should be a planned state, >>> not a surprise. >>> >>> That's one of the reasons fixed pools and preallocated state appeal to >>> me for systems under heavy load. >>> >> >> Preallocated state is another matter altogether, this sort of approach >> mentioned presumes fixed resources, for example when a memory-pool is >> in-use, to stop reads and then TCP/IP itself closes the receive window. > > Preallocated state is a nice way to get a 100% guarantee that everything > works as-is. If any more (extra) connections come in, at least in IOCP > we can use several means to expand the state. If we succeeded tag the > per_io and/or per_socket state with being "outside" of the pool. So on > shutdown, graceful close, aborted, etc. We know well, perhaps we need to > call free, or whatever, or even closesocket. With IOCP we can create all > of our sockets up front if we want. The windozer has that fun: > > https://learn.microsoft.com/en-us/previous-versions/windows/desktop/ > legacy/ms737757(v=vs.85) Shit. That link is not ideal for DisconnectEx. This is direct: https://learn.microsoft.com/en-us/windows/win32/api/mswsock/nc-mswsock-lpfn_disconnectex > > It allows a socket to be reused in either AcceptEx or ConnectEx: > > https://learn.microsoft.com/en-us/windows/win32/api/mswsock/nf-mswsock- > acceptex > > https://learn.microsoft.com/en-us/windows/win32/api/mswsock/nc-mswsock- > lpfn_connectex > > With io_uring, we would want to dedicate the whole box, or a part of it, > to be okay. This is for IO. Ideally we preallocate as much as the box > can handle without caking its pants. [...]
Re: Inversion-of-control and dependency-injection in C
Author: Ross Finlayson
Date: Thu, 19 Nov 2026 00:38
Date: Thu, 19 Nov 2026 00:38
30 lines
2701 bytes
2701 bytes
On 11/18/2026 12:40 PM, bartc wrote: > On 18/11/2026 19:58, Ross Finlayson wrote: > > <More than 3300 lines snipped> > > You're a nutter. > Hm. Dear me. At that rate I'd soon be a transient if not a criminal. Oh well, at least when I'm coding in C/C++ in C and looking for: function overloading, including with multiple parameters, covariant return-types, and transparent holders, polymorphism at run-time, if shallowly, and generic and specialized zero-cost container abstractions, all with the strong guarantees of types to compile, and other sorts features where I'd turn to C++, I can less worry my head about picking among the ten different ways of doing things in C++ that were after templates and type_traits. "Your time is valuable and your opinion is valued." Warm regards
Re: Inversion-of-control and dependency-injection in C
Author: fir
Date: Thu, 19 Nov 2026 06:47
Date: Thu, 19 Nov 2026 06:47
31 lines
2803 bytes
2803 bytes
Ross Finlayson pisze: > On 11/18/2026 12:40 PM, bartc wrote: >> On 18/11/2026 19:58, Ross Finlayson wrote: >> >> <More than 3300 lines snipped> >> >> You're a nutter. >> > > Hm. Dear me. At that rate I'd soon be a transient if not a criminal. > > Oh well, at least when I'm coding in C/C++ in C and looking for: > > function overloading, including with multiple parameters, > covariant return-types, and transparent holders, > polymorphism at run-time, if shallowly, > and generic and specialized zero-cost container abstractions, > all with the strong guarantees of types to compile, > > and other sorts features where I'd turn to C++, > I can less worry my head about picking among > the ten different ways of doing things in C++ > that were after templates and type_traits. > > > "Your time is valuable and your opinion is valued." > > > Warm regards > > if you want more buzzwords c++ is good way if less stay wit c ;c
Re: Inversion-of-control and dependency-injection in C
Author: fir
Date: Thu, 19 Nov 2026 06:48
Date: Thu, 19 Nov 2026 06:48
37 lines
2867 bytes
2867 bytes
fir pisze: > Ross Finlayson pisze: >> On 11/18/2026 12:40 PM, bartc wrote: >>> On 18/11/2026 19:58, Ross Finlayson wrote: >>> >>> <More than 3300 lines snipped> >>> >>> You're a nutter. >>> >> >> Hm. Dear me. At that rate I'd soon be a transient if not a criminal. >> >> Oh well, at least when I'm coding in C/C++ in C and looking for: >> >> function overloading, including with multiple parameters, >> covariant return-types, and transparent holders, >> polymorphism at run-time, if shallowly, >> and generic and specialized zero-cost container abstractions, >> all with the strong guarantees of types to compile, >> >> and other sorts features where I'd turn to C++, >> I can less worry my head about picking among >> the ten different ways of doing things in C++ >> that were after templates and type_traits. >> >> >> "Your time is valuable and your opinion is valued." >> >> >> Warm regards >> >> if you want more buzzwords c++ is good way if less stay wit c ;c
Re: Inversion-of-control and dependency-injection in C
Author: Bonita Montero
Date: Thu, 19 Nov 2026 06:57
Date: Thu, 19 Nov 2026 06:57
5 lines
2065 bytes
2065 bytes
Am 19.11.2026 um 07:48 schrieb fir: > if you want more buzzwords c++ is good way if less stay wit c ;c You don't understand C++.
Re: Inversion-of-control and dependency-injection in C
Author: fir
Date: Thu, 19 Nov 2026 07:54
Date: Thu, 19 Nov 2026 07:54
9 lines
2199 bytes
2199 bytes
Bonita Montero pisze: > Am 19.11.2026 um 07:48 schrieb fir: > >> if you want more buzzwords c++ is good way if less stay wit c ;c > You don't understand C++. > but i understand shit in c++ lame bonita..it is enough
Re: Inversion-of-control and dependency-injection in C
Author: Bonita Montero
Date: Thu, 19 Nov 2026 08:44
Date: Thu, 19 Nov 2026 08:44
12 lines
2532 bytes
2532 bytes
Am 19.11.2026 um 08:54 schrieb fir: > but i understand shit in c++ lame bonita..it is enough The abstraction in C++ maps to very efficient and easy to understand parts in the back. But the C-minimalists are too stupid to handle that. There are no complex data structures in C and it's very hard to handle them as easy and as efficient as in C++. Imagine you have a unordered_map<string_view, intin C++ and now you should implement that in C. With C++ that's a one-liner, with C that's a week of work.
Re: Inversion-of-control and dependency-injection in C
Author: fir
Date: Thu, 19 Nov 2026 09:13
Date: Thu, 19 Nov 2026 09:13
25 lines
3107 bytes
3107 bytes
Bonita Montero pisze: > Am 19.11.2026 um 08:54 schrieb fir: > >> but i understand shit in c++ lame bonita..it is enough > The abstraction in C++ maps to very efficient and easy to > understand parts in the back. But the C-minimalists are too > stupid to handle that. > There are no complex data structures in C and it's very hard > to handle them as easy and as efficient as in C++. Imagine > you have a unordered_map<string_view, intin C++ and now you > should implement that in C. With C++ that's a one-liner, with > C that's a week of work. > youre so lame you dont understand what you talking - youre comparing implementating a library in c to implementating in in c++ or youre comparing caling one in c to one in c++? i guess youre so lame you do the cros comparison here..and on this level of iq i dont talk overally teh implementation of containers in c its not so hard as you think..how many you impolemented? i m afraid youre so lame you implemented none. youre so good in containers as in sorting i guess
Re: Inversion-of-control and dependency-injection in C
Author: fir
Date: Thu, 19 Nov 2026 09:15
Date: Thu, 19 Nov 2026 09:15
29 lines
3264 bytes
3264 bytes
fir pisze: > Bonita Montero pisze: >> Am 19.11.2026 um 08:54 schrieb fir: >> >>> but i understand shit in c++ lame bonita..it is enough >> The abstraction in C++ maps to very efficient and easy to >> understand parts in the back. But the C-minimalists are too >> stupid to handle that. >> There are no complex data structures in C and it's very hard >> to handle them as easy and as efficient as in C++. Imagine >> you have a unordered_map<string_view, intin C++ and now you >> should implement that in C. With C++ that's a one-liner, with >> C that's a week of work. >> > youre so lame you dont understand what you talking - youre comparing > implementating a library in c to implementating in in c++ > or youre comparing caling one in c to one in c++? > > i guess youre so lame you do the cros comparison here..and on this level > of iq i dont talk > > overally teh implementation of containers in c its not so hard as you > think..how many you impolemented? i m afraid youre so lame you > implemented none. > > youre so good in containers as in sorting i guess overally your troll style of talking (oneliners + some bulshit) is not standable imo at all
Re: Inversion-of-control and dependency-injection in C
Author: fir
Date: Thu, 19 Nov 2026 09:18
Date: Thu, 19 Nov 2026 09:18
4 lines
2306 bytes
2306 bytes
note this your lame style of talking is so called "dwelling in bulshit" and this is below the typical level of this group when people try not to do that.. youre and your talk are more like unfamous rick hodgin here unfortunatelly
Re: Inversion-of-control and dependency-injection in C
Author: fir
Date: Thu, 19 Nov 2026 09:30
Date: Thu, 19 Nov 2026 09:30
149 lines
5641 bytes
5641 bytes
Bonita Montero pisze:
> There are no complex data structures in C and it's very hard
> to handle them as easy and as efficient as in C++. Imagine
> you have a unordered_map<string_view, intin C++ and now you
> should implement that in C. With C++ that's a one-liner, with
> C that's a week of work.
as this shot above you get it from ai - i never needed that so i dont
want to discus it (have may ovn more algebraic attitude to containers)
writing it alosne is not a weeks of work arso adjusting it to some
needs not so hard
this one cosed me like 2 * 3 seconds maybe here
ofc c has some unconvenience in syntax and with some additions the
containers in c could be more nice ofc (thats what im sometimes working on)
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
typedef struct {
const char *ptr;
int length;
} StringView;
typedef struct {
StringView key;
int value;
unsigned hash;
int used;
} StringIntMapEntry;
typedef struct {
StringIntMapEntry *data;
int size;
int capacity;
} StringIntMap;
unsigned HashStringView(StringView s)
{
unsigned h=2166136261u;
int i;
for(i=0;i<s.length;i++) {
h^=(unsigned char)s.ptr[i];
h*=16777619u;
}
return h;
}
int StringViewEqual(StringView a,StringView b)
{
return a.length==b.length && memcmp(a.ptr,b.ptr,a.length)==0;
}
void StringIntMapInit(StringIntMap *m,int capacity)
{
m->size=0;
m->capacity=capacity;
m->data=(StringIntMapEntry*)calloc(capacity,sizeof(StringIntMapEntry));
}
void StringIntMapFree(StringIntMap *m)
{
free(m->data);
m->data=NULL;
m->size=0;
m->capacity=0;
}
void StringIntMapResize(StringIntMap *m,int capacity)
{
StringIntMapEntry *old=m->data;
int old_capacity=m->capacity;
int i;
m->data=(StringIntMapEntry*)calloc(capacity,sizeof(StringIntMapEntry));
m->capacity=capacity;
m->size=0;
for(i=0;i<old_capacity;i++) {
if(old[i].used)
StringIntMapPut(m,old[i].key,old[i].value);
}
free(old);
}
void StringIntMapPut(StringIntMap *m,StringView key,int value)
{
unsigned hash=HashStringView(key);
int index;
if((m->size+1)*100>m->capacity*70)
StringIntMapResize(m,m->capacity*2);
index=hash%m->capacity;
while(m->data[index].used) {
if(m->data[index].hash==hash &&
StringViewEqual(m->data[index].key,key)) {
m->data[index].value=value;
return;
}
index=(index+1)%m->capacity;
}
m->data[index].used=1;
m->data[index].key=key;
m->data[index].value=value;
m->data[index].hash=hash;
m->size++;
}
int *StringIntMapGet(StringIntMap *m,StringView key)
{
unsigned hash=HashStringView(key);
int index=hash%m->capacity;
while(m->data[index].used) {
if(m->data[index].hash==hash &&
StringViewEqual(m->data[index].key,key))
return &m->data[index].value;
index=(index+1)%m->capacity;
}
return NULL;
}
int main(void)
{
StringIntMap map;
StringIntMapInit(&map,16);
StringIntMapPut(&map,(StringView){"ship",4},1);
StringIntMapPut(&map,(StringView){"miss",4},2);
StringIntMapPut(&map,(StringView){"bull",4},3);
int *v=StringIntMapGet(&map,(StringView){"miss",4});
if(v)
printf("%d\n",*v);
StringIntMapFree(&map);
return 0;
}
Re: Inversion-of-control and dependency-injection in C
Author: fir
Date: Thu, 19 Nov 2026 09:33
Date: Thu, 19 Nov 2026 09:33
6 lines
2450 bytes
2450 bytes
what is really usable in c++ is references and some operator overloading (like for vectors) but it noy justifies adding of all other trash this new cobol offers ;c references are ok, operator overloading probably shuld be done maybe a bit better..but overally c has more worse problems like this "not seing definitions down" which s terrible and has terrible consequences
Re: Inversion-of-control and dependency-injection in C
Author: fir
Date: Thu, 19 Nov 2026 09:49
Date: Thu, 19 Nov 2026 09:49
14 lines
2818 bytes
2818 bytes
fir pisze: > what is really usable in c++ is references and some operator overloading > (like for vectors) but it noy justifies adding of all other trash this > new cobol offers ;c > references are ok, operator overloading probably shuld be done maybe a > bit better..but overally c has more worse problems like this "not seing > definitions down" which s terrible and has terrible consequences c maybe dont even need just operator overloading - but not having basic */+- for float3-float3 and float-float3 is a shame... also i could maybe said what is needed to making impelmentation of containers in c much better but right now im not focused on that (but maybe some day i will get to it yet)
Re: Inversion-of-control and dependency-injection in C
Author: fir
Date: Thu, 19 Nov 2026 10:01
Date: Thu, 19 Nov 2026 10:01
13 lines
2619 bytes
2619 bytes
fir pisze: > ..but overally c has more worse problems like this "not seing > definitions down" which s terrible and has terrible consequences note if not that shit the declarations/externs in c would not be just existing (!) you could compile each file to .o with no adding one..and compiler could eventually generate some .h as an interface but it would be generated automaticaaly you would not write it and that mes with declarations/externs is in fact imo the worst practical problem of c today
Re: Inversion-of-control and dependency-injection in C
Author: Bonita Montero
Date: Thu, 19 Nov 2026 13:06
Date: Thu, 19 Nov 2026 13:06
20 lines
2947 bytes
2947 bytes
Am 19.11.2026 um 10:13 schrieb fir: > youre so lame you dont understand what you talking - youre comparing > implementating a library in c to implementating in in c++ > or youre comparing caling one in c to one in c++? Study C++ containers like unorderdered_map<>, then you may understand what I mean. > overally teh implementation of containers in c its not so hard as you > think.. ... Look at the count of methods in unordered_map<>: https://en.cppreference.com/cpp/container/unordered_map Do you think you could implement that so easy ? With C++ it's a one-liner to specialize this generic class to a user-defined key- / value-pair. With C it's a week's work; or you do it the poor stype with callbacks like with qsort(). And we've seen the performance difference between qsort() and std::sport - factor six.
Re: Inversion-of-control and dependency-injection in C
Author: Bonita Montero
Date: Thu, 19 Nov 2026 14:53
Date: Thu, 19 Nov 2026 14:53
137 lines
5938 bytes
5938 bytes
Am 19.11.2026 um 10:30 schrieb fir:
> Bonita Montero pisze:
>> There are no complex data structures in C and it's very hard
>> to handle them as easy and as efficient as in C++. Imagine
>> you have a unordered_map<string_view, intin C++ and now you
>> should implement that in C. With C++ that's a one-liner, with
>> C that's a week of work.
>
>
> as this shot above you get it from ai - i never needed that so i dont
> want to discus it (have may ovn more algebraic attitude to containers)
>
> writing it alosne is not a weeks of work arso adjusting it to some
> needs not so hard
>
> this one cosed me like 2 * 3 seconds maybe here
>
> ofc c has some unconvenience in syntax and with some additions the
> containers in c could be more nice ofc (thats what im sometimes working on)
>
>
> #include <stdlib.h>
> #include <string.h>
> #include <stdio.h>
>
> typedef struct {
> const char *ptr;
> int length;
> } StringView;
>
> typedef struct {
> StringView key;
> int value;
> unsigned hash;
> int used;
> } StringIntMapEntry;
>
> typedef struct {
> StringIntMapEntry *data;
> int size;
> int capacity;
> } StringIntMap;
>
> unsigned HashStringView(StringView s)
> {
> unsigned h=2166136261u;
> int i;
> for(i=0;i<s.length;i++) {
> h^=(unsigned char)s.ptr[i];
> h*=16777619u;
> }
> return h;
> }
>
> int StringViewEqual(StringView a,StringView b)
> {
> return a.length==b.length && memcmp(a.ptr,b.ptr,a.length)==0;
> }
>
> void StringIntMapInit(StringIntMap *m,int capacity)
> {
> m->size=0;
> m->capacity=capacity;
> m-
> >data=(StringIntMapEntry*)calloc(capacity,sizeof(StringIntMapEntry));
> }
>
> void StringIntMapFree(StringIntMap *m)
> {
> free(m->data);
> m->data=NULL;
> m->size=0;
> m->capacity=0;
> }
>
> void StringIntMapResize(StringIntMap *m,int capacity)
> {
> StringIntMapEntry *old=m->data;
> int old_capacity=m->capacity;
> int i;
>
> m-
> >data=(StringIntMapEntry*)calloc(capacity,sizeof(StringIntMapEntry));
> m->capacity=capacity;
> m->size=0;
>
> for(i=0;i<old_capacity;i++) {
> if(old[i].used)
> StringIntMapPut(m,old[i].key,old[i].value);
> }
>
> free(old);
> }
>
> void StringIntMapPut(StringIntMap *m,StringView key,int value)
> {
> unsigned hash=HashStringView(key);
> int index;
>
> if((m->size+1)*100>m->capacity*70)
> StringIntMapResize(m,m->capacity*2);
>
> index=hash%m->capacity;
>
> while(m->data[index].used) {
> if(m->data[index].hash==hash && StringViewEqual(m-
> >data[index].key,key)) {
> m->data[index].value=value;
> return;
> }
> index=(index+1)%m->capacity;
> }
>
> m->data[index].used=1;
> m->data[index].key=key;
> m->data[index].value=value;
> m->data[index].hash=hash;
> m->size++;
> }
>
> int *StringIntMapGet(StringIntMap *m,StringView key)
> {
> unsigned hash=HashStringView(key);
> int index=hash%m->capacity;
>
> while(m->data[index].used) {
> if(m->data[index].hash==hash && StringViewEqual(m-
> >data[index].key,key))
> return &m->data[index].value;
> index=(index+1)%m->capacity;
> }
>
> return NULL;
> }
Try to implement that with the full functionality of std::unordered_map.
You suck.
Re: Inversion-of-control and dependency-injection in C
Author: Bonita Montero
Date: Thu, 19 Nov 2026 14:54
Date: Thu, 19 Nov 2026 14:54
6 lines
2313 bytes
2313 bytes
Am 19.11.2026 um 10:33 schrieb fir: > what is really usable in c++ is references and some operator overloading > (like for vectors) ... You don't understand the rest.
Re: Inversion-of-control and dependency-injection in C
Author: fir
Date: Thu, 19 Nov 2026 15:03
Date: Thu, 19 Nov 2026 15:03
142 lines
6366 bytes
6366 bytes
Bonita Montero pisze:
> Am 19.11.2026 um 10:30 schrieb fir:
>> Bonita Montero pisze:
>>> There are no complex data structures in C and it's very hard
>>> to handle them as easy and as efficient as in C++. Imagine
>>> you have a unordered_map<string_view, intin C++ and now you
>>> should implement that in C. With C++ that's a one-liner, with
>>> C that's a week of work.
>>
>>
>> as this shot above you get it from ai - i never needed that so i dont
>> want to discus it (have may ovn more algebraic attitude to containers)
>>
>> writing it alosne is not a weeks of work arso adjusting it to some
>> needs not so hard
>>
>> this one cosed me like 2 * 3 seconds maybe here
>>
>> ofc c has some unconvenience in syntax and with some additions the
>> containers in c could be more nice ofc (thats what im sometimes
>> working on)
>>
>>
>> #include <stdlib.h>
>> #include <string.h>
>> #include <stdio.h>
>>
>> typedef struct {
>> const char *ptr;
>> int length;
>> } StringView;
>>
>> typedef struct {
>> StringView key;
>> int value;
>> unsigned hash;
>> int used;
>> } StringIntMapEntry;
>>
>> typedef struct {
>> StringIntMapEntry *data;
>> int size;
>> int capacity;
>> } StringIntMap;
>>
>> unsigned HashStringView(StringView s)
>> {
>> unsigned h=2166136261u;
>> int i;
>> for(i=0;i<s.length;i++) {
>> h^=(unsigned char)s.ptr[i];
>> h*=16777619u;
>> }
>> return h;
>> }
>>
>> int StringViewEqual(StringView a,StringView b)
>> {
>> return a.length==b.length && memcmp(a.ptr,b.ptr,a.length)==0;
>> }
>>
>> void StringIntMapInit(StringIntMap *m,int capacity)
>> {
>> m->size=0;
>> m->capacity=capacity;
>> m-
>> >data=(StringIntMapEntry*)calloc(capacity,sizeof(StringIntMapEntry));
>> }
>>
>> void StringIntMapFree(StringIntMap *m)
>> {
>> free(m->data);
>> m->data=NULL;
>> m->size=0;
>> m->capacity=0;
>> }
>>
>> void StringIntMapResize(StringIntMap *m,int capacity)
>> {
>> StringIntMapEntry *old=m->data;
>> int old_capacity=m->capacity;
>> int i;
>>
>> m-
>> >data=(StringIntMapEntry*)calloc(capacity,sizeof(StringIntMapEntry));
>> m->capacity=capacity;
>> m->size=0;
>>
>> for(i=0;i<old_capacity;i++) {
>> if(old[i].used)
>> StringIntMapPut(m,old[i].key,old[i].value);
>> }
>>
>> free(old);
>> }
>>
>> void StringIntMapPut(StringIntMap *m,StringView key,int value)
>> {
>> unsigned hash=HashStringView(key);
>> int index;
>>
>> if((m->size+1)*100>m->capacity*70)
>> StringIntMapResize(m,m->capacity*2);
>>
>> index=hash%m->capacity;
>>
>> while(m->data[index].used) {
>> if(m->data[index].hash==hash && StringViewEqual(m-
>> >data[index].key,key)) {
>> m->data[index].value=value;
>> return;
>> }
>> index=(index+1)%m->capacity;
>> }
>>
>> m->data[index].used=1;
>> m->data[index].key=key;
>> m->data[index].value=value;
>> m->data[index].hash=hash;
>> m->size++;
>> }
>>
>> int *StringIntMapGet(StringIntMap *m,StringView key)
>> {
>> unsigned hash=HashStringView(key);
>> int index=hash%m->capacity;
>>
>> while(m->data[index].used) {
>> if(m->data[index].hash==hash && StringViewEqual(m-
>> >data[index].key,key))
>> return &m->data[index].value;
>> index=(index+1)%m->capacity;
>> }
>>
>> return NULL;
>> }
> Try to implement that with the full functionality of std::unordered_map.
> You suck.
>
primitive troll lame bonita told me i suck..i think we ended all
possible conversation as your level of posting is near animal imo...
so good luck ..in your animal level world
Re: Inversion-of-control and dependency-injection in C
Author: Chris M. Thomasson
Date: Thu, 19 Nov 2026 20:40
Date: Thu, 19 Nov 2026 20:40
141 lines
6232 bytes
6232 bytes
On 11/19/2026 6:53 AM, Bonita Montero wrote:
> Am 19.11.2026 um 10:30 schrieb fir:
>> Bonita Montero pisze:
>>> There are no complex data structures in C and it's very hard
>>> to handle them as easy and as efficient as in C++. Imagine
>>> you have a unordered_map<string_view, intin C++ and now you
>>> should implement that in C. With C++ that's a one-liner, with
>>> C that's a week of work.
>>
>>
>> as this shot above you get it from ai - i never needed that so i dont
>> want to discus it (have may ovn more algebraic attitude to containers)
>>
>> writing it alosne is not a weeks of work arso adjusting it to some
>> needs not so hard
>>
>> this one cosed me like 2 * 3 seconds maybe here
>>
>> ofc c has some unconvenience in syntax and with some additions the
>> containers in c could be more nice ofc (thats what im sometimes
>> working on)
>>
>>
>> #include <stdlib.h>
>> #include <string.h>
>> #include <stdio.h>
>>
>> typedef struct {
>> const char *ptr;
>> int length;
>> } StringView;
>>
>> typedef struct {
>> StringView key;
>> int value;
>> unsigned hash;
>> int used;
>> } StringIntMapEntry;
>>
>> typedef struct {
>> StringIntMapEntry *data;
>> int size;
>> int capacity;
>> } StringIntMap;
>>
>> unsigned HashStringView(StringView s)
>> {
>> unsigned h=2166136261u;
>> int i;
>> for(i=0;i<s.length;i++) {
>> h^=(unsigned char)s.ptr[i];
>> h*=16777619u;
>> }
>> return h;
>> }
>>
>> int StringViewEqual(StringView a,StringView b)
>> {
>> return a.length==b.length && memcmp(a.ptr,b.ptr,a.length)==0;
>> }
>>
>> void StringIntMapInit(StringIntMap *m,int capacity)
>> {
>> m->size=0;
>> m->capacity=capacity;
>> m-
>> >data=(StringIntMapEntry*)calloc(capacity,sizeof(StringIntMapEntry));
>> }
>>
>> void StringIntMapFree(StringIntMap *m)
>> {
>> free(m->data);
>> m->data=NULL;
>> m->size=0;
>> m->capacity=0;
>> }
>>
>> void StringIntMapResize(StringIntMap *m,int capacity)
>> {
>> StringIntMapEntry *old=m->data;
>> int old_capacity=m->capacity;
>> int i;
>>
>> m-
>> >data=(StringIntMapEntry*)calloc(capacity,sizeof(StringIntMapEntry));
>> m->capacity=capacity;
>> m->size=0;
>>
>> for(i=0;i<old_capacity;i++) {
>> if(old[i].used)
>> StringIntMapPut(m,old[i].key,old[i].value);
>> }
>>
>> free(old);
>> }
>>
>> void StringIntMapPut(StringIntMap *m,StringView key,int value)
>> {
>> unsigned hash=HashStringView(key);
>> int index;
>>
>> if((m->size+1)*100>m->capacity*70)
>> StringIntMapResize(m,m->capacity*2);
>>
>> index=hash%m->capacity;
>>
>> while(m->data[index].used) {
>> if(m->data[index].hash==hash && StringViewEqual(m-
>> >data[index].key,key)) {
>> m->data[index].value=value;
>> return;
>> }
>> index=(index+1)%m->capacity;
>> }
>>
>> m->data[index].used=1;
>> m->data[index].key=key;
>> m->data[index].value=value;
>> m->data[index].hash=hash;
>> m->size++;
>> }
>>
>> int *StringIntMapGet(StringIntMap *m,StringView key)
>> {
>> unsigned hash=HashStringView(key);
>> int index=hash%m->capacity;
>>
>> while(m->data[index].used) {
>> if(m->data[index].hash==hash && StringViewEqual(m-
>> >data[index].key,key))
>> return &m->data[index].value;
>> index=(index+1)%m->capacity;
>> }
>>
>> return NULL;
>> }
> Try to implement that with the full functionality of std::unordered_map.
> You suck.
>
I am pretty sure AI wrote that code for him anyway.
Re: Inversion-of-control and dependency-injection in C
Author: Tristan Wibberley
Date: Fri, 20 Nov 2026 12:35
Date: Fri, 20 Nov 2026 12:35
38 lines
3633 bytes
3633 bytes
On 16/11/2026 18:09, Bonita Montero wrote: > Am 13.11.2026 um 23:50 schrieb Ross Finlayson: > >> So, here's one. Say you got a server process for sockets of the >> connection-oriented or datagram-wise or association-oriented like >> TCP, UDP, or SCTP, and it manages the connecting and the sending and >> receiving about a million of those and is sort of fixed-size and >> stable in a usual runtime. So, how do you design the interface, >> about stuff like the state-machine of _protocols_, all about >> _protocols_, in the application-layer and above, say, for example >> the incremental-parsing and the state-machine of the protocol >> and sub-protocols and upgrade-protocols and the like, what sort >> of abstraction with suitable-defaults and reasonable-opinions >> makes for having any sort protocol as a composable library. > Use C++20 coroutines with Bost.ASIO and io_uring. This gives > as less code as possible with nearly optimal I/O performance. I like this answer. It's funny: people used coroutines and CoEs back in the 1970s (I did it as a child, myself), then everyone told each other to stop it, now 50 years later here we are again, finally succeeding once more after a long hiatus, albeit with appalling syntax and semantics everywhere around it like thorny bushes. -- Tristan Wibberley The message body is Copyright (C) 2026 Tristan Wibberley except citations and quotations noted. All Rights Reserved except that you may, of course, cite it academically giving credit to me, distribute it verbatim as part of a usenet system or its archives, and use it to promote my greatness and general superiority without misrepresentation of my opinions other than my opinion of my greatness and general superiority which you _may_ misrepresent. You definitely MAY NOT train any production AI system with it but you may train experimental AI that will only be used for evaluation of the AI methods it implements.
Re: Inversion-of-control and dependency-injection in C
Author: Michael S
Date: Fri, 20 Nov 2026 13:12
Date: Fri, 20 Nov 2026 13:12
51 lines
3753 bytes
3753 bytes
On Fri, 20 Nov 2026 12:35:25 +0000 Tristan Wibberley <tristan.wibberley+netnews2@alumni.manchester.ac.uk> wrote: > On 16/11/2026 18:09, Bonita Montero wrote: > > Am 13.11.2026 um 23:50 schrieb Ross Finlayson: > > > >> So, here's one. Say you got a server process for sockets of the > >> connection-oriented or datagram-wise or association-oriented like > >> TCP, UDP, or SCTP, and it manages the connecting and the sending > >> and receiving about a million of those and is sort of fixed-size > >> and stable in a usual runtime. So, how do you design the interface, > >> about stuff like the state-machine of _protocols_, all about > >> _protocols_, in the application-layer and above, say, for example > >> the incremental-parsing and the state-machine of the protocol > >> and sub-protocols and upgrade-protocols and the like, what sort > >> of abstraction with suitable-defaults and reasonable-opinions > >> makes for having any sort protocol as a composable library. > > > Use C++20 coroutines with Bost.ASIO and io_uring. This gives > > as less code as possible with nearly optimal I/O performance. > > I like this answer. > > It's funny: people used coroutines and CoEs back in the 1970s (I did > it as a child, myself), then everyone told each other to stop it, now > 50 years later here we are again, finally succeeding once more after > a long hiatus, albeit with appalling syntax and semantics everywhere > around it like thorny bushes. > Not every co-routine syntax is as bad as one of C++. C# async is better. May be, even Rust is better, at cost on reliance on magic barely documented tokio runtime. Me, personally? I accepted the idea of language-managed stackless co-routines when heard about it first time. But with time passing I like it less and less. More and more I tend to think that what I really would like are normal co-routines, a.k.a. fibers, not necessarily as part of the language. Or just do as golang, leaving selection between fibers and kerner-visible threads to language runtime. Hopefully, I did not misrepresent golang approach to badly :(
Re: Inversion-of-control and dependency-injection in C
Author: Ross Finlayson
Date: Fri, 20 Nov 2026 13:48
Date: Fri, 20 Nov 2026 13:48
185 lines
11998 bytes
11998 bytes
On 11/20/2026 04:35 AM, Tristan Wibberley wrote:
> On 16/11/2026 18:09, Bonita Montero wrote:
>> Am 13.11.2026 um 23:50 schrieb Ross Finlayson:
>>
>>> So, here's one. Say you got a server process for sockets of the
>>> connection-oriented or datagram-wise or association-oriented like
>>> TCP, UDP, or SCTP, and it manages the connecting and the sending and
>>> receiving about a million of those and is sort of fixed-size and
>>> stable in a usual runtime. So, how do you design the interface,
>>> about stuff like the state-machine of _protocols_, all about
>>> _protocols_, in the application-layer and above, say, for example
>>> the incremental-parsing and the state-machine of the protocol
>>> and sub-protocols and upgrade-protocols and the like, what sort
>>> of abstraction with suitable-defaults and reasonable-opinions
>>> makes for having any sort protocol as a composable library.
>
>> Use C++20 coroutines with Bost.ASIO and io_uring. This gives
>> as less code as possible with nearly optimal I/O performance.
>
> I like this answer.
>
> It's funny: people used coroutines and CoEs back in the 1970s (I did it
> as a child, myself), then everyone told each other to stop it, now 50
> years later here we are again, finally succeeding once more after a long
> hiatus, albeit with appalling syntax and semantics everywhere around it
> like thorny bushes.
>
The re-routine, or retry-coroutine, is a simple sort of abstraction
that basically has "write code in the language that looks like
synchronous blocking code and collect & cache its intermediate results
according to encounter-order then just re-run the whole routine until
it succeeds/errors/times-out, or about cancellation/time-out one may
aver", sort of like NFA's the non-deterministic automatons vis-a-vis
DFA's the deterministic automatons that are made from flattening NFA's,
though NFA's are deterministic and should be called something else,
makes for an account that the backing-modules move around it instead
of the other way around.
It's considered simplified for reason's sake when "callback & yield",
i.e., "the primitives of asycnhronous concurrency", are simply made
implicit according to the executing-context and the
function-interception. ("..., In the language, ....")
About types in C I've been looking at it with regards to for example,
"the decaying of the array-type to the pointer-type", and particularly,
"accounts of tiered-_Generic constructs that make for function
overloading with the type-safety after type-inference of strong-types
in C". So, _Generic can work off of non-decayed complete array-types,
then for example when there are only a small number of fixed-size arrays
to care about, like BRIEFNAME = 16, FULLNAME = 256, CACHELINE = 64, PAGE
= 4096, LARGEPAGE = 2 * 1024 * 1024, then after cv-qualifiers
as part of types and complete-types, then the usual account of the
function "overloading" may result that it's inferred from the types
their constant parameters then to result that a "function:
'under'-loading" may happen, basically thusly being able to convert the
cases in the _Generic construct to derive the constant usual "len"
parameters that thusly one needn't pass the extra-parameter "len" when
dealing with arrays of fixed-size that are not decayed to pointers, then
to a single "underloaded" function with the array decayed to pointer and
the len, then that as a "compile-time invariant" the compiler is free to
optimize that according to various accounts of loop un-rolling and
vector-ization, for example in-lining the function anyways, at compile-time.
Then, these sorts of aspects of, "code-style", and "convention" see
introduced a complement concept to "function overloading", "function
under-loading", about the usual notion that "function overloading"
allows one (template) function to result emitting as many functions
as necessary disambiguated via name-mangling (name-flattening to
a flat namespace the object's symbols), instead they funnel back
to one, "specialized" for each of these few types of fixed-size
non-decaying array pointers by simply make a _Generic construct
that has "len" as a compile-time invariant, and resulting only
one symbol in the resulting object file, called variously.
Another part of what's considered this "code-style", is about
compile-time constants and "static const" variables, with regards
to what may be "constexpr" in C23 as would be by "enum" in C11
for compile-time constant that are symbolic instead of macro literals,
and then variables separately, again about arrays, and variable-length
arrays in C, having two copies of a "constant", one a constexpr the
other static const, then for "variable-length arrays", if not in
C++ then optional in C, for small buffer in un-likely branches like
formatting brief logging messages or string functions that need a
buffer, that again the _types_ in C are observed/respected (and expected).
So, in this approach to "code-style" for "inversion-of-control
and dependency-injection in C", then there's basically the _Generic
construct, which makes for a controlling-expression (evaluated as
an expression then for its _type_) the result replacement expressions or
a default (which for example may everywhere be the default expression a
static-assertion that at compile-time composes an error-message saying
what's missing by its name and _type_), then with
a commonality and distinctions among "introductions" (introduced
in quotes, i.e., add it to the glossary), of "tiered-_Generic"
constructs, starts seeing a number of approaches to making for
the basic abstraction of functions as a _boundary_, that besides
the usual account a function returning a value, the _co-variance_,
usually of value to value/status/error. Then, this sort of _boundary_
establishes responsibilities of "modules" as they would be or
"libraries" as for "components", what then have the basic account
of co-variance as: "holders, of return-types & faults, and passers, of
parameter-types their values", over and back the _boundary_, while
yet for mostly in the code, that the holders "hide & hoist" the
return-values, while, the passers "present & promote", the parameters
(as basically an account of "holders", for example "optional").
Then, where C++ templates is a great and fantastic thing for
function-overloading, and these tiered-_Generic constructs still have
explosions in definitions what result, it's yet also so that at
compile-time: the libraries (their invocations after over/under-loading)
can have their invoctions resolved and compiled _faster_ this way, not
that it's better for readability of reducing source-code
boilerplate-bloat, yet though "specializing for templates" would be
about on the same order, that because it's closed in the tiered-_Generic
constructs instead of the C++ compiler making an outer-product of the
AST-world and then pruning that down to the specialized overloads, the C
(or, C++, _Generic is a valid construct in C++) account of this way, can
result both faster compilations, then as above: faster code.
So, accounts of "code-style" and "convention" often vary (for example,
they often _don't_ and are considered very "opinionated" in their
interpretation, for example by tabs-vs-spaces or pretty-printers
and re-formatters, touching first even on the "cosmetic" before even
getting into accounts like the above of the "ergonomic"). For example,
many prefer to adopt the code style that their editor gives the cosmetic
then into the case-convention of identifiers and so on, for example
PascalCase and camlCase and SNAKE_CASE and snake_case, then for
example the ordering of declarations according to scope or file
encounter lexicographically, by then entering accounts of the language.
So, sometimes accounts of "code-style" are like, for example, "there are
no boundaries and there are no exceptions", vis-a-vis, there are
boundaries and there are exceptions, then, for example, conventions
or patterns, like "we only use co-routines and don't use executors",
vis-a-vis, "our co-routines are run by threads that are our executors",
and then the strong-coupling, vis-a-vis the weak-coupling, which
basically in terms of the concrete and the abstract, has that
"inversion-of-control and dependency-injection" needs everything at
least abstractly abstract, vis-a-vis "boundaries" as above, then though
with a goal that at run-time (or evaluation) it yet results "as concrete
and direct as possible", that leading to a usual notion
of "zero-cost-abstraction", and these kinds of things.
Why care? Not for me to say, except for myself, and for expectations
of library authors and component designers for fair boundaries yet
un-obtrusiveness. Here though is an example, these "tiered-_Generic
constructs" with these concepts of "underloading" for example or
for "vanishing/phantom types" only in the templates as they would be,
run faster at both compile-time and run-time in both C and C++,
while with the guarantees of strong types according to the compiler
in both C and C++, and with the same code in both C and C++,
and being un-surprising and mapping to standard namespace types in C++.
If the best sort of style just fades away or rather is legible and
"ergonomic", for example that all these tiered-_Generic
type-interpretation introductions live in a header and the actual
sources just defined functions that the compiler complains must exist
until they're just plain functions, and they're just plain code
and functions according to the compiler and IDE, though with that
the IDE would know about the AST the _Generic construct in its
code-model, with regards "IDE vomit" and "A.I. slop", then there's
also that "the tooling" meaning tracing, debugging, and profilers,
it's all symbols to them.
(This is not "A.I.", though "AP" does have a stated opinion
that he considers me among "the A.I.". AP of course is notorious
for "universe is one giant dot", and is thought to be in gentle
retirement in the hinterlands.)
Re: Inversion-of-control and dependency-injection in C
Author: Tristan Wibberley
Date: Fri, 20 Nov 2026 14:00
Date: Fri, 20 Nov 2026 14:00
28 lines
3015 bytes
3015 bytes
On 16/11/2026 20:20, Ross Finlayson wrote: > Why don't they just call std::coroutine "fiber"? a) coroutines are a specific thing that existed already a very very long time ago b) C++ coroutines are a specific restriction on that thing which MS "fiber"s are not c) "fiber"s have some special interaction with thread_local and OS task CoEs which I read is not what c++ requires/assumes (even though it cannot reasonably require what it does universally). d) "fiber" names whatever MS chooses it to name at whatever time MS chooses, so it isn't a sufficiently deterministic reference. -- Tristan Wibberley The message body is Copyright (C) 2026 Tristan Wibberley except citations and quotations noted. All Rights Reserved except that you may, of course, cite it academically giving credit to me, distribute it verbatim as part of a usenet system or its archives, and use it to promote my greatness and general superiority without misrepresentation of my opinions other than my opinion of my greatness and general superiority which you _may_ misrepresent. You definitely MAY NOT train any production AI system with it but you may train experimental AI that will only be used for evaluation of the AI methods it implements.
Re: Inversion-of-control and dependency-injection in C
Author: bartc
Date: Fri, 20 Nov 2026 14:01
Date: Fri, 20 Nov 2026 14:01
47 lines
3587 bytes
3587 bytes
On 20/11/2026 13:48, Ross Finlayson wrote: > On 11/20/2026 04:35 AM, Tristan Wibberley wrote: >> On 16/11/2026 18:09, Bonita Montero wrote: >>> Am 13.11.2026 um 23:50 schrieb Ross Finlayson: >>> >>>> So, here's one. Say you got a server process for sockets of the >>>> connection-oriented or datagram-wise or association-oriented like >>>> TCP, UDP, or SCTP, and it manages the connecting and the sending and >>>> receiving about a million of those and is sort of fixed-size and >>>> stable in a usual runtime. So, how do you design the interface, >>>> about stuff like the state-machine of _protocols_, all about >>>> _protocols_, in the application-layer and above, say, for example >>>> the incremental-parsing and the state-machine of the protocol >>>> and sub-protocols and upgrade-protocols and the like, what sort >>>> of abstraction with suitable-defaults and reasonable-opinions >>>> makes for having any sort protocol as a composable library. >> >>> Use C++20 coroutines with Bost.ASIO and io_uring. This gives >>> as less code as possible with nearly optimal I/O performance. >> >> I like this answer. >> >> It's funny: people used coroutines and CoEs back in the 1970s (I did it >> as a child, myself), then everyone told each other to stop it, now 50 >> years later here we are again, finally succeeding once more after a long >> hiatus, albeit with appalling syntax and semantics everywhere around it >> like thorny bushes. >> <snip 147-line reply> > (This is not "A.I.", Oh, so it's you choosing to post endless reams of gibberish. Just, WHY? Nobody here has the patience to read through that crap let alone try and understand what the hell you're on about or what relevance it has to anything. > though "AP" does have a stated opinion Who the fuck is AP? On second thoughts, never mind; I don't want a 5,000-word exposition!
Re: Inversion-of-control and dependency-injection in C
Author: Ross Finlayson
Date: Fri, 20 Nov 2026 14:03
Date: Fri, 20 Nov 2026 14:03
84 lines
5511 bytes
5511 bytes
On 11/20/2026 05:12 AM, Michael S wrote: > On Fri, 20 Nov 2026 12:35:25 +0000 > Tristan Wibberley <tristan.wibberley+netnews2@alumni.manchester.ac.uk> > wrote: > >> On 16/11/2026 18:09, Bonita Montero wrote: >>> Am 13.11.2026 um 23:50 schrieb Ross Finlayson: >>> >>>> So, here's one. Say you got a server process for sockets of the >>>> connection-oriented or datagram-wise or association-oriented like >>>> TCP, UDP, or SCTP, and it manages the connecting and the sending >>>> and receiving about a million of those and is sort of fixed-size >>>> and stable in a usual runtime. So, how do you design the interface, >>>> about stuff like the state-machine of _protocols_, all about >>>> _protocols_, in the application-layer and above, say, for example >>>> the incremental-parsing and the state-machine of the protocol >>>> and sub-protocols and upgrade-protocols and the like, what sort >>>> of abstraction with suitable-defaults and reasonable-opinions >>>> makes for having any sort protocol as a composable library. >> >>> Use C++20 coroutines with Bost.ASIO and io_uring. This gives >>> as less code as possible with nearly optimal I/O performance. >> >> I like this answer. >> >> It's funny: people used coroutines and CoEs back in the 1970s (I did >> it as a child, myself), then everyone told each other to stop it, now >> 50 years later here we are again, finally succeeding once more after >> a long hiatus, albeit with appalling syntax and semantics everywhere >> around it like thorny bushes. >> > > Not every co-routine syntax is as bad as one of C++. > C# async is better. > May be, even Rust is better, at cost on reliance on magic barely > documented tokio runtime. > > Me, personally? > I accepted the idea of language-managed stackless co-routines when heard > about it first time. But with time passing I like it less and less. > More and more I tend to think that what I really would like are > normal co-routines, a.k.a. fibers, not necessarily as part of the > language. > > Or just do as golang, leaving selection between fibers and > kerner-visible threads to language runtime. Hopefully, I did not > misrepresent golang approach to badly :( > > > > > One may get the impression that std::coroutine or verbally "s.t.d.-namespace co-routine", much "is" fibers, after an account of the semantics and a re-write rule, much reflecting the 'Soft's deserved if sometimes underservedly the influence in the development of the standards, and accelerating that development to promote their tools, vis-a-vis the stability of interface and standards and specification and interoperability. Go's "select" basically is about POSIX's "select", with some nice syntactic-sugar and for lambdas in the language. The account of std::coroutine and availables and that, like as the model of "fibers" as co-operating switching among function bodies during a thread's time-slice, giving-or-taking accounts of stack abstraction, or "execution and par" and this kind of thing, or even for example "std::simd" and the like, about accounts of both parallelism, for the parallelizable, and concurrency, for the throughput or for example "transput" as Finkel put it in "An Operating Systems Vade Mecum" a great account of a walk-through of most usual accounts of operating-systems then widened for the distributed-world, makes for that _protocols are protocols_, and Postel & Murphy's laws has that Postel's law is a good guideline, describing good-actors in well-defined protocols, and Murphy's is in effect. (I'm a big fan of "concepts" in C++, if not so relevant here.)
Page 2 of 3 • 129 total messages
Thread Navigation
This is a paginated view of messages in the thread with full content displayed inline.
Messages are displayed in chronological order, with the original post highlighted in green.
Use pagination controls to navigate through all messages in large threads.
Back to All Threads