forked from trustwallet/wallet-core
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBinaryCoding.h
More file actions
83 lines (76 loc) · 2.62 KB
/
Copy pathBinaryCoding.h
File metadata and controls
83 lines (76 loc) · 2.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Copyright © 2017-2020 Trust Wallet.
//
// This file is part of Trust. The full Trust copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
#pragma once
#include "Data.h"
#include "../BinaryCoding.h"
namespace TW::Algorand {
static inline void encodeString(std::string string, Data &data) {
// encode string header
auto bytes = Data(string.begin(), string.end());
if (bytes.size() < 0x20) {
// fixstr
data.push_back(static_cast<uint8_t>(0xa0 + bytes.size()));
} else if (bytes.size() < 0x100) {
// str 8
data.push_back(static_cast<uint8_t>(0xd9));
data.push_back(static_cast<uint8_t>(bytes.size()));
} else if (bytes.size() < 0x10000) {
// str 16
data.push_back(static_cast<uint8_t>(0xda));
encode16BE(static_cast<uint16_t>(bytes.size()), data);
} else if (bytes.size() < 0x100000000) {
// str 32
data.push_back(static_cast<uint8_t>(0xdb));
encode32BE(static_cast<uint32_t>(bytes.size()), data);
} else {
// too long string
return;
}
append(data, bytes);
}
static inline void encodeNumber(uint64_t number, Data &data) {
if (number < 0x80) {
// positive fixint
data.push_back(static_cast<uint8_t>(number));
} else if (number < 0x100) {
// uint 8
data.push_back(static_cast<uint8_t>(0xcc));
data.push_back(static_cast<byte>(number));
} else if (number < 0x10000) {
// uint 16
data.push_back(static_cast<uint8_t>(0xcd));
encode16BE(static_cast<uint16_t>(number), data);
} else if (number < 0x100000000) {
// uint 32
data.push_back(static_cast<uint8_t>(0xce));
encode32BE(static_cast<uint32_t>(number), data);
} else {
// uint 64
data.push_back(static_cast<uint8_t>(0xcf));
encode64BE(number, data);
}
}
static inline void encodeBytes(const Data &bytes, Data &data) {
auto size = bytes.size();
if (size < 0x100) {
// bin 8
data.push_back(static_cast<uint8_t>(0xc4));
data.push_back(static_cast<uint8_t>(size));
} else if (size < 0x10000) {
// bin 16
data.push_back(static_cast<uint8_t>(0xc5));
encode16BE(static_cast<uint16_t>(size), data);
} else if (size < 0x100000000) {
// bin 32
data.push_back(static_cast<uint8_t>(0xc6));
encode32BE(static_cast<uint32_t>(size), data);
} else {
// too long binary
return;
}
append(data, bytes);
}
} // namespace TW::Algorand