Coverage Report

Created: 2026-10-28 07:07

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/util-linux/lib/encode.c
Line
Count
Source
1
/*
2
 * Based on code from libblkid,
3
 *
4
 * Copyright (C) 2008 Kay Sievers <kay.sievers@vrfy.org>
5
 * Copyright (C) 2009 Karel Zak <kzak@redhat.com>
6
 * Copyright (C) 2020 Pali Rohár <pali.rohar@gmail.com>
7
 *
8
 * This file may be redistributed under the terms of the
9
 * GNU Lesser General Public License.
10
 */
11
#include "c.h"
12
#include "encode.h"
13
14
size_t ul_encode_to_utf8(int enc, unsigned char *dest, size_t len,
15
      const unsigned char *src, size_t count)
16
50
{
17
50
  size_t i, j;
18
50
  uint32_t c;
19
50
  uint16_t c2;
20
21
286
  for (j = i = 0; i < count; i++) {
22
280
    if (enc == UL_ENCODE_UTF16LE) {
23
0
      if (i+2 > count)
24
0
        break;
25
0
      c = (src[i+1] << 8) | src[i];
26
0
      i++;
27
280
    } else if (enc == UL_ENCODE_UTF16BE) {
28
274
      if (i+2 > count)
29
3
        break;
30
271
      c = (src[i] << 8) | src[i+1];
31
271
      i++;
32
271
    } else if (enc == UL_ENCODE_LATIN1) {
33
6
      c = src[i];
34
6
    } else {
35
0
      return 0;
36
0
    }
37
277
    if ((enc == UL_ENCODE_UTF16LE || enc == UL_ENCODE_UTF16BE) &&
38
271
        c >= 0xD800 && c <= 0xDBFF && i+2 < count) {
39
10
      if (enc == UL_ENCODE_UTF16LE)
40
0
        c2 = (src[i+2] << 8) | src[i+1];
41
10
      else
42
10
        c2 = (src[i+1] << 8) | src[i+2];
43
10
      if (c2 >= 0xDC00 && c2 <= 0xDFFF) {
44
3
        c = 0x10000 + ((c - 0xD800) << 10) + (c2 - 0xDC00);
45
3
        i += 2;
46
3
      }
47
10
    }
48
277
    if (c == 0) {
49
14
      dest[j] = '\0';
50
14
      break;
51
14
    }
52
53
263
    if (c < 0x80) {
54
42
      if (j+1 >= len)
55
3
        break;
56
39
      dest[j++] = (uint8_t) c;
57
221
    } else if (c < 0x800) {
58
62
      if (j+2 >= len)
59
5
        break;
60
57
      dest[j++] = (uint8_t) (0xc0 | (c >> 6));
61
57
      dest[j++] = (uint8_t) (0x80 | (c & 0x3f));
62
159
    } else if (c < 0x10000) {
63
156
      if (j+3 >= len)
64
19
        break;
65
137
      dest[j++] = (uint8_t) (0xe0 | (c >> 12));
66
137
      dest[j++] = (uint8_t) (0x80 | ((c >> 6) & 0x3f));
67
137
      dest[j++] = (uint8_t) (0x80 | (c & 0x3f));
68
137
    } else {
69
3
      if (j+4 >= len)
70
0
        break;
71
3
      dest[j++] = (uint8_t) (0xf0 | (c >> 18));
72
3
      dest[j++] = (uint8_t) (0x80 | ((c >> 12) & 0x3f));
73
3
      dest[j++] = (uint8_t) (0x80 | ((c >> 6) & 0x3f));
74
3
      dest[j++] = (uint8_t) (0x80 | (c & 0x3f));
75
3
    }
76
263
  }
77
50
  dest[j] = '\0';
78
50
  return j;
79
50
}