1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
#include "stream.h"
#include "misc.h"
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <errno.h>
// htons, ntohs
#include <arpa/inet.h>
#define STREAM_CHECK_OP(stream, op) \
do { if ((stream->ops->op) == NULL) \
{ \
errno = ENOTSUP; \
return -1; \
} } while (0)
int StreamClose(Stream *stream)
{
if (stream->ops->close)
{
return stream->ops->close(stream);
}
return 0;
}
int64_t StreamRead(void *ptr, size_t size, Stream *stream)
{
STREAM_CHECK_OP(stream, read);
int64_t rv = stream->ops->read(ptr, size, stream);
#if defined(STREAM_HEXDUMP_READ)
if (rv >= 0)
{
printf("READ %lu bytes:\n", size);
DumpHex(ptr, size);
}
#endif
return rv;
}
int64_t StreamReadUint16Be(uint16_t *v, Stream *stream)
{
STREAM_CHECK_OP(stream, read);
if (StreamRead(v, 2, stream) != 2)
return -1;
*v = ntohs(*v);
return 2;
}
int64_t StreamWrite(const void *ptr, size_t size, Stream *stream)
{
STREAM_CHECK_OP(stream, write);
#if defined(STREAM_HEXDUMP_WRITE)
printf("WRITE %lu bytes:\n", size);
DumpHex(ptr, size);
#endif
return stream->ops->write(ptr, size, stream);
}
int64_t StreamWriteUint16Be(uint16_t v, Stream *stream)
{
v = htons(v);
return StreamWrite(&v, sizeof(v), stream);
}
int StreamSeek(Stream *stream, int64_t offset, int whence)
{
STREAM_CHECK_OP(stream, seek);
return stream->ops->seek(stream, offset, whence);
}
int64_t StreamTell(Stream *stream)
{
STREAM_CHECK_OP(stream, tell);
return stream->ops->tell(stream);
}
|