2013-01-29 21:45:44 -07:00
|
|
|
#include <stdbool.h>
|
|
|
|
#include <stdint.h>
|
|
|
|
#include <stddef.h>
|
|
|
|
#include <string.h>
|
|
|
|
#include "stream.h"
|
|
|
|
|
|
|
|
void
|
|
|
|
sinit(struct stream *s, char const *buf, size_t buflen)
|
|
|
|
{
|
2013-01-29 21:53:17 -07:00
|
|
|
s->buf = buf;
|
|
|
|
s->len = buflen;
|
2013-01-29 21:45:44 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
bool
|
|
|
|
sskip(struct stream *s, size_t count)
|
|
|
|
{
|
2013-01-29 21:53:17 -07:00
|
|
|
if (count > s->len) {
|
|
|
|
s->len = 0;
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
s->buf += count;
|
|
|
|
s->len -= count;
|
|
|
|
return true;
|
2013-01-29 21:45:44 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
bool
|
2013-01-29 21:53:17 -07:00
|
|
|
sread(struct stream * s, void *buf, size_t count)
|
2013-01-29 21:45:44 -07:00
|
|
|
{
|
2013-01-29 21:53:17 -07:00
|
|
|
void const *d = s->buf;
|
2013-01-29 21:45:44 -07:00
|
|
|
|
2013-01-29 21:53:17 -07:00
|
|
|
if (!sskip(s, count)) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
memcpy(buf, d, count);
|
2013-01-29 21:45:44 -07:00
|
|
|
|
2013-01-29 21:53:17 -07:00
|
|
|
return true;
|
2013-01-29 21:45:44 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
uint8_t
|
2013-01-29 21:53:17 -07:00
|
|
|
read_uint8(struct stream * s)
|
2013-01-29 21:45:44 -07:00
|
|
|
{
|
2013-01-29 21:53:17 -07:00
|
|
|
uint8_t *d = (uint8_t *) s->buf;
|
2013-01-29 21:45:44 -07:00
|
|
|
|
2013-01-29 21:53:17 -07:00
|
|
|
if (!sskip(s, 1)) {
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
return d[0];
|
2013-01-29 21:45:44 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
uint16_t
|
2013-01-29 21:53:17 -07:00
|
|
|
read_uint16be(struct stream * s)
|
2013-01-29 21:45:44 -07:00
|
|
|
{
|
2013-01-29 21:53:17 -07:00
|
|
|
uint8_t *d = (uint8_t *) s->buf;
|
|
|
|
|
|
|
|
if (!sskip(s, 2)) {
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
return ((d[0] << 8) | (d[1] << 0));
|
2013-01-29 21:45:44 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
uint16_t
|
2013-01-29 21:53:17 -07:00
|
|
|
read_uint16le(struct stream * s)
|
2013-01-29 21:45:44 -07:00
|
|
|
{
|
2013-01-29 21:53:17 -07:00
|
|
|
uint8_t *d = (uint8_t *) s->buf;
|
|
|
|
|
|
|
|
if (!sskip(s, 2)) {
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
return ((d[0] << 0) | (d[1] << 8));
|
2013-01-29 21:45:44 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
uint32_t
|
2013-01-29 21:53:17 -07:00
|
|
|
read_uint32be(struct stream * s)
|
2013-01-29 21:45:44 -07:00
|
|
|
{
|
2013-01-29 21:53:17 -07:00
|
|
|
uint8_t *d = (uint8_t *) s->buf;
|
|
|
|
|
|
|
|
if (!sskip(s, 4)) {
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
return ((d[0] << 24) | (d[1] << 16) | (d[2] << 8) | (d[3] << 0));
|
2013-01-29 21:45:44 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
uint32_t
|
2013-01-29 21:53:17 -07:00
|
|
|
read_uint32le(struct stream * s)
|
2013-01-29 21:45:44 -07:00
|
|
|
{
|
2013-01-29 21:53:17 -07:00
|
|
|
uint8_t *d = (uint8_t *) s->buf;
|
2013-01-29 21:45:44 -07:00
|
|
|
|
2013-01-29 21:53:17 -07:00
|
|
|
if (!sskip(s, 4)) {
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
return ((d[0] << 0) | (d[1] << 8) | (d[2] << 16) | (d[3] << 24));
|
|
|
|
}
|