-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchunk.cpp
85 lines (75 loc) · 1.99 KB
/
chunk.cpp
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
#include "chunk.hpp"
namespace midi
{
Chunk::Chunk(Raw raw) : raw(raw) {}
auto Chunk::eof() const -> bool { return pos >= raw.size(); }
auto Chunk::putBack() -> void { --pos; }
auto Chunk::readBytes(int len) -> std::string
{
pos += len;
if (pos > raw.size())
throw Error{"unexpected end of file"};
return std::string{raw.data() + pos - len, static_cast<size_t>(len)};
}
auto Chunk::readVlq() -> uint32_t
{
auto ret = uint32_t{0};
for (auto i = 0U; i < sizeof(uint32_t); ++i)
{
const auto b = readU8();
ret = (ret << 7) | (b & 0x7fU);
if ((b & 0x80) == 0)
break;
}
return ret;
}
auto Chunk::readU8() -> uint8_t
{
if (eof())
throw Error{"unexpected end of file"};
return static_cast<uint8_t>(raw[pos++]);
}
auto Chunk::readU32() -> uint32_t
{
auto ret = uint32_t{};
for (auto i = 0U; i < sizeof(uint32_t); ++i)
ret = (ret << 8) | readU8();
return ret;
}
auto Chunk::readU16() -> uint16_t
{
auto ret = uint16_t{};
for (auto i = 0U; i < sizeof(uint16_t); ++i)
ret = (ret << 8) | readU8();
return ret;
}
auto Chunk::writeU16(std::ostream &st, uint16_t v) -> void
{
for (auto i = 0U; i < sizeof(uint16_t); ++i)
writeU8(st, static_cast<char>((v >> ((sizeof(uint16_t) - i - 1) * 8)) & 0xff));
}
auto Chunk::writeU32(std::ostream &st, uint32_t v) -> void
{
for (auto i = 0U; i < sizeof(uint32_t); ++i)
writeU8(st, static_cast<char>((v >> ((sizeof(uint32_t) - i - 1) * 8)) & 0xff));
}
auto Chunk::writeU8(std::ostream &st, uint8_t v) -> void
{
const auto ch = static_cast<char>(v);
st.write(&ch, 1);
}
auto Chunk::writeVlq(std::ostream &st, uint32_t v) -> void
{
auto ret = std::string{};
while (v != 0)
{
ret = static_cast<char>(v & 0x7fU) + ret;
v >>= 7;
}
if (ret.empty())
ret += char{0};
for (auto i = 0U; i < ret.size() - 1; ++i)
ret[i] |= 0x80;
st << ret;
}
} // namespace midi