summaryrefslogtreecommitdiff
path: root/src/JSystem/JSupport/JSUMemoryStream.cpp
blob: 6fb5cd03fcac473732fab6062d98d7b431cd7339 (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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include "JSystem/JSystem.h" // IWYU pragma: keep

#include "JSystem/JSupport/JSUMemoryStream.h"
#include <cstring>

void JSUMemoryInputStream::setBuffer(void const* pBuffer, s32 length) {
    mBuffer = pBuffer;
    mLength = length;
    mPosition = 0;
}

u32 JSUMemoryInputStream::readData(void* pData, s32 length) {
    if (mPosition + length > mLength) {
        length = mLength - mPosition;
    }

    if (length > 0) {
        memcpy(pData, (void*)((s32)mBuffer + mPosition), length);
        mPosition += length;
    }

    return length;
}

s32 JSUMemoryInputStream::seekPos(s32 pos, JSUStreamSeekFrom seekFrom) {
    s32 oldPos = mPosition;

    switch (seekFrom) {
    case JSUStreamSeekFrom_SET:
        mPosition = pos;
        break;
    case JSUStreamSeekFrom_END:
        mPosition = mLength - pos;
        break;
    case JSUStreamSeekFrom_CUR:
        mPosition += pos;
        break;
    }

    if (mPosition < 0) {
        mPosition = 0;
    }

    if (mPosition > mLength) {
        mPosition = mLength;
    }

    return mPosition - oldPos;
}

s32 JSUMemoryInputStream::getLength() const {
    return mLength;
}

s32 JSUMemoryInputStream::getPosition() const {
    return mPosition;
}

void JSUMemoryOutputStream::setBuffer(void* pBuffer, s32 length) {
    mBuffer = pBuffer;
    mLength = length;
    mPosition = 0;
}

s32 JSUMemoryOutputStream::writeData(const void* pData, s32 length) {
    if (mPosition + length > mLength) {
        length = mLength - mPosition;
    }

    if (length > 0) {
        memcpy((void*)((s32)mBuffer + mPosition), pData, length);
        mPosition += length;
    }

    return length;
}

s32 JSUMemoryOutputStream::seekPos(s32 pos, JSUStreamSeekFrom seekFrom) {
    s32 oldPos = mPosition;

    switch (seekFrom) {
    case JSUStreamSeekFrom_SET:
        mPosition = pos;
        break;
    case JSUStreamSeekFrom_END:
        mPosition = mLength - pos;
        break;
    case JSUStreamSeekFrom_CUR:
        mPosition += pos;
        break;
    }

    if (mPosition < 0) {
        mPosition = 0;
    }

    if (mPosition > mLength) {
        mPosition = mLength;
    }

    return mPosition - oldPos;
}

s32 JSUMemoryOutputStream::getLength() const {
    return mLength;
}