summaryrefslogtreecommitdiff
path: root/src/util/string.cc
blob: bec9638f0352de38d1cf95ad6246cce8621f640a (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

#include "util/string.h"

#include <print>

using namespace std;

namespace ov4
{

/*
 * construct C-style **argv
 * user should be responsible for allocation of **argv
 * and make sure it's large enough
 * argv should be the address to an empty and continuous memory space
 */
void string2argv(const vector<string> &v, char **argv)
{

    // pointers [0, size)
    // nullptr [size]
    // data  [size+1, ...)

    char *p = (char*)(argv + v.size() + 1);

    argv[v.size()] = nullptr;

    for (size_t i = 0; i < v.size(); i++)
    {
        strcpy(p, v[i].c_str());
        argv[i] = p;
        p += v[i].size() + 1; // for '\0'
    }
}

/*
 * allocate heap memory, and construct C-style **argv
 * NB: user should be responsible to ::operator delete();
 */
char **string2argv_alloc(const std::vector<std::string> &v)
{
    size_t size = argv_get_required_size(v);
    char **p = static_cast<char**>(operator new(size));
    string2argv(v, p);
    return p;
}

void argv2string(vector<string> &v, const char * const * argv)
{
    if (argv == nullptr) return; 

    v.clear();
    
    for (size_t i = 0; true; i++)
    {
        if (argv[i] == nullptr) return;
        v.push_back(argv[i]);
    }
}

/*
 * return the memory size required to construct argv[][]
 * in byte
 */
size_t argv_get_required_size(const std::vector<std::string> &v)
{
    size_t ret = 0; 
    ret += sizeof(char*) * (v.size() + 1); // point to every strings in v, and nullptr terminator
    for (auto &sub : v)
        ret += sizeof(char) * (sub.size() + 1); // chars, and null terminator
    return ret;
}

std::string safe_str(const char *s, const char *fallback)
{
    return (s != nullptr) ? s : fallback; 
}

void print_str_hex(const std::string &s)
{
    for (unsigned char c : s)
    {
        print("{:02X} ", c);
    }
}

}