bytes.h 1.61 KB
Newer Older
/jdi/'s avatar
/jdi/ committed
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
/*
 * Bytes.h
 *
 *  Created on: 02.10.2015
 *      Author: jdi
 */

#ifndef BYTES_H_
#define BYTES_H_

#include <initializer_list>
#include <functional>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <map>

typedef unsigned char byte;

class bytes: public std::vector<unsigned char> {
	typedef std::vector<unsigned char> vector;
public:
	using vector::operator[];
	bytes() {
	}
	bytes(int n) :
			vector(n) {
	}

	bytes(std::string);

	bytes(std::initializer_list<uint8_t> s)
	{
		for (uint8_t b : s) {
			this->push_back(b);
    }
	}

	bytes(const vector &B) {
		this->reserve(B.size());
		this->insert(this->begin(), B.begin(), B.end());
	}

	bytes readHex(std::string s){
		return bytes(s);
	}

	bytes operator=(const vector &B) {
		this->reserve(B.size());
		this->insert(this->begin(), B.begin(), B.end());
		return *this;
	}

	bytes &operator+=(const bytes &B) {
		this->reserve(this->size() + B.size());
		this->insert(this->end(), B.begin(), B.end());
		return *this;
	}

	bytes operator+(const bytes &B) {
		bytes AB;
		AB.reserve(this->size() + B.size());
		AB.insert(AB.end(), this->begin(), this->end());
		AB.insert(AB.end(), B.begin(), B.end());
		return AB;
	}

	friend std::ostream& operator<<(std::ostream& out, const bytes& arr) {
		if (arr.size() > 0) {
			out << std::hex << std::setw(2) << std::setfill('0')
					<< (unsigned) arr[0];
		}
		for (unsigned i = 1; i < arr.size(); i++) {
			out << ":" << std::setw(2) << std::setfill('0') << (unsigned) arr[i];
		}
		return out;
	}

	operator std::string() {
		std::string s(this->begin(),this->end());
		return s;
	}
};

#endif /* BYTES_H_ */