File: kvu_utils.cpp

package info (click to toggle)
ecasound 2.9.3-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 6,292 kB
  • sloc: cpp: 39,475; sh: 4,335; lisp: 1,918; ansic: 1,883; makefile: 888; python: 617; ruby: 202
file content (688 lines) | stat: -rw-r--r-- 16,438 bytes parent folder | download | duplicates (2)
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
// ------------------------------------------------------------------------
// kvu_utils.cpp: Miscellaneous helper routines
// Copyright (C) 1999-2004,2009 Kai Vehmanen
//
// Attributes:
//     eca-style-version: 2
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
// ------------------------------------------------------------------------

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <algorithm> /* find() */
#include <cstdlib> /* atoi() */
#include <iostream>
#include <string>
#include <vector>

#if HAVE_LOCALE_H
#include <locale.h> /* setlocale */
#endif

#include <time.h> /* nanosleep() */
#include <sys/time.h> /* gettimeofday() */
#include <unistd.h> /* usleep() */
#include <ctype.h> /* isspace(), toupper() */

#include "kvu_dbc.h"
#include "kvu_utils.h"

using namespace std;

static string::const_iterator kvu_priv_find_next_instance(const string& arg, const string::const_iterator& curpos, const string::value_type value);
static void kvu_priv_strip_escapes(string* const input, const string& escaped_char);

/**
 * Returns a string where all regex metachars in 'arg'
 * have been quoted using a backslash.
 *
 * Reference: man regex(7)
 */
string kvu_string_regex_meta_escape(const string& arg)
{
  string result;

  /* regex metachar set: ^.[]$()|*+?{}\ */

  string::const_iterator p = arg.begin();
  while(p != arg.end()) {
    if (*p == '^') result += "\\^";
    else if (*p == '.') result += "\\.";
    else if (*p == '[') result += "\\[";
    else if (*p == ']') result += "\\]";
    else if (*p == '$') result += "\\$";
    else if (*p == '(') result += "\\(";
    else if (*p == ')') result += "\\)";
    else if (*p == '|') result += "\\|";
    else if (*p == '*') result += "\\*";
    else if (*p == '+') result += "\\+";
    else if (*p == '?') result += "\\?";
    else if (*p == '{') result += "\\{";
    else if (*p == '}') result += "\\}";
    else if (*p == '\\') result += "\\\\";
    else 
      result += *p;

    ++p;
  }

  return result;
}

/**
 * Returns a string where all meta characters in 'arg'
 * have been quoted using a backslash.
 *
 * Reference: man sh(1), man bash(1)
 */
string kvu_string_shell_meta_escape(const string& arg)
{
  string result;

  string::const_iterator p = arg.begin();
  while(p != arg.end()) {
    if (*p == '"') result += "\\\"";
    else if (*p == '\'') result += "\\\'";
    else if (*p == ' ') result += "\\ ";
    else if (*p == '|') result += "\\|";
    else if (*p == '&') result += "\\&";
    else if (*p == ';') result += "\\;";
    else if (*p == '(') result += "\\(";
    else if (*p == ')') result += "\\)";
    else if (*p == '<') result += "\\<";
    else if (*p == '>') result += "\\>";
    else 
      result += *p;

    ++p;
  }

  return result;
}

/**
 * Converts a string to a vector of strings (words).
 * Whitespace is used as the separator.
 *
 * Note! This function is obsolete, use @see string_to_tokens() 
 *       instead.
 */
vector<string> kvu_string_to_words(const string& s)
{
  return kvu_string_to_tokens(s);
}

/**
 * Converts a string to a vector of token strings.
 * Whitespace is used as the separator.
 */
vector<string> kvu_string_to_tokens(const string& s)
{
  vector<string> vec;
  string stmp = "";

  for(string::const_iterator p = s.begin(); p != s.end(); p++) {
    if (isspace(*p) == 0)
      stmp += *p;
    else {
      if (stmp == "") continue;
      vec.push_back(stmp);
      stmp = "";
    }
  }
  if (stmp.size() > 0)
    vec.push_back(stmp);

  return vec;
}

/**
 * Converts a string to a vector of token strings.
 * Whitespace is used as the token separator. 
 *
 * Unlike string_to_tokens(), quotes can be used to mark 
 * groups of words as tokens (e.g. "this is one token").
 * The tokens are not removed from the string. 
 * Single-quotes (') are not supported.
 *
 * It's also possible to add individual whitespace
 * characted by escaping them with a backclash (e.g.
 * 'this\ is\ one\ token\ '). Escaped characters are
 * not considered as possible separators.
 */
