Coverage Summary for Class: PathEncoder (co.rsk.trie)
Class |
Class, %
|
Method, %
|
Line, %
|
PathEncoder |
100%
(1/1)
|
83.3%
(5/6)
|
88.9%
(24/27)
|
1 /*
2 * This file is part of RskJ
3 * Copyright (C) 2017 RSK Labs Ltd.
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU Lesser General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 package co.rsk.trie;
20
21 import javax.annotation.Nonnull;
22
23 /**
24 * Created by martin.medina on 5/04/17.
25 */
26 public class PathEncoder {
27 private PathEncoder() { }
28
29 @Nonnull
30 public static byte[] encode(byte[] path) {
31 if (path == null) {
32 throw new IllegalArgumentException("path");
33 }
34
35 return encodeBinaryPath(path);
36 }
37
38 @Nonnull
39 public static byte[] decode(byte[] encoded, int length) {
40 if (encoded == null) {
41 throw new IllegalArgumentException("encoded");
42 }
43
44 return decodeBinaryPath(encoded, length);
45 }
46
47 @Nonnull
48 // First bit is MOST SIGNIFICANT
49 private static byte[] encodeBinaryPath(byte[] path) {
50 int lpath = path.length;
51 int lencoded = calculateEncodedLength(lpath);
52
53 byte[] encoded = new byte[lencoded];
54 int nbyte = 0;
55
56 for (int k = 0; k < lpath; k++) {
57 int offset = k % 8;
58 if (k > 0 && offset == 0) {
59 nbyte++;
60 }
61
62 if (path[k] == 0) {
63 continue;
64 }
65
66 encoded[nbyte] |= 0x80 >> offset;
67 }
68
69 return encoded;
70 }
71
72 @Nonnull
73 // length is the length in bits. For example ({1},8) is fine
74 // First bit is MOST SIGNIFICANT
75 private static byte[] decodeBinaryPath(byte[] encoded, int bitlength) {
76 byte[] path = new byte[bitlength];
77
78 for (int k = 0; k < bitlength; k++) {
79 int nbyte = k / 8;
80 int offset = k % 8;
81
82 if (((encoded[nbyte] >> (7 - offset)) & 0x01) != 0) {
83 path[k] = 1;
84 }
85 }
86
87 return path;
88 }
89
90 public static int calculateEncodedLength(int keyLength) {
91 return keyLength / 8 + (keyLength % 8 == 0 ? 0 : 1);
92 }
93 }