Strings.cpp 1.9 KB
Newer Older
legoc's avatar
legoc 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
/*
 * Copyright 2015 Institut Laue-Langevin
 *
 * Licensed under the EUPL, Version 1.1 only (the "License");
 * You may not use this work except in compliance with the Licence.
 * You may obtain a copy of the Licence at:
 *
 * http://joinup.ec.europa.eu/software/page/eupl
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the Licence is distributed on an "AS IS" basis,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the Licence for the specific language governing permissions and
 * limitations under the Licence.
 */

#include "Strings.h"
#include "BadFormatException.h"
#include <iostream>

using namespace std;

namespace cameo {

std::vector<std::string> split(const std::string& str, char c) {

	vector<string> result;

	int lastIndex = 0;
	int index = str.find(c);
	while (index != string::npos) {
		result.push_back(str.substr(lastIndex, index - lastIndex));
		lastIndex = index + 1;
		index = str.find(c, lastIndex);
	}
	result.push_back(str.substr(lastIndex));

	return result;
}

Endpoint::Endpoint(const std::string& address, int port) {
	m_address = address;
	m_port = port;
}

const std::string& Endpoint::getAddress() const {
	return m_address;
}

int Endpoint::getPort() const {
	return m_port;
}

Endpoint Endpoint::parse(const std::string& str) {

	if (str.substr(0, 6) != "tcp://") {
		throw new BadFormatException("Bad format for endpoint " + str);
	}

	string substr = str.substr(7);
	vector<string> tokens = split(substr, ':');

	if (tokens.size() != 2) {
		throw new BadFormatException("Bad format for endpoint " + str);
	}

	string address = tokens[0];
	int port = 0;

	try {
		port = stoi(tokens[1]);
	}
	catch (...) {
		throw new BadFormatException("Bad format for endpoint " + str);
	}

	return Endpoint(address, port);
}

std::string Endpoint::toString() const {
	return string("tcp://") + m_address + ":" + to_string(m_port);
}

}