summaryrefslogtreecommitdiff
path: root/tools/utils.c
blob: a7c287841133a260ec8b680dceea8612eb324988 (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
#include <string>
#include <sstream>
#include <iomanip>
#include <stdlib.h>     /* for abs() */
/////                   <cmath> would not be an improvement
/////                   due to lack of interger abs()
/////                   and ambiguous (and inefficient) promotion
#include <ctype.h>      /* for isalnum() */
using namespace std;


// strip off the directory part of a path, leaving just
// the basic filename
string basename(const string path){
  size_t where = path.rfind("/");
  if (where != string::npos) return path.substr(1+where);
  return path;
}

////////////////
// little utility to help with argument parsing:
//
int prefix(const string shorter, const string longer){
  return shorter == longer.substr(0, shorter.length());
}

///////////////
// print a time as (-)hh:mm:ss
//
string time_out(const int _ttt){
using namespace std;
  int ttt(abs(_ttt));
  int sec(ttt % 60);
  int min((ttt / 60) % 60);
  int hr(ttt / 3600);
  stringstream foo;
  int didsome(0);
  if (_ttt < 0) foo << "-";
  if (hr) {
    foo << hr << ":";
    didsome++;
  }
  if (didsome || min){
    foo << setw(didsome?2:1) << setfill('0') << min << ":";
    didsome++;
  }
  foo << setw(didsome?2:1) << setfill('0') << sec;
  return foo.str();
}

string toLower(const string a){
  string rslt = a;
  string::iterator rr;
  for (rr = rslt.begin(); rr != rslt.end(); rr++){
    *rr = tolower(*rr);
  }
  return rslt;
}

string ltrim(const string foo, const string strip){
  size_t where = foo.find_first_not_of(strip);
  if (where == foo.npos) return foo;
  return foo.substr(where);
}

string rtrim(const string foo, const string strip){
  size_t where = foo.find_last_not_of(strip);
  if (where == foo.npos) return "";
  return foo.substr(0, where+1);
}

string trim(const string foo, const string bar){
  return ltrim(rtrim(foo, bar), bar);
}

static const string Pure_Enough("+-_.,@%~");

string purify(const string arg){
  using namespace std;
  string rslt(arg);
  for (string::iterator ptr = rslt.begin();
        ptr != rslt.end(); ptr++){
    char ch = *ptr;
    if (isalnum(ch)) continue;
    if (Pure_Enough.find(ch) != string::npos) continue;
    *ptr = '~';
  }
  return rslt;
}