summaryrefslogtreecommitdiff
path: root/src/mbgl/style/conversion/constant.cpp
blob: e837c4e70bb158dfeffd272ccedf156d99bc0d57 (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
#include <mbgl/style/conversion/constant.hpp>

namespace mbgl {
namespace style {
namespace conversion {

optional<bool> Converter<bool>::operator()(const Convertible& value, Error& error) const {
    optional<bool> converted = toBool(value);
    if (!converted) {
        error = { "value must be a boolean" };
        return {};
    }
    return *converted;
}

optional<float> Converter<float>::operator()(const Convertible& value, Error& error) const {
    optional<float> converted = toNumber(value);
    if (!converted) {
        error = { "value must be a number" };
        return {};
    }
    return *converted;
}

optional<std::string> Converter<std::string>::operator()(const Convertible& value, Error& error) const {
    optional<std::string> converted = toString(value);
    if (!converted) {
        error = { "value must be a string" };
        return {};
    }
    return *converted;
}

optional<Color> Converter<Color>::operator()(const Convertible& value, Error& error) const {
    optional<std::string> string = toString(value);
    if (!string) {
        error = { "value must be a string" };
        return {};
    }

    optional<Color> color = Color::parse(*string);
    if (!color) {
        error = { "value must be a valid color" };
        return {};
    }

    return *color;
}

optional<std::vector<float>> Converter<std::vector<float>>::operator()(const Convertible& value, Error& error) const {
    if (!isArray(value)) {
        error = { "value must be an array" };
        return {};
    }

    std::vector<float> result;
    result.reserve(arrayLength(value));

    for (std::size_t i = 0; i < arrayLength(value); ++i) {
        optional<float> number = toNumber(arrayMember(value, i));
        if (!number) {
            error = { "value must be an array of numbers" };
            return {};
        }
        result.push_back(*number);
    }

    return result;
}

optional<std::vector<std::string>> Converter<std::vector<std::string>>::operator()(const Convertible& value, Error& error) const {
    if (!isArray(value)) {
        error = { "value must be an array" };
        return {};
    }

    std::vector<std::string> result;
    result.reserve(arrayLength(value));

    for (std::size_t i = 0; i < arrayLength(value); ++i) {
        optional<std::string> string = toString(arrayMember(value, i));
        if (!string) {
            error = { "value must be an array of strings" };
            return {};
        }
        result.push_back(*string);
    }

    return result;
}

} // namespace conversion
} // namespace style
} // namespace mbgl