Skip to content

Instantly share code, notes, and snippets.

@masakielastic
Last active May 1, 2024 10:47
Show Gist options
  • Save masakielastic/306eeffac019d5287cfd757640f69d42 to your computer and use it in GitHub Desktop.
Save masakielastic/306eeffac019d5287cfd757640f69d42 to your computer and use it in GitHub Desktop.
PHP エクステンションで nghttp2 による HPACK エンコードの例です
/* hpack extension for PHP */
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "php.h"
#include "ext/standard/info.h"
#include "php_hpack.h"
#include "hpack_arginfo.h"
#include <nghttp2/nghttp2.h>
/* For compatibility with older PHP versions */
#ifndef ZEND_PARSE_PARAMETERS_NONE
#define ZEND_PARSE_PARAMETERS_NONE() \
ZEND_PARSE_PARAMETERS_START(0, 0) \
ZEND_PARSE_PARAMETERS_END()
#endif
#define MAKE_NV(K, V) \
{ \
(uint8_t *)K, (uint8_t *)V, sizeof(K) - 1, sizeof(V) - 1, \
NGHTTP2_NV_FLAG_NONE \
}
/* {{{ string hpack_encode_example() */
PHP_FUNCTION(hpack_encode_example)
{
ZEND_PARSE_PARAMETERS_NONE();
size_t i;
size_t nvlen;
uint8_t *buf;
size_t buflen;
size_t outlen;
int rv;
nghttp2_hd_deflater *deflater;
zend_string *result;
nghttp2_nv nva[] = {
MAKE_NV(":scheme", "https"), MAKE_NV(":authority", "example.org"),
MAKE_NV(":path", "/"), MAKE_NV("user-agent", "libnghttp2"),
MAKE_NV("accept-encoding", "gzip, deflate")
};
nvlen = sizeof(nva) / sizeof(nva[0]);
rv = nghttp2_hd_deflate_new(&deflater, 4096);
buflen = nghttp2_hd_deflate_bound(deflater, nva, nvlen);
buf = malloc(buflen);
rv = nghttp2_hd_deflate_hd(deflater, buf, buflen, nva, nvlen);
outlen = (size_t)rv;
result = strpprintf(outlen, "%s", buf);
RETURN_STR(result);
free(buf);
nghttp2_hd_deflate_del(deflater);
}
/* }}} */
$ php -d extension=modules/hpack.so test.php
bool(true)
<?php
var_dump(
'8741882f91d35d055cf64d847a87a0d1d534e94d6290' === bin2hex(hpack_encode_example())
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment