1// LAF Base Library
2// Copyright (c) 2001-2016 David Capello
3//
4// This file is released under the terms of the MIT license.
5// Read LICENSE.txt for more information.
6
7#ifdef HAVE_CONFIG_H
8#include "config.h"
9#endif
10
11#include "base/convert_to.h"
12#include "base/sha1.h"
13#include <cstdio>
14#include <cstdlib>
15
16namespace base {
17
18template<> int convert_to(const std::string& from)
19{
20 return std::strtol(from.c_str(), NULL, 10);
21}
22
23template<> std::string convert_to(const int& from)
24{
25 char buf[32];
26 std::sprintf(buf, "%d", from);
27 return buf;
28}
29
30template<> uint32_t convert_to(const std::string& from)
31{
32 return std::strtoul(from.c_str(), NULL, 10);
33}
34
35template<> std::string convert_to(const uint32_t& from)
36{
37 char buf[32];
38 std::sprintf(buf, "%u", from);
39 return buf;
40}
41
42template<> double convert_to(const std::string& from)
43{
44 return std::strtod(from.c_str(), NULL);
45}
46
47template<> std::string convert_to(const double& from)
48{
49 char buf[32];
50 std::sprintf(buf, "%g", from);
51 return buf;
52}
53
54template<> Sha1 convert_to(const std::string& from)
55{
56 std::vector<uint8_t> digest(Sha1::HashSize);
57
58 for (size_t i=0; i<Sha1::HashSize; ++i) {
59 if (i*2+1 >= from.size())
60 break;
61
62 digest[i] = convert_to<int>(from.substr(i*2, 2));
63 }
64
65 return Sha1(digest);
66}
67
68template<> std::string convert_to(const Sha1& from)
69{
70 char buf[3];
71 std::string res;
72 res.reserve(2*Sha1::HashSize);
73
74 for(int c=0; c<Sha1::HashSize; ++c) {
75 sprintf(buf, "%02x", from[c]);
76 res += buf;
77 }
78
79 return res;
80}
81
82} // namespace base
83