vector<string> kvu_string_to_tokens_quoted(const string& s)
{
  vector<string> vec;
  string stmp;
  bool quoteflag = false;

  for(string::const_iterator p = s.begin(); p != s.end(); p++) {
    if (*p == '\"') {
      quoteflag = !quoteflag;
      stmp += *p;
    }
    else if (*p == '\\') {
      p++;
      if (p == s.end()) break;
      stmp += *p;
    }
    else if (isspace(*p) == 0 || quoteflag == true) {
      stmp += *p;
    }
    else {
      /* note: token ready, add to vector if length is non-zero */
      if (stmp.size() == 0) continue;

      vec.push_back(stmp);
      stmp = "";
      DBC_CHECK(stmp.size() == 0);
    }
  }
  if (stmp.size() > 0)
    vec.push_back(stmp);

  return vec;
}

/**
 * Converts a string to a vector of strings.
 *
 * @param str string to be converted
 * @param separator character to be used for separating items
 */
vector<string> kvu_string_to_vector(const string& str, 
				    const string::value_type separator)
{
  vector<string> vec;
  string stmp = "";

  for(string::const_iterator p = str.begin(); p != str.end(); p++) {
    if (*p != separator)
      stmp += *p;
    else {
      if (stmp == "") continue;
      vec.push_back(stmp);
      stmp = "";
    }
  }
  if (stmp.size() > 0)
    vec.push_back(stmp);

  return vec;
}

/**
 * Converts a string to a vector of integers.
 *
 * @param str string to be converted
 * @param separator character to be used for separating items
 */
vector<int> kvu_string_to_int_vector(const string& str, 
				     const string::value_type separator)
{
  vector<int> vec;
  string stmp = "";

  for(string::const_iterator p = str.begin(); p != str.end(); p++) {
    if (*p != separator)
      stmp += *p;
    else {
      if (stmp == "") continue;
      vec.push_back(atoi(stmp.c_str()));
      stmp = "";
    }
  }
  if (stmp.size() > 0)
    vec.push_back(atoi(stmp.c_str()));

  return vec;
}

/**
 * Return a modified copy of vector 'str_vector' where 'from' has
 * been replaced with 'to' in all items.
 */
vector<string> kvu_vector_search_and_replace(const vector<string>& str_vector, 
					     const string& from,
					     const string& to)
{
  vector<string> vstmp;
  vector<string>::const_iterator p = str_vector.begin();
  while(p != str_vector.end()) {
    vstmp.push_back(kvu_string_search_and_replace(*p, from, to));
    ++p;
  }
  return vstmp;
}

/**
 * Converts a vector of strings to a single string.
 *
 * @param str vector of strings to be converted
 * @param separator string that is inserted between items
 */
string kvu_vector_to_string(const vector<string>& str, 
			    const string& separator)
{

  string stmp;

  vector<string>::const_iterator p = str.begin();
  while(p != str.end()) {
    stmp += *p;
    ++p;
    if (p != str.end()) 
      stmp += separator;
  }

  return stmp;
}

/**
 * Return a new string, where all 'from' characters are
 * replaced with 'to' characters.
 */
string kvu_string_search_and_replace(const string& str, 
				     const string::value_type from,
				     const string::value_type to)
{
  string stmp (str);
  for(vector<string>::size_type p = 0; p < str.size(); p++) {
    if (str[p] == from) stmp[p] = to;
    else stmp[p] = str[p];
  }

  return stmp;
}

/**
 * Return a new string, where all 'from' characters are
 * replaced with 'to' characters.
 */
string kvu_string_search_and_replace(const string& str, 
				     const string& from,
				     const string& to)
{
  string tmp (str);
  size_t pos = 0;
  while((pos = tmp.find(from, pos)) != string::npos) {
    tmp.replace(pos, from.size(), to);
    pos += (to.size() > from.size() ? to.size() : from.size());
  }
  return tmp;
}

/**
 * Case-insensitive string compare. Ignores preceding and 
 * trailing white space.
 */
bool kvu_string_icmp(const string& first, const string& second)
{
  string a = first;
  string b = second;

  a = kvu_remove_trailing_spaces(a);
  a = kvu_remove_preceding_spaces(a);
  a = kvu_convert_to_uppercase(a);

  b = kvu_remove_trailing_spaces(b);
  b = kvu_remove_preceding_spaces(b);
  b = kvu_convert_to_uppercase(b);

  return a == b;
}

