-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtlv.cpp
More file actions
1841 lines (1568 loc) · 47.2 KB
/
Copy pathtlv.cpp
File metadata and controls
1841 lines (1568 loc) · 47.2 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <cstdio>
#include <cstdarg>
#include <stack>
#include <functional>
#include <algorithm>
#include <cassert>
#include <tlv.hpp>
namespace LibtlvUtil
{
std::vector<uint8_t> unhexify( std::string_view hexInput, bool throw_ex )
{
if( hexInput.size() % 2 != 0 )
{
if( throw_ex )
throw std::invalid_argument( "Hex Decode: input string must have even number of chars!" );
return std::vector<uint8_t>();
}
auto hexChar2Bin = [&](char c)
{
if( c >= '0' && c <= '9' )
return static_cast<uint8_t>(c - '0');
else if ( c >= 'A' && c <= 'F' )
return static_cast<uint8_t>(c - 'A' + 10 );
else if ( c >= 'a' && c <= 'f' )
return static_cast<uint8_t>(c - 'a' + 10 );
throw std::invalid_argument( std::string( "Hex Decode: invalid input char '" ) + c + "'" );
};
std::vector<uint8_t> data;
try
{
data.reserve(hexInput.size()/2 );
for( size_t i = 0; i < hexInput.size(); i+=2 )
{
uint8_t byte = hexChar2Bin( hexInput.at( i ) ) << 4;
byte += hexChar2Bin( hexInput.at( i+1 ) );
data.push_back( byte );
}
}
catch( std::exception &e )
{
data.clear();
if( throw_ex )
throw; // rethrow
}
return data;
}
std::string hexify( const std::vector<uint8_t> &data, bool lower_case )
{
const char* characters = lower_case ? "0123456789abcdef" : "0123456789ABCDEF";
std::string hexString;
hexString.reserve( data.size()*2 );
for ( const auto &byte : data )
{
hexString += characters[byte >> 4];
hexString += characters[byte & 0x0F];
}
return hexString;
}
// most significant bit
static uint32_t msb( uint32_t value )
{
return value >> ( 8 * ( sizeof(value) - __builtin_clz( value ) / 8 - 1 ) );
}
}
using namespace LibtlvUtil;
/*
* TlvTag
*/
Tlv::Tag Tlv::Tag::build( Tlv::Tag::Class cls, bool constructed, uint32_t tag_number )
{
// See X.690 BER tar encoding
static const uint8_t next_byte = 0x80;
static const uint8_t first_byte_bits = 0x1F;
static const uint8_t paytload_bits = 0x7F;
static const uint8_t constructed_tag = 0x20;
static const uint8_t primitive_tag = 0x00;
Tlv::Tag ret; // invalid tag
if( tag_number <= max_tag_number ) // must fit in 4 bytes
{
if ( tag_number < 31 )
{
// Short form
ret._value = (uint32_t)cls | ( constructed ? constructed_tag : primitive_tag ) | tag_number;
} else {
// Long form
// First byte
ret._value = (uint32_t)cls | ( constructed ? constructed_tag : primitive_tag ) | first_byte_bits;
// Next bytes
size_t effective_bits = sizeof( tag_number ) * 8 - __builtin_clz( tag_number );
for( int i = ( effective_bits / 7 ) + ( ( effective_bits % 7 ) ? 1 : 0 ); i > 0; i-- )
{
ret._value <<= 8;
ret._value |= next_byte | ( ( tag_number >> ( 7 * ( i - 1 ) ) ) & paytload_bits );
}
ret._value ^= next_byte; // Unset last byte "next byte" indicator
}
}
return ret;
}
Tlv::Tag Tlv::Tag::build( UniversalTagType type, bool constructed )
{
return build( Class::Universal, constructed, (uint32_t)type );
}
Tlv::Tag::Tag( const char* null_terminated_tag ) :
_value( 0 )
{
for( unsigned i = 0; null_terminated_tag[i] != 0; ++i )
{
if( i >= sizeof(uint32_t) )
{
_value = 0;
return;
}
const uint8_t byte = static_cast<uint8_t>(null_terminated_tag[i]);
_value <<= 8;
_value |= byte;
}
}
size_t Tlv::Tag::size() const
{
if ( _value == empty_tag_value )
{
return 0;
}
else
{
return 4 - __builtin_clz( _value ) / 8;
}
}
Tlv::Tag::Class Tlv::Tag::tag_class() const
{
return (Class)( msb( _value ) & 0xC0 );
}
bool Tlv::Tag::constructed() const
{
return empty() || msb( _value ) & 0x20;
}
uint32_t Tlv::Tag::tag_number() const
{
int i = ( sizeof(_value) - __builtin_clz( _value ) / 8 );
uint32_t tag = ( i > 1 ) ? 0 : ( _value & 0x1F );
for( i--; i > 0; i-- )
{
tag <<= 7;
tag |= ( 0x7F & ( _value >> ( ( i - 1 ) * 8 ) ) );
}
return tag;
}
std::string Tlv::Tag::to_hex_string() const
{
const char* characters = "0123456789ABCDEF";
int most_significant_byte = ( sizeof( _value ) - __builtin_clz( _value ) / 8 ) - 1;
std::string hex_string;
hex_string.reserve( (most_significant_byte + 1) * 2 );
for( int i = most_significant_byte; i >= 0; i-- )
{
uint8_t byte = ( _value >> ( i * 8 ) ) & 0xFF;
hex_string += characters[byte >> 4];
hex_string += characters[byte & 0x0F];
}
return hex_string;
}
/*
* Tlv::Data
*/
struct Tlv::Data
{
Tag tag;
Data* parent;
// Leaf
Value value;
// Branch
ChildContainer children;
Data() :
parent( nullptr )
{}
Data( const Data &rhs ) = delete;
Data operator=( const Data &rhs ) = delete;
~Data()
{
// make sure that parent ptr of children is unset, when parent is destroyed
for( auto& child : children )
{
child.data_->parent = nullptr;
}
}
bool operator==( const Data &rhs ) const
{
return tag == rhs.tag && parent == rhs.parent && value == rhs.value && children == rhs.children;
}
bool operator!=( const Data &rhs ) const
{
return !operator==( rhs );
}
bool empty()
{
return tag.empty() && value.empty() && children.empty();
}
};
/*
* Error
*/
Tlv::Status::Status( const Code code, const size_t length ) :
code_( code ),
length_( length )
{}
Tlv::Status::Status( Code code, const size_t length, const char *fmt, ... ) :
code_( code ),
length_( length )
{
va_list vl, vl2;
va_start( vl, fmt );
va_copy( vl2, vl );
unsigned len = vsnprintf( nullptr, 0, fmt, vl ) + 1;
va_end( vl );
if ( len > 0 )
{
message_.resize( len );
vsnprintf( (char*)message_.c_str(), len, fmt, vl2 );
}
va_end( vl2 );
}
/*
* Parser
*/
class Tlv::Parser
{
static constexpr const uint8_t multi_octet_tag_mask_ = 0x1F;
static constexpr const uint8_t more_octet_mask_ = 0x80;
const uint8_t* _pos;
const uint8_t* _end;
const uint8_t* _tree_start;
inline bool next_byte( uint8_t &byte )
{
if ( _pos < _end )
{
byte = *_pos;
_pos++;
return true;
} else {
return false;
}
}
void skip_zero_bytes()
{
while( _pos < _end && *_pos == 0 ) _pos++;
}
public:
struct ShallowNode // for detected nodes during parser run
{
Tlv::Tag tag;
const uint8_t* begin;
const uint8_t* end;
ShallowNode() :
tag(),
begin( nullptr ),
end( nullptr )
{}
};
Parser( const uint8_t* begin, const uint8_t* end, const uint8_t* tree_start ) :
_pos( begin ),
_end( end ),
_tree_start( tree_start )
{}
bool has_next_tag()
{
skip_zero_bytes();
return _pos < _end;
}
size_t get_offset() const
{
return _pos - _tree_start;
}
Tlv::Status next( ShallowNode &node )
{
uint32_t tag = 0;
uint32_t length = 0;
uint8_t byte;
/* Step 1: Read Tag */
// Read tag first byte
if( !next_byte( byte ) )
return Tlv::Status( Tlv::Status::BadArgument, get_offset(),
"Unexpected error: no more tag at offset %d", static_cast<int>( get_offset() ) );
tag = byte;
// Read tag other bytes
if( ( byte & multi_octet_tag_mask_ ) == multi_octet_tag_mask_ )
{
bool hasNext = true;
for(size_t i = 1; i < sizeof(uint32_t) && hasNext; i++ )
{
if( !next_byte(byte) )
return Tlv::Status( Tlv::Status::UnexpectedEnd, get_offset(),
"Unexpected end of input while reading tag '%X' at offset %d", tag, static_cast<int>( get_offset() ) );
tag = ( tag << 8 ) + byte;
hasNext = (byte & more_octet_mask_);
}
if( hasNext )
{
return Tlv::Status( Tlv::Status::BadLength, get_offset(),
"Tag too long while reading tag '%X' at offset %d", tag, static_cast<int>( get_offset() ) );
}
}
node.tag = tag;
/* Step 2: Read Length */
// Read tag length first byte
if( !next_byte( byte ) )
return Tlv::Status( Tlv::Status::UnexpectedEnd, get_offset(),
"Unexpected end of input while reading length of tag '%X' at offset %d", tag, static_cast<int>( get_offset() ) );
// Reag tag length other bytes
if( byte & more_octet_mask_ )
{
size_t num_bytes = byte ^ more_octet_mask_;
if( num_bytes > sizeof( length ) )
return Tlv::Status( Tlv::Status::BadLength, get_offset(),
"Tag length of tag '%X' too large at offset %d", tag, static_cast<int>( get_offset() ) );
for(size_t i = 0; i < num_bytes; i++ )
{
if( !next_byte( byte ) )
return Tlv::Status( Tlv::Status::UnexpectedEnd, get_offset(),
"Unexpected end of input while reading length of tag '%X' at offset %d", tag, static_cast<int>( get_offset() ) );
length = ( length << 8 ) + byte;
}
}
else
{
length = byte;
}
// Verify data bounds, advance parser _pos
node.begin = _pos;
const uint8_t* valueEnd = _pos + length;
if( valueEnd > _end )
{
node.end = _end;
_pos = _end;
return Tlv::Status( Tlv::Status::UnexpectedEnd, get_offset(),
"Unexpected end of input while reading data of tag '%X' at offset %d", tag, static_cast<int>( get_offset() ) );
} else {
node.end = valueEnd;
_pos = valueEnd;
return Tlv::Status( Tlv::Status::OK, get_offset() ); // Status ok
}
}
};
/*
* FormattedParser
*/
class Tlv::FormattedParser
{
std::string_view data;
size_t pos;
size_t curLine;
size_t curLineStartPos;
static constexpr const uint8_t multi_octet_tag_mask_ = 0x1F;
static constexpr const uint8_t more_octet_mask_ = 0x80;
private:
void read_spaces()
{
while(pos < data.size() && data.at(pos) == ' ')
{
pos++;
}
}
int read_indet()
{
// indent defines tag hierarch (just whitespaces allowed)
auto old_pos = pos;
read_spaces();
return pos - old_pos;
}
std::string_view read_hex( Tlv::Status &status )
{
// hex string for either tag or data, must be terminated by either whitespace, newline, or EOF
auto is_hex_char = []( char c )
{
return ((c >= '0') && (c <= '9')) ||
((c >= 'A') && (c <= 'F')) ||
((c >= 'a') && (c <= 'f'));
};
size_t begin = pos;
// read all hex chars
while( pos < data.size() && is_hex_char(data.at(pos)) )
{
pos++;
}
size_t end = pos;
// check if hex string is terminated correctly with whitespace, newline for enf of input (if exists at all)
if( (end-begin) > 0 && end < data.size() )
{
if( data.at(pos) != ' ' && data.at(pos) != '\n' )
{
status = Tlv::Status( Tlv::Status::UnexpectedData, pos, "Unexpected char '%c' at line %u pos %u while parsing hex data",
data.at(pos), (unsigned)curLine, (unsigned)get_cur_line_pos() );
return std::string_view();
}
}
// check size of hex string
if( (end-begin) % 2 != 0 )
{
status = Tlv::Status( Tlv::Status::UnexpectedData, pos, "Unexpected size of hex encoded data at line %u pos %u",
(unsigned)curLine, (unsigned)get_cur_line_pos() );
return std::string_view();
}
return std::string_view( &data.at(begin), end-begin );
}
Tlv::Tag read_tag( Tlv::Status &status )
{
auto tagHexStr = read_hex( status );
if( !status.ok() )
{
return Tlv::Tag();
}
else if( tagHexStr.empty() )
{
status = Tlv::Status( Tlv::Status::UnexpectedData, pos, "Unexpected end of tag number at line %u pos %u: expected hex encoded tag",
(unsigned)curLine, (unsigned)get_cur_line_pos() );
return Tlv::Tag();
}
// Hex 2 Bin
auto tagBinVec = LibtlvUtil::unhexify( tagHexStr );
// Read tag fist byte
uint32_t tag = tagBinVec[0];
// Read tag other bytes
if( ( tagBinVec[0] & multi_octet_tag_mask_ ) == multi_octet_tag_mask_ )
{
bool hasNext = true;
size_t i = 1;
for(; i < sizeof(uint32_t) && hasNext; i++ )
{
if( i == tagBinVec.size() )
{
status = Tlv::Status( Tlv::Status::BadTag, pos, "Unexpected end of tag number at line %u pos %u",
(unsigned)curLine, (unsigned)get_cur_line_pos() );
return Tlv::Tag();
}
tag = ( tag << 8 ) + tagBinVec[i];
hasNext = (tagBinVec[i] & more_octet_mask_);
}
if( hasNext )
{
status = Tlv::Status( Tlv::Status::BadTag, pos, "Tag too long while reading tag number '%X' at line %u pos %u",
tag, (unsigned)curLine, (unsigned)get_cur_line_pos() );
return Tlv::Tag();
}
if( i != tagBinVec.size())
{
status = Tlv::Status( Tlv::Status::BadTag, pos, "Unexpected trailing data while reading tag number at line %u",
(unsigned)curLine );
}
}
return Tlv::Tag( tag );
}
// optional hex data, emtpy string if not present
std::string_view read_tag_data( Tlv::Status& status )
{
// read spaces before tag data
read_spaces();
return read_hex( status );
}
// optional comment, empty string if not present, no errors
std::string_view read_tag_comment( Tlv::Status & )
{
// read spaces before comment
read_spaces();
// starts with "//"
if( pos < (data.size() - 1) && data.at(pos) == '/' && data.at(pos+1) == '/' )
{
pos+=2;
// read until newline or end of input
size_t begin = pos;
while( pos < data.size() && data.at(pos) != '\n' )
{
pos++;
}
size_t end = pos;
return std::string_view( &data.at(begin), end-begin );
}
return std::string_view();
};
// end of tag andvances the line, ensures all other data was read
void read_end_of_tag( Tlv::Status& status )
{
if( pos < data.size() && data.at( pos ) == '\n' )
{
pos++;
curLine++;
curLineStartPos = pos;
}
else if ( pos < data.size() )
{
status = Tlv::Status( Tlv::Status::UnexpectedData, pos, "Unexpected char '%c' at line %u pos %u",
data.at(pos), (unsigned)curLine, (unsigned)get_cur_line_pos() );
}
}
public:
struct ShallowNode
{
int line;
int indent;
Tlv::Tag tag;
std::string_view hexData;
std::string_view comment;
};
FormattedParser( std::string_view data ) :
data( data ),
pos( 0 ),
curLine( 1 ),
curLineStartPos( 0 )
{}
bool has_next_tag() { return data.size() > pos; }
size_t get_cur_pos() { return pos; }
size_t get_cur_line() { return curLine; }
size_t get_cur_line_pos() { return pos - curLineStartPos + 1; }
Tlv::Status next( ShallowNode& node )
{
Tlv::Status status;
node.line = curLine;
node.indent = read_indet();
// Get Tag
node.tag = read_tag( status );
if( !status.ok() )
{
return status;
}
// Get Tag data (optional)
node.hexData = read_tag_data( status );
if( !status.ok() )
{
return status;
}
// Get Tag comment (optional)
node.comment = read_tag_comment( status );
if( !status.ok() )
{
return status;
}
// Read enf of line, ensure no junk data is left
read_end_of_tag( status );
return status;
}
};
/**
* Tlv
*/
Tlv::Tlv() :
data_( std::make_shared<Data>() )
{}
Tlv::Tlv( const Tag tag ) :
Tlv()
{
data_->tag = tag;
}
Tlv::Tlv( const Tag tag, const Value &data ) :
Tlv( tag )
{
data_->value = data;
}
Tlv::Tlv( const Tag tag, const Value &&data ) :
Tlv( tag )
{
data_->value = std::move( data );
}
Tlv::Tlv( const Tag tag, const uint8_t *data, size_t size ) :
Tlv( tag )
{
data_->value = Value( data, data + size );
}
Tlv::Tlv( const Tag tag, const char *s ) :
Tlv( tag, std::string( s ) )
{}
Tlv::Tlv( const Tag tag, const std::string &s ) :
Tlv( tag )
{
data_->value = Value( s.data(), s.data() + s.size() );
}
template<typename T>
void build_int_value_raw( Tlv::Value& buf, const T val )
{
/*
* Write as unsigned integer with MSB byte order,
* without leading 0x00-bytes (not BER-TLV signed integer)
*/
using U = std::make_unsigned_t<T>;
const U uval = static_cast<U>(val);
auto getByte = [&](int n) -> uint8_t
{
return static_cast<uint8_t>( uval >> ( n * 8 ) );
};
if ( val == 0 )
{
buf.push_back( 0x00 );
}
else
{
int i = sizeof( T ) - 1;
// skip leading 0x00-bytes
for( ; i >= 0 && getByte( i ) == 0x00; i-- );
// store other bytes
for( ; i >= 0; i-- )
{
buf.push_back( getByte( i ) );
}
}
}
template<typename T>
T read_int_value_raw( const Tlv::Value& buf )
{
/*
* Read as unsigned integer with MSB byte order (not BER-TLV signed integer)
*
* If buffer is bigger than the target value it will only read
* the tail bytes in MSB order (overflow).
*/
T val = 0;
// start with tail bytes if target value would overflow (MSB order)
size_t i = buf.size() > sizeof( T ) ? buf.size() - sizeof( T ) : 0;
for( ; i < buf.size(); i++ )
{
if constexpr(sizeof(T) > 1)
{
val <<= 8;
}
val |= buf.at( i );
}
return val;
}
Tlv::Tlv( const Tag tag, bool b ) :
Tlv( tag )
{
data_->value.push_back( (uint8_t)b );
}
Tlv::Tlv( const Tag tag, int8_t i ) :
Tlv( tag )
{
data_->value.push_back( i );
}
Tlv::Tlv( const Tag tag, int16_t i ) :
Tlv( tag )
{
build_int_value_raw<int16_t>( data_->value, i );
}
Tlv::Tlv( const Tag tag, int32_t i ) :
Tlv( tag )
{
build_int_value_raw<int32_t>( data_->value, i );
}
Tlv::Tlv( const Tag tag, int64_t i ) :
Tlv( tag )
{
build_int_value_raw<int64_t>( data_->value, i );
}
Tlv::Tlv( const Tag tag, uint8_t i ) :
Tlv( tag )
{
data_->value.push_back( i );
}
Tlv::Tlv( const Tag tag, uint16_t i ) :
Tlv( tag )
{
build_int_value_raw<int16_t>( data_->value, i );
}
Tlv::Tlv( const Tag tag, uint32_t i ) :
Tlv( tag )
{
build_int_value_raw<int32_t>( data_->value, i );
}
Tlv::Tlv( const Tag tag, uint64_t i ) :
Tlv( tag )
{
build_int_value_raw<int64_t>( data_->value, i );
}
Tlv::Tlv( const Tag tag, Tlv &child ) :
Tlv( tag )
{
push_back( child );
}
Tlv::Tlv(const Tag tag, Tlv&& child ) :
Tlv( tag )
{
push_back( std::move(child) );
}
Tlv::Tlv( const Tlv &rhs ) :
data_( rhs.data_ )
{}
Tlv::Tlv( Tlv &&rhs ) :
data_( std::move(rhs.data_) )
{}
Tlv::Tlv( const std::shared_ptr<Data> &data ) :
data_( data )
{}
Tlv::Tlv( std::shared_ptr<Data> &&data ) :
data_( std::move(data) )
{}
Tlv::~Tlv()
{}
Tlv& Tlv::operator=( const Tlv &rhs )
{
data_ = rhs.data_;
return *this;
}
Tlv& Tlv::operator=( Tlv &&rhs )
{
data_ = std::move( rhs.data_ );
return *this;
}
bool Tlv::operator==( const Tlv &rhs ) const
{
return *data_ == *rhs.data_;
}
bool Tlv::operator!=( const Tlv &rhs ) const
{
return *data_ != *rhs.data_;
}
bool Tlv::identical(const Tlv& other) const
{
return data_ == other.data_;
}
Tlv::operator bool() const
{
return !empty();
}
Tlv Tlv::parse( const uint8_t *data, const size_t size, Status &s, int depth )
{
Tlv tlv;
s = tlv.parse( data, size, depth );
return tlv;
}
Tlv Tlv::parse_all( const uint8_t *data, const size_t size, Status &s, int depth )
{
Tlv root;
s = root.parse_all( data, size, depth );
return root;
}
Tlv::Status Tlv::parse( const uint8_t *data, const size_t size, int depth )
{
reset();
return _parse_one( *this, data, data + size, data, depth );
}
Tlv::Status Tlv::parse_all(const uint8_t* data, const size_t size, int depth )
{
reset();
return _parse( *this, data, data + size, data, depth );
}
Tlv Tlv::parse_formatted(const uint8_t *data, const size_t size, Status &s)
{
Tlv root;
s = root.parse_formatted( data, size );
return root;
}
Tlv Tlv::parse_formatted(std::string_view data, Status &s)
{
Tlv root;
s = root.parse_formatted( data );
return root;
}
Tlv::Status Tlv::parse_formatted(const uint8_t *data, const size_t size)
{
reset();
std::string_view formattedStr( reinterpret_cast<const char*>(data), size );
return _parse_formatted( *this, formattedStr );
}
Tlv::Status Tlv::parse_formatted( std::string_view data )
{
reset();
return _parse_formatted( *this, data );
}
Tlv::Status Tlv::expand( int depth )
{
Status s;
if( data_->value.size() > 0 )
{
s = _parse( *this, data_->value.data(), data_->value.data() + data_->value.size() , &data_->value.front(), depth );
if( s )
{
data_->value.clear();
}
else
{
data_->children.clear();
}
} else {
s = Status( Status::BadArgument, 0, "Node has no value" );
}
return s;
}
std::vector<uint8_t> Tlv::dump() const
{
struct BuildStackFrame
{
const Tlv* node;
int nodeNumber;
size_t parentOffset;
};
struct BuildElement
{
const Tlv* node;
size_t size;
};
auto len_field_size = [](size_t len)
{
if( len <= 127 )
return 1;
else
return 4 - __builtin_clz( len ) / 8 + 1;
};
int nodeNumber = 0;
std::vector<BuildStackFrame> buildStack;
std::vector<BuildElement> buildElements;
buildStack.push_back( { this, -1, 0 } ); // start with root
while( !buildStack.empty() )
{
auto ¤tElement = buildStack.back();
// unexplored node
if( currentElement.nodeNumber == -1 )
{
// assign node number (dfs order)
currentElement.nodeNumber = nodeNumber++;
buildElements.push_back( { currentElement.node, 0 } );
// leaf node: set payload size
if( currentElement.node->data_->children.empty() )
{
buildElements[currentElement.nodeNumber].size += currentElement.node->data_->value.size();
}
// branch node: add children to stack
else
{
auto &children = currentElement.node->data_->children;
size_t off = 0;
for( int r = children.size() -1; r >= 0; --r )
{
buildStack.push_back({ &children[r], -1, ++off });
}
}
}
// already explored node, size is known, propagate to parent nodes
else
{
if( currentElement.parentOffset > 0 )
{
// add own size to parent size + size for tag + len field
auto &parentNodeNumber = buildStack[buildStack.size() - 1 - currentElement.parentOffset].nodeNumber;
// this node only has a positive node size and len field if, the tag is not emtpy
if( !currentElement.node->tag().empty() )
{
buildElements[parentNodeNumber].size
+= currentElement.node->tag().size() // tag size
+ len_field_size( buildElements[currentElement.nodeNumber].size ); // len field size
}
buildElements[parentNodeNumber].size += buildElements[currentElement.nodeNumber].size; // payload size