-
Notifications
You must be signed in to change notification settings - Fork 1
/
varlength.cpp
119 lines (100 loc) · 2.56 KB
/
varlength.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/*
Copyright (c) 2014 Auston Sterling
See LICENSE for copying permissions.
-----Variable Length Number Implementation-----
Auston Sterling
MIDI's variable-length number format. Big-endian, where the most significant bit
in each byte indicates whether or not there are more bytes to read. The maximum
length is four bytes.
*/
#include "varlength.hpp"
namespace midi
{
//Default constructor, all zeros
VarLength::VarLength()
{
for (int i = 0; i < VARLENGTH_MAX_SIZE; i++)
{
data_[i] = 0;
}
}
//Copy constructor
VarLength::VarLength(const VarLength& vl)
{
for (int i = 0; i < VARLENGTH_MAX_SIZE; i++)
{
data_[i] = vl.data_[i];
}
}
//Constructor from uint32_t
//Since this class can hold 28 bits, this uses the lower 28 bits of the uint32_t
VarLength::VarLength(std::uint32_t in)
{
//Copy over 7 bits at a time
for (int i = VARLENGTH_MAX_SIZE-1; i >= 0; i--)
{
data_[i] = in & 0x7F;
in >>= 7;
}
//Assign most significant bits appropriately
//Last byte always has 0
data_[VARLENGTH_MAX_SIZE-1] &= ~0x80;
//For all other bytes
bool begin = false;
for (int i = 0; i < VARLENGTH_MAX_SIZE-1; i++)
{
//If it's zero and we're not inbetween (1 0 1)
if (data_[i] == 0 && !begin)
{
//Set to 0
data_[i] &= ~0x80;
}
else //Value or inbetween
{
data_[i] |= 0x80;
begin = true;
}
}
}
//Typecast from VarLength to std::uint32_t
VarLength::operator std::uint32_t() const
{
//Create output
std::uint32_t ret = 0;
//Add each component
for (int i = VARLENGTH_MAX_SIZE-1; i >= 0; i--)
{
ret += (data_[i] & 0x7F) << 7*(VARLENGTH_MAX_SIZE - 1 - i);
}
//Return the answer
return ret;
}
std::uint8_t VarLength::operator[](unsigned char index) const
{
//Align with actual data
index += VARLENGTH_MAX_SIZE-size();
return data_[index];
}
//Assignment operator
VarLength& VarLength::operator=(const VarLength& vl)
{
for (int i = 0; i < VARLENGTH_MAX_SIZE; i++)
{
data_[i] = vl.data_[i];
}
return *this;
}
//Returns the size in bytes of this VarLength
std::size_t VarLength::size() const
{
//Starting size is 1
std::size_t ret = 1;
//Check most significant bits to determine length
for (int i = VARLENGTH_MAX_SIZE-2; i >= 0; i--)
{
if (data_[i] & 0x80) ret++;
}
return ret;
}
} //Namespace