summaryrefslogtreecommitdiff
path: root/src/inc/nibblestream.h
blob: 92ba287212ebcb6fa32a5428ebb2ba0c3ac26b78 (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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
// NibbleStream reader and writer.


#ifndef _NIBBLESTREAM_H_
#define _NIBBLESTREAM_H_

#include "contract.h"
#include "sigbuilder.h"

typedef BYTE NIBBLE;

//-----------------------------------------------------------------------------
// Helpers for compression routines.
//-----------------------------------------------------------------------------
// This class allows variable-length compression of DWORDs.
//
// A value can be stored using one or more nibbles. 3 bits of a nibble are used 
// to store 3 bits of the value, and the top bit indicates if  the following nibble 
// contains rest of the value. If the top bit is not set, then this
// nibble is the last part of the value. 
// The higher bits of the value are written out first, and the lowest 3 bits
// are written out last.
//
// In the encoded stream of bytes, the lower nibble of a byte is used before 
// the high nibble.
//
// A binary value ABCDEFGHI (where A is the highest bit) is encoded as
// the follow two bytes : 1DEF1ABC XXXX0GHI
//
// Examples :
// 0            => X0
// 1            => X1
//
// 7            => X7
// 8            => 09
// 9            => 19
//
// 0x3F (63)    => 7F
// 0x40 (64)    => F9 X0
// 0x41 (65)    => F9 X1
//
// 0x1FF (511)  => FF X7
// 0x200 (512)  => 89 08
// 0x201 (513)  => 89 18

class NibbleWriter
{
public:
    NibbleWriter()
    {
        LIMITED_METHOD_CONTRACT;
        
        m_fPending = false;
    }

    void Flush()
    {
        if (m_fPending)
            m_SigBuilder.AppendByte(m_PendingNibble);
    }

    PVOID GetBlob(DWORD * pdwLength)
    {
        return m_SigBuilder.GetSignature(pdwLength);
    }

    DWORD GetBlobLength()
    {
        return m_SigBuilder.GetSignatureLength();
    }

//.............................................................................
// Writer methods
//.............................................................................


    // Write a single nibble to the stream.
    void WriteNibble(NIBBLE i)
    {
        CONTRACTL
        {
            THROWS;
            GC_NOTRIGGER;
        }
        CONTRACTL_END;

        _ASSERTE(i <= 0xF);

        if (m_fPending)
        {
            // Use the high nibble after the low nibble is used
            m_SigBuilder.AppendByte(m_PendingNibble | (i << 4));
            m_fPending = false;
        }
        else
        {
            // Use the low nibble first
            m_PendingNibble = i;
            m_fPending = true;
        }
    }

    // Write an unsigned int via variable length nibble encoding.
    // We use the bit scheme:
    // 0ABC (if 0 <= dw <= 0x7)
    // 1ABC 0DEF (if 0 <= dw <= 0x7f)
    // 1ABC 1DEF 0GHI (if 0 <= dw <= 0x7FF)
    // etc..

    void WriteEncodedU32(DWORD dw)
    {
        CONTRACTL
        {
            THROWS;
            GC_NOTRIGGER;
        }
        CONTRACTL_END;

        // Fast path for common small inputs
        if (dw <= 63)
        {
            if (dw > 7)
            {
                WriteNibble((NIBBLE) ((dw >> 3) | 8));
            }
            
            WriteNibble((NIBBLE) (dw & 7));
            return;
        }

        // Note we must write this out with the low terminating nibble (0ABC) last b/c the
        // reader gets nibbles in the same order we write them.
        int i = 0;
        while ((dw >> i) > 7)
        {
            i+= 3;
        }
        while(i > 0)
        {
            WriteNibble((NIBBLE) ((dw >> i) & 0x7) | 0x8);
            i -= 3;
        }
        WriteNibble((NIBBLE) dw & 0x7);        
    }

    // Write a signed 32 bit value.
    void WriteEncodedI32(int x)
    {
        CONTRACTL
        {
            THROWS;
            GC_NOTRIGGER;
        }
        CONTRACTL_END;
        
        DWORD dw = (x < 0) ? (((-x) << 1) + 1) : (x << 1);
        WriteEncodedU32(dw);
    };

protected:
    NIBBLE m_PendingNibble;     // Pending value, not yet written out.
    bool m_fPending;

    // SigBuilder is a convenient helper class for writing out small blobs
    SigBuilder m_SigBuilder;
};

//-----------------------------------------------------------------------------

class NibbleReader
{
public:
    NibbleReader(PTR_BYTE pBuffer, size_t size)
    {
        LIMITED_METHOD_CONTRACT;
        SUPPORTS_DAC;
        _ASSERTE(pBuffer != NULL);
        
        m_pBuffer = pBuffer;
        m_cBytes = size;
        m_cNibble = 0;
    }

    // Get the index of the next Byte.
    // This tells us how many bytes (rounding up to whole bytes) have been read.
    // This is can be used to extract raw byte data that may be embedded on a byte boundary in the nibble stream.
    size_t GetNextByteIndex()
    {
        LIMITED_METHOD_CONTRACT;
        SUPPORTS_DAC;

        return (m_cNibble + 1) / 2;
    }

    NIBBLE ReadNibble()
    {
        CONTRACTL
        {
            THROWS;
            GC_NOTRIGGER;
            SUPPORTS_DAC;
        }
        CONTRACTL_END;
        
        NIBBLE i = 0;
        // Bufer should have been allocated large enough to hold data.
        if (!(m_cNibble / 2 < m_cBytes))
        {
            // We should never get here in a normal retail scenario.
            // We could wind up here if somebody provided us invalid data (maybe by corrupting an ngenned image).
            EX_THROW(HRException, (E_INVALIDARG));
        }
        
        BYTE p = m_pBuffer[m_cNibble / 2];
        if ((m_cNibble & 1) == 0)
        {
            // Read the low nibble first
            i = (NIBBLE) (p & 0xF);
        }
        else
        {
            // Read the high nibble after the low nibble has been read
            i = (NIBBLE) (p >> 4) & 0xF;
        }
        m_cNibble++;

        return i;
    }

    // Read an unsigned int that was encoded via variable length nibble encoding
    // from NibbleWriter::WriteEncodedU32.    
    DWORD ReadEncodedU32()
    {
        CONTRACTL
        {
            THROWS;
            GC_NOTRIGGER;
            SUPPORTS_DAC;
        }
        CONTRACTL_END;
        
        DWORD dw =0;

#if defined(_DEBUG) || defined(DACCESS_COMPILE)
        int dwCount = 0;
#endif

        // The encoding is variably lengthed, with the high-bit of every nibble indicating whether
        // there is another nibble in the value.  Each nibble contributes 3 bits to the value.
        NIBBLE n;
        do
        {
#if defined(_DEBUG) || defined(DACCESS_COMPILE)
            // If we've already read 11 nibbles (with 3 bits of usable data each), then we 
            // should be done reading a 32-bit integer.
            // Avoid working with corrupted data and potentially long loops by failing
            if(dwCount > 11)
            {
                _ASSERTE_MSG(false, "Corrupt nibble stream - value exceeded 32-bits in size");
#ifdef DACCESS_COMPILE
                DacError(CORDBG_E_TARGET_INCONSISTENT);
#endif
            }                
            dwCount++;
#endif

            n = ReadNibble();
            dw = (dw << 3) + (n & 0x7);
        } while((n & 0x8) > 0);

        return dw;
    }

    int ReadEncodedI32()
    {
        CONTRACTL
        {
            THROWS;
            GC_NOTRIGGER;
            SUPPORTS_DAC;
        }
        CONTRACTL_END;
        
        DWORD dw = ReadEncodedU32();
        int x = dw >> 1;
        return (dw & 1) ? (-x) : (x);
    }

protected:
    PTR_BYTE m_pBuffer;
    size_t m_cBytes; // size of buffer.
    size_t m_cNibble; // Which nibble are we at?
};



#endif // _NIBBLESTREAM_H_