/**
 * Removes all trailing white space
 */
string kvu_remove_trailing_spaces(const string& a)
{
  string r = "";
  string::const_reverse_iterator p;
  for(p = a.rbegin(); p != a.rend(); p++) {
    if (*p != ' ') break;
  }
  for(; p != a.rend(); p++) {
    r = *p + r;
  }
  return  r;
}

/**
 * Removes all preciding white space
 */
string kvu_remove_preceding_spaces(const string& a)
{
  string r = "";
  string::const_iterator p;
  for(p = a.begin(); p != a.end(); p++) {
    if (*p != ' ') break;
  }
  for(; p != a.end(); p++) {
    r += *p;
  }
  return r;
}

/**
 * Removes all surrounding white spaces
 */
string kvu_remove_surrounding_spaces(const string& a)
{
  string::const_iterator p,q;
  for(p = a.begin(); p != a.end() && *p == ' '; p++);
  for(q = (a.end() - 1); q != a.begin() && *q == ' '; q--);
  return string(p,q + 1);
}

/**
 * Converts string to uppercase using toupper(int)
 */
string kvu_convert_to_uppercase(const string& a)
{
  string r = a;
  for(string::iterator p = r.begin(); p != r.end(); p++)
    *p = toupper(*p);
  return r;
}

/**
 * Converts string to lowercase using tolower(int)
 */
string kvu_convert_to_lowercase(const string& a)
{ 
  string r = a;
  for(string::iterator p = r.begin(); p != r.end(); p++)
    *p = tolower(*p);
  return r;
}

/**
 * Converts string to uppercase using toupper(int)
 * Modifies the parameter object.
 */
void kvu_to_uppercase(string& a)
{
  string::iterator p = a.begin();
  while(p != a.end()) {
    *p = toupper(*p);
    ++p;
  }
}

/**
 * Converts string to lowercase using tolower(int)
 * Modifies the parameter object.
 */
void kvu_to_lowercase(string& a)
{
  string::iterator p = a.begin();
  while(p != a.end()) {
    *p = tolower(*p);
    ++p;
  }
}

/**
 * Finds the next instance of character 'value' and returns its
 * position.
 * 
 * All backslash escaped instances of 'value' ("\<value>")
 * are ignored in the search. Also instance of 'value' within 
 * a pair of double quotes are ignored.
 *
 * Note that general backlash escaping is not supported, i.e. 
 * "\<character>" is not interpreted as "<character>".
 *
 * @return position of next 'value' or arg.end() if not found
 */
static string::const_iterator kvu_priv_find_next_instance(const string& arg, const string::const_iterator& start, const string::value_type value)
{
  string::const_iterator curpos = start, ret = arg.end(), nextquote = arg.end();

  while(curpos != arg.end()) {
    ret = find(curpos, arg.end(), value);

    nextquote = find(curpos, arg.end(), '"'); 
    if (nextquote < ret) {

      /* step: ignore quoted part of the input string */
      nextquote = find(nextquote + 1, arg.end(), '"');
      if (nextquote != arg.end()) {
	curpos = nextquote + 1;
	ret = find(curpos, arg.end(), value);
      }
    }

    if (ret != arg.end() && ret != arg.begin()) {
      string::const_iterator prev = ret - 1;
      if ((*prev) == '\\') {
	curpos = ret + 1;
	continue;
      }
    }

    break;
  }

  return ret;
}

/**
 * Returns the nth argument from a formatted string
 *
 * @param number the argument number 
 * @param argu a formatted string: "something:arg1,arg2,...,argn"
 *
 * require:
 *  number >= 1
 */
string kvu_get_argument_number(int number, const string& arg)
{
  string result;
  vector<string> temp = kvu_get_arguments(arg);
  if (static_cast<int>(temp.size()) >= number) {
    result = temp[number - 1];
  }
  return result;
}

/**
 * Converts all backslash-commas into commas and returns
 * the result.
 *
 * @pre escaped_char.size() == 1
 */
static void kvu_priv_strip_escapes(string* const input, const string& escaped_char)
{
  size_t pos; 
  while((pos = input->find(string("\\") + escaped_char)) != string::npos) {
    input->replace(pos, 2, escaped_char);
  }
}

