Веб-сайт самохостера Lotigara

summaryrefslogtreecommitdiff
path: root/source/core/StarLexicalCast.hpp
blob: 08dab148d73297594bb558d4eac1f05fcb8ed958 (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
#pragma once

#include "StarFormat.hpp"
#include "StarString.hpp"
#include "StarStringView.hpp"
#include "StarMaybe.hpp"

#include "fast_float.h"

namespace Star {

STAR_EXCEPTION(BadLexicalCast, StarException);

void throwLexicalCastError(std::errc ec, const char* first, const char* last);

template <typename Type>
bool tryLexicalCast(Type& result, const char* first, const char* last) {
  auto res = fast_float::from_chars(first, last, result);
  return res.ptr == last && (res.ec == std::errc() || res.ec == std::errc::result_out_of_range);
}

template <>
bool tryLexicalCast(bool& result, const char* first, const char* last);

template <typename Type>
bool tryLexicalCast(Type& result, String const& s) {
  return tryLexicalCast<Type>(result, s.utf8Ptr(), s.utf8Ptr() + s.utf8Size());
}

template <typename Type>
bool tryLexicalCast(Type& result, StringView s) {
  return tryLexicalCast<Type>(result, s.utf8Ptr(), s.utf8Ptr() + s.utf8Size());
}

template <typename Type>
Maybe<Type> maybeLexicalCast(const char* first, const char* last) {
  Type result{};
  if (tryLexicalCast(result, first, last))
    return result;
  else
    return {};
}

template <typename Type>
Maybe<Type> maybeLexicalCast(StringView s) {
  return maybeLexicalCast<Type>(s.utf8Ptr(), s.utf8Ptr() + s.utf8Size());
}

template <typename Type>
Type lexicalCast(const char* first, const char* last) {
  Type result{};
  auto res = fast_float::from_chars(first, last, result);
  if ((res.ec != std::errc() && res.ec != std::errc::result_out_of_range) || res.ptr != last)
    throwLexicalCastError(res.ec, first, last);
  
  return result;
}

template <>
bool lexicalCast(const char* first, const char* last);

template <typename Type>
Type lexicalCast(StringView s) {
  return lexicalCast<Type>(s.utf8Ptr(), s.utf8Ptr() + s.utf8Size());
}

}