aboutsummaryrefslogtreecommitdiffstats
path: root/sources/shiboken6/tests/libsample/str.cpp
blob: 742c0bb01ca47f85f09b534bc87477f3d1b3aa5b (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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "str.h"

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <sstream>

Str::Str(char c)
{
    char str[2] = { c, 0 };
    init(str);
}

Str::Str(const char *cstr)
{
    init(cstr);
}

void Str::init(const char *cstr)
{
    if (cstr)
        m_str = cstr;
}

Str Str::arg(const Str &s) const
{
    size_t idx = m_str.find_first_of("%VAR");
    if (idx == std::string::npos)
        return *this;

    std::string result = m_str;
    result.replace(idx, 4, s.m_str);
    return result.c_str();
}

Str &Str::append(const Str &s)
{
    m_str += s.m_str;
    return *this;
}

Str &Str::prepend(const Str &s)
{
    m_str = s.m_str + m_str;
    return *this;
}

const char *Str::cstring() const
{
    return m_str.c_str();
}

int Str::toInt(bool *ok, int base) const
{
    int result = 0;
    std::istringstream conv(m_str);
    switch (base) {
    case 8:
        conv >> std::oct >> result;
        break;
    case 10:
        conv >> std::dec >> result;
        break;
    case 16:
        conv >> std::hex >> result;
        break;
    }
    const bool my_ok = std::istringstream::eofbit & conv.rdstate();
    if (!my_ok)
        result = 0;
    if (ok)
        *ok = my_ok;
    return result;
}

void Str::show() const
{
    std::printf("%s", cstring());
}

char Str::get_char(int pos) const
{
    return m_str[pos];
}

bool Str::set_char(int pos, char ch)
{
    m_str[pos] = ch;
    return true;
}

Str Str::operator+(int number) const
{
    std::ostringstream in;
    in << m_str << number;
    return in.str().c_str();
}

bool Str::operator==(const Str &other) const
{
    return m_str == other.m_str;
}

Str operator+(int number, const Str &str)
{
    std::ostringstream in;
    in << number << str.m_str;
    return in.str().c_str();
}

bool Str::operator<(const Str &other) const
{
    return m_str < other.m_str;
}

unsigned int strHash(const Str &str)
{
    unsigned int result = 0;
    for (char c : str.m_str)
        result = 5U * result + unsigned(c);
    return result;
}

void changePStr(PStr *pstr, const char *suffix)
{
    pstr->append(suffix);
}

void duplicatePStr(PStr *pstr)
{
    if (!pstr)
        return;
    pstr->append(*pstr);
}