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/>.
31 int huffmanEncodeBuf(uint8_t *outBuf
, int outBufLen
, const uint8_t *inBuf
, int inLen
, const huffmanTable_t
*huffmanTable
)
35 uint8_t *outByte
= outBuf
;
37 uint8_t outBit
= 0x80;
39 for (int ii
= 0; ii
< inLen
; ++ii
) {
40 const int huffCodeLen
= huffmanTable
[*inBuf
].codeLen
;
41 const uint16_t huffCode
= huffmanTable
[*inBuf
].code
;
43 uint16_t testBit
= 0x8000;
45 for (int jj
= 0; jj
< huffCodeLen
; ++jj
) {
46 if (huffCode
& testBit
) {
59 if (ret
>= outBufLen
&& ii
< inLen
- 1 && jj
< huffCodeLen
- 1) {
65 // ensure last character in output buffer is counted
71 int huffmanEncodeBufStreaming(huffmanState_t
*state
, const uint8_t *inBuf
, int inLen
, const huffmanTable_t
*huffmanTable
)
73 uint8_t *savedOutBytePtr
= state
->outByte
;
74 uint8_t savedOutByte
= *savedOutBytePtr
;
76 for (const uint8_t *pos
= inBuf
, *end
= inBuf
+ inLen
; pos
< end
; ++pos
) {
77 const int huffCodeLen
= huffmanTable
[*pos
].codeLen
;
78 const uint16_t huffCode
= huffmanTable
[*pos
].code
;
79 uint16_t testBit
= 0x8000;
81 for (int jj
= 0; jj
< huffCodeLen
; ++jj
) {
82 if (huffCode
& testBit
) {
83 *state
->outByte
|= state
->outBit
;
88 if (state
->outBit
== 0) {
92 ++state
->bytesWritten
;
95 // if buffer is filled and we haven't finished compressing
96 if (state
->bytesWritten
>= state
->outBufLen
&& (pos
< end
- 1 || jj
< huffCodeLen
- 1)) {
97 // restore savedOutByte
98 *savedOutBytePtr
= savedOutByte
;