/**
 * Strips the outer quotes of type 'quote_char' from the string.
 * The string is only modified if the the string starts with,
 * and ends to, a character matching 'quote_char'.
 *
 * @pre escaped_char.size() == 1
 */
void kvu_string_strip_outer_quotes(string* input, const std::string::value_type quote_char)
{
  if (input->size() >= 2 &&
      *input->begin() == quote_char &&
      *(input->end() - 1) == quote_char)
    *input = std::string(input->begin() + 1, input->end() - 1);
}

/** 
 * Returns number of arguments in formatted string 'arg'.
 */
int kvu_get_number_of_arguments(const string& arg)
{
  return kvu_get_arguments(arg).size();
}

/**
 * Returns a vector of all arguments from a formatted string
 *
 * Note: forces locale to "POSIX" as decimal separate must be
 *       be period (.) in order to argument separation to work
 *
 * @param argu a formatted string: "something:arg1,arg2,...,argn"
 */
vector<string> kvu_get_arguments(const string& argu)
{
  vector<string> resvec;
  char* locale_save;
  string::const_iterator b = kvu_priv_find_next_instance(argu, argu.begin(), ':');
  string::const_iterator e;

  if (b == argu.end()) {
    if (argu.size() > 0) b = argu.begin();
    else return resvec;
  }
  else 
    ++b;

#if HAVE_SETLOCALE
  locale_save = setlocale (LC_NUMERIC, "POSIX");
#else
  locale_save = NULL;
#endif

  for(; b != argu.end();) {
    e = kvu_priv_find_next_instance(argu, b, ',');
    string target = string(b, e);

    /* strip backslash-commas (and leave the commas in place) */
    kvu_priv_strip_escapes(&target, ",");
    kvu_priv_strip_escapes(&target, ":");
    kvu_string_strip_outer_quotes(&target, '"');
    resvec.push_back(target);

    if (e == argu.end()) 
      break;

    b = e;
    ++b;
    
    /* special case in which last argument is empty */
    if (b == argu.end() &&
	*e == ',')
      resvec.push_back("");
  }

#if HAVE_SETLOCALE
  /* restore original locale */
  if (locale_save)
    setlocale (LC_NUMERIC, locale_save);
#endif

  return resvec;
}

/**
 * Get the prefix part of a string argument
 * @param argument format used is -prefix:arg1, arg2, ..., argN
 *
 * require:
 *   argu.find('-') != string::npos
 *
 * ensure:
 *   result.size() >= 0
 */
string kvu_get_argument_prefix(const string& argu)
{
  // --------
  DBC_REQUIRE(argu.find('-') != string::npos);
  // --------

  string::const_iterator b = find(argu.begin(), argu.end(), '-');
  string::const_iterator e = find(argu.begin(), argu.end(), ':');

  if (b != argu.end()) {
    ++b;
    if (b !=  argu.end()) {
      return string(b,e);
    }
  }

  return "";
}

/**
 * Prints a time stamp to stderr
 */
void kvu_print_time_stamp(void)
{
  // --
  // not thread-safe!
  // --
  static bool first = true;
  static struct timeval last;
  struct timeval current;

  if (first) {
    ::gettimeofday(&last, 0);
    first = false;
  }

  ::gettimeofday(&current, 0);

  cerr << "(timestamp) " << current.tv_sec << "sec, " <<
    current.tv_usec << "msec.";
  
  long delta = current.tv_usec;
  delta -= last.tv_usec;
  delta += (current.tv_sec - last.tv_sec) * 1000000;
  cerr << " Delta " << delta << "msec." << endl;

  last.tv_sec = current.tv_sec;
  last.tv_usec = current.tv_usec;
}

/**
 * Put the calling execution context to sleeps for 
 * 'seconds.nanosecods'.
 *
 * Note! If available, implemented using nanosleep().
 *
 * @return 0 on success, non-zero if sleep was 
 *         interrupted for some reason
 */
int kvu_sleep(long int seconds, long int nanoseconds)
{
  int ret = 0;
#if defined(HAVE_NANOSLEEP) && !defined(__CYGWIN__)
  struct timespec len;
  len.tv_sec = static_cast<time_t>(seconds);
  len.tv_nsec = nanoseconds;
  ret = ::nanosleep(&len, NULL);

#elif HAVE_USLEEP
  ret = ::usleep(seconds * 1000000 + nanoseconds / 1000);

#else
  cerr << "(libkvutils) kvutils:: warning! neither nanosleep() or usleep() found!" << endl;
  return -1;
#endif

  return ret;
}