aboutsummaryrefslogtreecommitdiff
path: root/src/stream.c
blob: 1c466684d40bdd81e3afbfce8a996665e97a5ba0 (plain)
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
78
79
80
81
82
83
84
85
86
87
88
#include "stream.h"
#include "misc.h"

#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <errno.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)
{
    int64_t rv;
    STREAM_CHECK_OP(stream, read);
    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)
{
    unsigned char data[2];
    STREAM_CHECK_OP(stream, read);
    if (StreamRead(data, 2, stream) != 2)
        return -1;
    *v = (data[1] << 0) | (data[0] << 1);
    return 2;
}

int64_t StreamReadByte(unsigned char *byte, Stream *stream)
{
    return StreamRead(byte, sizeof(*byte), stream);
}

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)
{
    unsigned char data[2];
    data[0] = v >> 8;
    data[1] = (unsigned char) (v & 0xFF);
    return StreamWrite(data, sizeof(data), stream);
}

int64_t StreamWriteByte(unsigned char byte, Stream *stream)
{
    return StreamWrite(&byte, sizeof(byte), 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);
}