aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/string_utils/parse_size/parse_size.cpp
blob: 1195f89a51c31bc31378db94b953707af376b473 (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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include "parse_size.h"

#include <util/generic/yexception.h>
#include <util/generic/ylimits.h>
#include <util/string/cast.h> 
#include <util/stream/output.h>

namespace {
    enum ESuffixShifts { 
        ESS_KILO_BYTES = 10, 
        ESS_MEGA_BYTES = 20, 
        ESS_GIGA_BYTES = 30, 
        ESS_TERA_BYTES = 40, 
    }; 

    bool TryShiftValue(ui64& value, ui64 shift) { 
        if (value > (Max<ui64>() >> shift)) { 
            return false; 
        } 

        value <<= shift; 
        return true; 
    }

    ui64 ShiftValue(ui64 value, ui64 shift) { 
        if (!TryShiftValue(value, shift)) { 
            ythrow yexception() << "value overflow '" << value << " << " << shift << "'"; 
        } else { 
            return value; 
        } 
    }

}

namespace NSize {
    ui64 ParseSize(TStringBuf str) { 
        if (! str.size())
            ythrow yexception() << "Wrong size " << str; 
        char suff = tolower(str[str.size() - 1]);
        if (isdigit(suff)) 
            return FromString<ui64>(str); 
        ui64 shift = 1; 
        switch (suff) { 
            case 'k': 
                shift = ESS_KILO_BYTES; 
                break; 
            case 'm': 
                shift = ESS_MEGA_BYTES; 
                break; 
            case 'g': 
                shift = ESS_GIGA_BYTES; 
                break; 
            case 't': 
                shift = ESS_TERA_BYTES; 
                break; 
            default: 
                ythrow yexception() << "Unknown suffix " << str; 
        } 

        ui64 value = FromString<ui64>(str.substr(0, str.size() - 1));
 
        if (!TryShiftValue(value, shift)) { 
            ythrow yexception() << "Value overflow " << str; 
        } else { 
            return value; 
        } 
    }

    TSize FromKiloBytes(ui64 value) { 
        return TSize(ShiftValue(value, ESS_KILO_BYTES)); 
    } 

    TSize FromMegaBytes(ui64 value) { 
        return TSize(ShiftValue(value, ESS_MEGA_BYTES)); 
    }

    TSize FromGigaBytes(ui64 value) { 
        return TSize(ShiftValue(value, ESS_GIGA_BYTES)); 
    } 

    TSize FromTeraBytes(ui64 value) { 
        return TSize(ShiftValue(value, ESS_TERA_BYTES)); 
    } 

}

template <> 
NSize::TSize FromStringImpl<NSize::TSize>(const char* data, size_t len) {
    return NSize::TSize(NSize::ParseSize(TStringBuf(data, len)));
}

template <>
void Out<NSize::TSize>(IOutputStream& os, const NSize::TSize& size) {
    os << size.GetValue();
}