Skip to content
pi-c Documentation
Login

Documentation

/* Server-sent events framer: bytes in, complete events out. No I/O, no allocation
 * beyond the caller-sized buffers set at init. Provider-neutral. */
#ifndef PIC_SSE_H
#define PIC_SSE_H

#include <stddef.h>

/* Called once per dispatched event. event is "message" when the stream gave
 * none. data has no trailing newline and is NUL-terminated. Return nonzero to
 * stop the stream; pic_sse_feed then returns that value. */
typedef int (*pic_sse_event_fn)(void *ctx, const char *event, const char *data, size_t data_len);

typedef struct {
    pic_sse_event_fn on_event;
    void *ctx;
    char *line;      /* current line being assembled */
    size_t line_len, line_cap;
    char *data;      /* data field accumulated for the current event */
    size_t data_len, data_cap;
    char event[64];  /* event field for the current event */
    int has_data;    /* a data field was seen since the last dispatch */
    int after_cr;    /* the previous byte was CR: a following LF is part of it */
    int started;     /* past the point where a leading BOM can appear */
    int bom_matched; /* bytes of a leading BOM seen so far */
    int failed;      /* a limit was exceeded; the stream is unusable */
} pic_sse;

/* line_cap and data_cap bound memory; a line or event over them fails the stream. */
int pic_sse_init(pic_sse *p, size_t line_cap, size_t data_cap, pic_sse_event_fn on_event, void *ctx);
void pic_sse_free(pic_sse *p);
/* Returns 0, a callback's nonzero value, or -1 when a limit is exceeded. */
int pic_sse_feed(pic_sse *p, const char *bytes, size_t n);
/* Call at end of stream. Returns 1 if bytes of an unfinished event were left
 * (a truncated stream), 0 if the stream ended cleanly between events. */
int pic_sse_pending(const pic_sse *p);

#endif