2 * This file is part of Cleanflight and Betaflight.
4 * Cleanflight and Betaflight are free software. You can redistribute
5 * this software and/or modify this software under the terms of the
6 * GNU General Public License as published by the Free Software
7 * Foundation, either version 3 of the License, or (at your option)
10 * Cleanflight and Betaflight are distributed in the hope that they
11 * will be useful, but WITHOUT ANY WARRANTY; without even the implied
12 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 * See the GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this software.
18 * If not, see <http://www.gnu.org/licenses/>.
27 int huffmanEncodeBuf(uint8_t *outBuf
, int outBufLen
, const uint8_t *inBuf
, int inLen
, const huffmanTable_t
*huffmanTable
)
31 uint8_t *outByte
= outBuf
;
33 uint8_t outBit
= 0x80;
35 for (int ii
= 0; ii
< inLen
; ++ii
) {
36 const int huffCodeLen
= huffmanTable
[*inBuf
].codeLen
;
37 const uint16_t huffCode
= huffmanTable
[*inBuf
].code
<< 4;
39 uint16_t testBit
= 0x8000;
41 for (int jj
= 0; jj
< huffCodeLen
; ++jj
) {
42 if (huffCode
& testBit
) {
55 if (ret
>= outBufLen
&& ii
< inLen
- 1 && jj
< huffCodeLen
- 1) {
61 // ensure last character in output buffer is counted
67 int huffmanEncodeBufStreaming(huffmanState_t
*state
, const uint8_t *inBuf
, int inLen
, const huffmanTable_t
*huffmanTable
)
69 uint8_t *savedOutBytePtr
= state
->outByte
;
70 uint8_t savedOutByte
= *savedOutBytePtr
;
72 for (const uint8_t *pos
= inBuf
, *end
= inBuf
+ inLen
; pos
< end
; ++pos
) {
73 const int huffCodeLen
= huffmanTable
[*pos
].codeLen
;
74 const uint16_t huffCode
= huffmanTable
[*pos
].code
<< 4;
75 uint16_t testBit
= 0x8000;
77 for (int jj
= 0; jj
< huffCodeLen
; ++jj
) {
78 if (huffCode
& testBit
) {
79 *state
->outByte
|= state
->outBit
;
84 if (state
->outBit
== 0) {
88 ++state
->bytesWritten
;
91 // if buffer is filled and we haven't finished compressing
92 if (state
->bytesWritten
>= state
->outBufLen
&& (pos
< end
- 1 || jj
< huffCodeLen
- 1)) {
93 // restore savedOutByte
94 *savedOutBytePtr
= savedOutByte
;