-rw-r--r-- | lib/util.cc | 96 |
1 files changed, 96 insertions, 0 deletions
diff --git a/lib/util.cc b/lib/util.cc new file mode 100644 index 0000000..4bbe6f3 --- a/dev/null +++ b/lib/util.cc | |||
@@ -0,0 +1,96 @@ | |||
1 | #include <midillo/util.h> | ||
2 | #include <midillo/exception.h> | ||
3 | |||
4 | namespace midillo { | ||
5 | |||
6 | unsigned long read32(istream& s) { | ||
7 | unsigned long rv = 0; | ||
8 | for(int t=0;t<4;++t) { | ||
9 | rv<<=8; | ||
10 | rv|=0xFF&s.get(); | ||
11 | if(!s.good()) | ||
12 | throw exception_input_error(CODEPOINT,"Input error"); | ||
13 | } | ||
14 | return rv; | ||
15 | } | ||
16 | |||
17 | unsigned int read16(istream& s) { | ||
18 | unsigned int rv = 0; | ||
19 | for(int t=0;t<2;++t) { | ||
20 | rv<<=8; | ||
21 | rv|=0xFF&s.get(); | ||
22 | if(!s.good()) | ||
23 | throw exception_input_error(CODEPOINT,"Input error"); | ||
24 | } | ||
25 | return rv; | ||
26 | } | ||
27 | |||
28 | unsigned long readVL(istream& s) { | ||
29 | unsigned long rv=s.get(); | ||
30 | if(!s.good()) | ||
31 | throw exception_input_error(CODEPOINT,"Error reading VLQ"); | ||
32 | int b; | ||
33 | if(rv&0x80) { | ||
34 | rv&=0x7F; | ||
35 | do { | ||
36 | rv = (rv<<7)|( (b=s.get())&0x7F ); | ||
37 | if(!s.good()) | ||
38 | throw exception_input_error(CODEPOINT,"Error reading VLQ"); | ||
39 | }while(b&0x80); | ||
40 | } | ||
41 | return rv; | ||
42 | } | ||
43 | |||
44 | void write32(ostream& s,unsigned long d) { | ||
45 | for(int t=3;t>=0;--t) { | ||
46 | s.put(((const char*)&d)[t]); | ||
47 | if(!s.good()) | ||
48 | throw exception_output_error(CODEPOINT,"Output error"); | ||
49 | } | ||
50 | } | ||
51 | |||
52 | void write16(ostream& s,unsigned int d) { | ||
53 | for(int t=1;t>=0;--t) { | ||
54 | s.put(((const char*)&d)[t]); | ||
55 | if(!s.good()) | ||
56 | throw exception_output_error(CODEPOINT,"Output error"); | ||
57 | } | ||
58 | } | ||
59 | |||
60 | void writeVL(ostream& s,unsigned long d) { | ||
61 | // TODO: I don't think this is perfectly written code | ||
62 | unsigned long tmp = d&0x7F; | ||
63 | while(d>>=7) { | ||
64 | tmp<<=8; | ||
65 | tmp |=((d&0x7F)|0x80); | ||
66 | } | ||
67 | for(;;) { | ||
68 | s.put(tmp&0xFF); | ||
69 | if(!s.good()) | ||
70 | throw exception_output_error(CODEPOINT,"Error writing VLQ"); | ||
71 | if(tmp&0x80) | ||
72 | tmp>>=8; | ||
73 | else | ||
74 | break; | ||
75 | } | ||
76 | } | ||
77 | |||
78 | unsigned long calcVLsize(unsigned long d) { | ||
79 | unsigned long rv = 0; | ||
80 | // TODO: imperfect code revisited | ||
81 | unsigned long tmp = d&0x7F; | ||
82 | while(d>>=7) { | ||
83 | tmp<<=8; | ||
84 | tmp |=((d&0x7F)|0x80); | ||
85 | } | ||
86 | for(;;) { | ||
87 | ++rv; | ||
88 | if(tmp&0x80) | ||
89 | tmp>>=8; | ||
90 | else | ||
91 | break; | ||
92 | } | ||
93 | return rv; | ||
94 | } | ||
95 | |||
96 | } | ||