@@ -200,8 +200,7 @@ namespace lsp
200200 status_t res = STATUS_OK;
201201 const uint8_t *head = sTemp .data ();
202202 const uint8_t *tail = &head[flength];
203- ssize_t offset = 0 , length = 0 , append = 0 ;
204- size_t rep = 0 ;
203+ size_t offset = 0 ;
205204
206205// IF_TRACE(
207206// wssize_t coffset = sOS.position();
@@ -213,38 +212,32 @@ namespace lsp
213212 while (head < tail)
214213 {
215214 // Estimate the length of match
216- length = sBuffer .lookup (&offset, head, tail-head);
217- if (length == 0 )
218- length = 1 ;
215+ size_t length = sBuffer .lookup (&offset, head, tail-head);
216+ const size_t emit = lsp_min (length, 1u );
219217
220218 // Calc number of repeats
221- rep = calc_repeats (&head[length ], tail);
222- append = length + lsp_min (rep, REPEAT_BUF_MAX);
219+ size_t rep = calc_repeats (&head[emit ], tail);
220+ size_t append = emit + lsp_min (rep, REPEAT_BUF_MAX);
223221
224222 // Estimate size of output
225- size_t est1 = (est_uint (sBuffer .size () + *head, 5 , 5 ) + est_uint (rep, 0 , 4 )) * length; // How many bits per octet
226- size_t est2 = (offset < 0 ) ? est1 + 1 :
227- est_uint (offset, 5 , 5 ) +
228- est_uint (length - 1 , 5 , 5 ) +
229- est_uint (rep, 0 , 4 );
223+ const size_t est1 = est_uint (sBuffer .size () + *head, 5 , 5 ); // How many bits used to encode buffer replay command
224+ const size_t est2 = (length > 0 ) ? est_uint (offset, 5 , 5 ) + est_uint (emit - 1 , 5 , 5 ) : est1 + 1 ; // How many bits used to encode octet command
230225
231- if (est1 > est2) // Prefer buffer over dictionary
226+ // IF_TRACE(
227+ // if (rep)
228+ // ++ repeats;
229+ // )
230+
231+ if (est2 < est1) // Prefer buffer replay over octet emission
232232 {
233- // REPLAY
234- // Offset
233+ // REPLAY BUFFER
234+ // Emit Offset
235235 if ((res = emit_uint (offset, 5 , 5 )) != STATUS_OK)
236236 break ;
237- // Length
238- if ((res = emit_uint (length - 1 , 5 , 5 )) != STATUS_OK)
239- break ;
240- // Repeat
241- if ((res = emit_uint (rep, 0 , 4 )) != STATUS_OK)
237+ // Emit Length
238+ if ((res = emit_uint (emit - 1 , 5 , 5 )) != STATUS_OK)
242239 break ;
243240
244- // Append data to buffer
245- sBuffer .append (head, append);
246- head += length + rep;
247-
248241// IF_TRACE(
249242// ++ replays;
250243// if (rep)
@@ -253,20 +246,22 @@ namespace lsp
253246 }
254247 else
255248 {
256- // OCTET
257- // Value
249+ // EMIT OCTET
250+ // Emit Value
258251 if ((res = emit_uint (sBuffer .size () + *head, 5 , 5 )) != STATUS_OK)
259252 break ;
260- // Repeat
261- if ((res = emit_uint (rep, 0 , 4 )) != STATUS_OK)
262- break ;
263-
264- // Append data to buffer
265- sBuffer .append (head, append);
266- head += length + rep;
267253
268254// IF_TRACE(++octets);
269255 }
256+
257+ // Emit Repeat counter
258+ if ((res = emit_uint (rep, 0 , 4 )) != STATUS_OK)
259+ break ;
260+
261+
262+ // Append data to buffer
263+ sBuffer .append (head, append);
264+ head += emit + rep;
270265 }
271266
272267 // Flush the bit sequence
0 commit comments