Project::OSiRiON - Git repositories
Project::OSiRiON
News . About . Screenshots . Downloads . Forum . Wiki . Tracker . Git
summaryrefslogtreecommitdiff
blob: c33e46584b49c3911bfd64f3770daf81f83e5a24 (plain)
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
/*
   core/uid.cc
   This file is part of the Osirion project and is distributed under
   the terms of the GNU General Public License version 2.
*/ 

// #include <cstring>
#include "sys/sys.h"
#include "core/uid.h"
#include "math/functions.h"

#include <cstring>

namespace core
{

const char hexchar[16] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};

UID::UID()
{
	clear();
}

UID::~UID()
{
	clear();
}

UID::UID(const UID & other)
{
	assign(other);
}

void UID::assign(const UID & other)
{
	memcpy(uid_key, other.uid_key, UIDKEYSIZE);
}

void UID::assign(const std::string & str)
{
	char new_key[UIDKEYSIZE];
	char l, h;
	
	if (str.size() != UIDKEYSIZE * 2) {
		return;
	}
	
	for (size_t i = 0; i < UIDKEYSIZE; i++ ) {
		h = str[i * 2];
		switch (h) {
			case '0':
			case '1':
			case '2':
			case '3':
			case '4':
			case '5':
			case '6':
			case '7':
			case '8':
			case '9':
				new_key[i] = (h - '0') << 4;
				break;
			case 'a':
			case 'b':
			case 'c':
			case 'd':
			case 'e':
			case 'f':
				new_key[i] = (h - 'a' + 10) << 4;
				break;
			default:
				return;
				break;
		}
		
		l = str[i * 2 + 1];
		switch (l) {
			case '0':
			case '1':
			case '2':
			case '3':
			case '4':
			case '5':
			case '6':
			case '7':
			case '8':
			case '9':
				new_key[i] += (l - '0');
				break;
			case 'a':
			case 'b':
			case 'c':
			case 'd':
			case 'e':
			case 'f':
				new_key[i] += (l - 'a' + 10);
				break;
			default:
				return;
				break;
		}
	}
	
	memcpy(uid_key, new_key, UIDKEYSIZE);
}

void UID::generate()
{
	for (size_t i = 0; i < UIDKEYSIZE; i++) {
		// FIXME the worst random key generator ever
		uid_key[i] = math::randomi(256);
	}
}

bool UID::is_valid() const
{
	for (size_t i = 0; i < UIDKEYSIZE; i++) {
		if (uid_key[i] != 0 )
			return true;
	}
	return false;
}

void UID::clear()
{
	memset(uid_key, 0, UIDKEYSIZE);
}

const std::string UID::str() const {
	std::string s;
	for (size_t i = 0; i < UIDKEYSIZE; i++) {
		// upper nibble
		s += hexchar[ uid_key[i] >> 4 ];
		// lower nibble
		s += hexchar[ uid_key[i] % 16 ];
	}
	return s;
}


} // namespace core