Skip to content

Instantly share code, notes, and snippets.

@nmoinvaz
Created February 11, 2026 21:51
Show Gist options
  • Select an option

  • Save nmoinvaz/4a7c42385dd2808acf17960cbc9eb69c to your computer and use it in GitHub Desktop.

Select an option

Save nmoinvaz/4a7c42385dd2808acf17960cbc9eb69c to your computer and use it in GitHub Desktop.
Zlib-ng deflate symbol macros
/* ===========================================================================
* Symbol buffer write/read macros.
*
* The symbol buffer stores literal and distance/length pairs. The storage
* format differs based on LIT_MEM (separate buffers) vs sym_buf (interleaved),
* and on whether the platform supports fast unaligned 32-bit access
* (OPTIMAL_CMP >= 32), which allows packing a 3-byte symbol into a single
* 32-bit write/read.
*
* SYM_WRITE_LIT and SYM_WRITE_DIST write a symbol and advance sym_next.
* SYM_READ reads a symbol and advances sx.
*/
#ifdef LIT_MEM
#define SYM_WRITE_LIT(s, sym_next, c) { \
(s)->d_buf[(sym_next)] = 0; \
(s)->l_buf[(sym_next)] = (c); \
(sym_next) += 1; \
}
#define SYM_WRITE_DIST(s, sym_next, dist, len) { \
(s)->d_buf[(sym_next)] = (uint16_t)(dist); \
(s)->l_buf[(sym_next)] = (uint8_t)(len); \
(sym_next) += 1; \
}
#define SYM_READ(s, sx, dist, lc) { \
(dist) = (s)->d_buf[(sx)]; \
(lc) = (s)->l_buf[(sx)]; \
(sx) += 1; \
}
#else /* !LIT_MEM */
#if OPTIMAL_CMP >= 32
#define SYM_WRITE_LIT(s, sym_next, c) { \
zng_memwrite_4(&(s)->sym_buf[(sym_next)], Z_U32_TO_LE((uint32_t)(c) << 16)); \
(sym_next) += 3; \
}
#define SYM_WRITE_DIST(s, sym_next, dist, len) { \
zng_memwrite_4(&(s)->sym_buf[(sym_next)], Z_U32_TO_LE((dist) | ((uint32_t)(len) << 16))); \
(sym_next) += 3; \
}
#define SYM_READ(s, sx, dist, lc) { \
uint32_t _val = Z_U32_FROM_LE(zng_memread_4(&(s)->sym_buf[(sx)])); \
(dist) = _val & 0xffff; \
(lc) = (_val >> 16) & 0xff; \
(sx) += 3; \
}
#else /* OPTIMAL_CMP < 32 */
#define SYM_WRITE_LIT(s, sym_next, c) { \
(s)->sym_buf[(sym_next)] = 0; \
(s)->sym_buf[(sym_next)+1] = 0; \
(s)->sym_buf[(sym_next)+2] = (c); \
(sym_next) += 3; \
}
#define SYM_WRITE_DIST(s, sym_next, dist, len) { \
(s)->sym_buf[(sym_next)] = (uint8_t)(dist); \
(s)->sym_buf[(sym_next)+1] = (uint8_t)((dist) >> 8); \
(s)->sym_buf[(sym_next)+2] = (uint8_t)(len); \
(sym_next) += 3; \
}
#define SYM_READ(s, sx, dist, lc) { \
(dist) = (s)->sym_buf[(sx)] + ((unsigned)(s)->sym_buf[(sx) + 1] << 8); \
(lc) = (s)->sym_buf[(sx) + 2]; \
(sx) += 3; \
}
#endif /* OPTIMAL_CMP >= 32 */
#endif /* LIT_MEM */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment