fluffy

Network Archaeology tools for Unix
git clone https://git.woozle.org/neale/fluffy.git

Neale Pickett  ·  2013-07-23

stream.c

  1#include <stdbool.h>
  2#include <stdint.h>
  3#include <stddef.h>
  4#include <string.h>
  5#include "stream.h"
  6
  7void
  8sinit(struct stream *s, char const *buf, size_t buflen, enum endianness endian)
  9{
 10	s->buf = buf;
 11	s->len = buflen;
 12	s->endian = endian;
 13}
 14
 15bool
 16sskip(struct stream *s, size_t count)
 17{
 18	if (count > s->len) {
 19		s->len = 0;
 20		return false;
 21	}
 22
 23	s->buf += count;
 24	s->len -= count;
 25	return true;
 26}
 27
 28bool
 29sread(struct stream *s, void *buf, size_t count)
 30{
 31	void const *d = s->buf;
 32
 33	if (!sskip(s, count)) {
 34		return false;
 35	}
 36	memcpy(buf, d, count);
 37
 38	return true;
 39}
 40
 41
 42
 43uint8_t
 44read_uint8(struct stream *s)
 45{
 46	uint8_t *d = (uint8_t *) s->buf;
 47
 48	if (!sskip(s, 1)) {
 49		return 0;
 50	}
 51	return d[0];
 52}
 53
 54
 55
 56uint16_t
 57read_uint16be(struct stream *s)
 58{
 59	uint8_t *d = (uint8_t *) s->buf;
 60
 61	if (!sskip(s, 2)) {
 62		return 0;
 63	}
 64	return ((d[0] << 8) | (d[1] << 0));
 65}
 66
 67
 68uint16_t
 69read_uint16le(struct stream *s)
 70{
 71	uint8_t *d = (uint8_t *) s->buf;
 72
 73	if (!sskip(s, 2)) {
 74		return 0;
 75	}
 76	return ((d[0] << 0) | (d[1] << 8));
 77}
 78
 79uint16_t 
 80read_uint16(struct stream *s)
 81{
 82	if (s->endian == ENDIAN_BIG) {
 83		return read_uint16be(s);
 84	} else {
 85		return read_uint16le(s);
 86	}
 87}
 88
 89
 90uint32_t
 91read_uint32be(struct stream *s)
 92{
 93	uint8_t *d = (uint8_t *) s->buf;
 94	if (!sskip(s, 4)) {
 95		return 0;
 96	}
 97	return ((d[0] << 24) | (d[1] << 16) | (d[2] << 8) | (d[3] << 0));
 98}
 99
100uint32_t
101read_uint32le(struct stream *s)
102{
103	uint8_t *d = (uint8_t *) s->buf;
104	if (!sskip(s, 4)) {
105		return 0;
106	}
107	return ((d[0] << 0) | (d[1] << 8) | (d[2] << 16) | (d[3] << 24));
108}
109
110uint32_t
111read_uint32(struct stream *s)
112{
113	if (s->endian == ENDIAN_BIG) {
114		return read_uint32be(s);
115	} else {
116		return read_uint32le(s);
117	}
118}