fluffy/stream.c

119 lines
1.6 KiB
C
Raw Permalink Normal View History

2013-01-29 21:45:44 -07:00
#include <stdbool.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include "stream.h"
void
2013-07-23 16:30:38 -06:00
sinit(struct stream *s, char const *buf, size_t buflen, enum endianness endian)
2013-01-29 21:45:44 -07:00
{
2013-01-29 21:53:17 -07:00
s->buf = buf;
s->len = buflen;
2013-07-23 16:30:38 -06:00
s->endian = endian;
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-07-23 16:30:38 -06: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
}
2013-07-23 16:30:38 -06:00
2013-01-29 21:45:44 -07:00
uint8_t
2013-07-23 16:30:38 -06: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
}
2013-07-23 16:30:38 -06:00
2013-01-29 21:45:44 -07:00
uint16_t
2013-07-23 16:30:38 -06: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
}
2013-07-23 16:30:38 -06:00
2013-01-29 21:45:44 -07:00
uint16_t
2013-07-23 16:30:38 -06: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
}
2013-07-23 16:30:38 -06:00
uint16_t
read_uint16(struct stream *s)
{
if (s->endian == ENDIAN_BIG) {
return read_uint16be(s);
} else {
return read_uint16le(s);
}
}
2013-01-29 21:45:44 -07:00
uint32_t
2013-07-23 16:30:38 -06: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-07-23 16:30:38 -06: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;
if (!sskip(s, 4)) {
return 0;
}
return ((d[0] << 0) | (d[1] << 8) | (d[2] << 16) | (d[3] << 24));
}
2013-07-23 16:30:38 -06:00
uint32_t
read_uint32(struct stream *s)
{
if (s->endian == ENDIAN_BIG) {
return read_uint32be(s);
} else {
return read_uint32le(s);
}
}