Coverage Report

Created: 2026-10-17 07:11

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/brunsli/c/dec/context_map_decode.cc
Line
Count
Source
1
// Copyright (c) Google LLC 2019
2
//
3
// Use of this source code is governed by an MIT-style
4
// license that can be found in the LICENSE file or at
5
// https://opensource.org/licenses/MIT.
6
7
#include "./context_map_decode.h"
8
9
#include <brunsli/status.h>
10
#include <brunsli/types.h>
11
12
#include <vector>
13
14
#include "../common/platform.h"
15
#include "./bit_reader.h"
16
#include "./huffman_decode.h"
17
18
namespace brunsli {
19
20
namespace {
21
22
1.23M
void MoveToFront(uint8_t* v, uint8_t index) {
23
1.23M
  uint8_t value = v[index];
24
1.23M
  uint8_t i = index;
25
68.7M
  for (; i; --i) v[i] = v[i - 1];
26
1.23M
  v[0] = value;
27
1.23M
}
28
29
678
void InverseMoveToFrontTransform(uint8_t* v, size_t v_len) {
30
678
  uint8_t mtf[256];
31
174k
  for (size_t i = 0; i < 256; ++i) {
32
173k
    mtf[i] = static_cast<uint8_t>(i);
33
173k
  }
34
1.31M
  for (size_t i = 0; i < v_len; ++i) {
35
1.31M
    uint8_t index = v[i];
36
1.31M
    v[i] = mtf[index];
37
1.31M
    if (index) MoveToFront(mtf, index);
38
1.31M
  }
39
678
}
40
41
}  // namespace
42
43
BrunsliStatus DecodeContextMap(const HuffmanDecodingData& entropy,
44
                               size_t max_run_length_prefix, size_t* index,
45
                               std::vector<uint8_t>* context_map,
46
6.04k
                               BrunsliBitReader* br) {
47
6.04k
  size_t& i = *index;
48
6.04k
  uint8_t* map = context_map->data();
49
6.04k
  const size_t length = context_map->size();
50
1.93M
  while (i < length) {
51
    // Check there is enough deta for Huffman code, RLE and IMTF bit.
52
1.93M
    if (!BrunsliBitReaderCanRead(br, 15 + max_run_length_prefix + 1)) {
53
4.79k
      return BRUNSLI_NOT_ENOUGH_DATA;
54
4.79k
    }
55
1.93M
    uint32_t code = entropy.ReadSymbol(br);
56
1.93M
    if (code == 0) {
57
269k
      map[i] = 0;
58
269k
      ++i;
59
1.66M
    } else if (code <= max_run_length_prefix) {
60
21.5k
      size_t reps = 1u + (1u << code) + (int)BrunsliBitReaderRead(br, code);
61
522k
      while (--reps) {
62
500k
        if (i >= length) return BRUNSLI_INVALID_BRN;
63
500k
        map[i] = 0;
64
500k
        ++i;
65
500k
      }
66
1.63M
    } else {
67
1.63M
      map[i] = (uint8_t)(code - max_run_length_prefix);
68
1.63M
      ++i;
69
1.63M
    }
70
1.93M
  }
71
1.12k
  if (BrunsliBitReaderRead(br, 1)) {
72
678
    InverseMoveToFrontTransform(map, length);
73
678
  }
74
1.12k
  return BrunsliBitReaderIsHealthy(br) ? BRUNSLI_OK : BRUNSLI_INVALID_BRN;
75
6.04k
}
76
77
}  // namespace brunsli