aboutsummaryrefslogtreecommitdiffstats
path: root/yql/essentials/utils/parse_double.cpp
blob: 90923160c552ea69f2a596a03cd363becf812b2e (plain) (blame)
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
#include "parse_double.h"

#include <util/string/ascii.h>
#include <util/string/cast.h>

namespace NYql {

namespace {
template <typename T>
bool GenericTryFloatFromString(TStringBuf buf, T& value) {
    value = 0;
    if (!buf.size()) {
        return false;
    }

    if (TryFromString(buf.data(), buf.size(), value)) {
        return true;
    }
    
    const char* ptr = buf.data();
    ui32 size = buf.size();
    char sign = '+';
    if (*ptr == '+' || *ptr == '-') {
        sign = *ptr;
        ++ptr;
        --size;
    }

    if (size != 3) {
        return false;
    }

    // NaN or Inf (ignoring case)
    if (AsciiToUpper(ptr[0]) == 'N' && AsciiToUpper(ptr[1]) == 'A' && AsciiToUpper(ptr[2]) == 'N') {
        value = std::numeric_limits<T>::quiet_NaN();
    } else if (AsciiToUpper(ptr[0]) == 'I' && AsciiToUpper(ptr[1]) == 'N' && AsciiToUpper(ptr[2]) == 'F') {
        value = std::numeric_limits<T>::infinity();
    } else {
        return false;
    }

    if (sign == '-') {
        value = -value;
    }

    return true;
}
}

float FloatFromString(TStringBuf buf) {
    float result = 0;
    if (!TryFloatFromString(buf, result)) {
        throw yexception() << "unable to parse float from '" << buf << "'";
    }

    return result;
}

double DoubleFromString(TStringBuf buf) {
    double result = 0;
    if (!TryDoubleFromString(buf, result)) {
        throw yexception() << "unable to parse double from '" << buf << "'";
    }

    return result;
}

bool TryFloatFromString(TStringBuf buf, float& value) {
    return GenericTryFloatFromString(buf, value);
}

bool TryDoubleFromString(TStringBuf buf, double& value) {
    return GenericTryFloatFromString(buf, value);
}

}