StringHelpers.C 34.5 KB
Newer Older
hrchilds's avatar
hrchilds committed
1 2
/*****************************************************************************
*
bonnell's avatar
bonnell committed
3
* Copyright (c) 2000 - 2015, Lawrence Livermore National Security, LLC
hrchilds's avatar
hrchilds committed
4
* Produced at the Lawrence Livermore National Laboratory
brugger's avatar
 
brugger committed
5
* LLNL-CODE-442911
hrchilds's avatar
hrchilds committed
6 7
* All rights reserved.
*
brugger's avatar
 
brugger committed
8
* This file is  part of VisIt. For  details, see https://visit.llnl.gov/.  The
hrchilds's avatar
hrchilds committed
9 10 11 12 13 14 15 16 17 18
* full copyright notice is contained in the file COPYRIGHT located at the root
* of the VisIt distribution or at http://www.llnl.gov/visit/copyright.html.
*
* Redistribution  and  use  in  source  and  binary  forms,  with  or  without
* modification, are permitted provided that the following conditions are met:
*
*  - Redistributions of  source code must  retain the above  copyright notice,
*    this list of conditions and the disclaimer below.
*  - Redistributions in binary form must reproduce the above copyright notice,
*    this  list of  conditions  and  the  disclaimer (as noted below)  in  the
brugger's avatar
 
brugger committed
19 20 21
*    documentation and/or other materials provided with the distribution.
*  - Neither the name of  the LLNS/LLNL nor the names of  its contributors may
*    be used to endorse or promote products derived from this software without
hrchilds's avatar
hrchilds committed
22 23 24 25 26
*    specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT  HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR  IMPLIED WARRANTIES, INCLUDING,  BUT NOT  LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND  FITNESS FOR A PARTICULAR  PURPOSE
brugger's avatar
 
brugger committed
27 28 29
* ARE  DISCLAIMED. IN  NO EVENT  SHALL LAWRENCE  LIVERMORE NATIONAL  SECURITY,
* LLC, THE  U.S.  DEPARTMENT OF  ENERGY  OR  CONTRIBUTORS BE  LIABLE  FOR  ANY
* DIRECT,  INDIRECT,   INCIDENTAL,   SPECIAL,   EXEMPLARY,  OR   CONSEQUENTIAL
hrchilds's avatar
hrchilds committed
30 31 32 33 34 35 36 37
* DAMAGES (INCLUDING, BUT NOT  LIMITED TO, PROCUREMENT OF  SUBSTITUTE GOODS OR
* SERVICES; LOSS OF  USE, DATA, OR PROFITS; OR  BUSINESS INTERRUPTION) HOWEVER
* CAUSED  AND  ON  ANY  THEORY  OF  LIABILITY,  WHETHER  IN  CONTRACT,  STRICT
* LIABILITY, OR TORT  (INCLUDING NEGLIGENCE OR OTHERWISE)  ARISING IN ANY  WAY
* OUT OF THE  USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*****************************************************************************/

hrchilds's avatar
hrchilds committed
38 39
#include <StringHelpers.h>

40
#include <errno.h>
hrchilds's avatar
hrchilds committed
41
#include <sys/types.h>
42
#include <stdarg.h>
hrchilds's avatar
hrchilds committed
43 44 45
#if defined(_WIN32)
#include <win32-regex.h>
#else
hrchilds's avatar
hrchilds committed
46
#include <regex.h>
hrchilds's avatar
hrchilds committed
47
#endif
hrchilds's avatar
hrchilds committed
48
#include <stdlib.h>
49
#include <algorithm>
50
#include <map>
hrchilds's avatar
hrchilds committed
51
#include <string>
52
#include <cstring>
fogal1's avatar
fogal1 committed
53
#include <sstream>
hrchilds's avatar
hrchilds committed
54 55
#include <vector>

56
#include <visit-config.h>
57
#include <FileFunctions.h>
58

59
using std::map;
hrchilds's avatar
hrchilds committed
60 61 62
using std::string;
using std::vector;

hrchilds's avatar
hrchilds committed
63
static string IGNORE_CHARS = StringHelpers::NON_RELEVANT_CHARS;
hrchilds's avatar
hrchilds committed
64

65 66
bool has_nonspace_chars(const std::string &s);

67 68 69 70 71 72
#if defined(_WIN32) || defined(__APPLE__)

#define MACCESS(...)

#else

camp's avatar
camp committed
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
#include <stdint.h>    // uintptr_t
#include <stdio.h>
#include <unistd.h>     // getpid...

extern int etext;

#define MAXRNGS 100

static struct rng { uintptr_t alpha, omega; } rngv[MAXRNGS], *rend = NULL;

void maccess_init()
{
    uintptr_t       brk = (uintptr_t)sbrk(0);
    char            buf[99];
    sprintf(buf, "/proc/%d/maps", getpid());
    FILE            *fp = fopen(buf, "re");
    rend = rngv;
90
    while (0 < fscanf(fp, "%lx-%lx %4s %*[^\n]",
camp's avatar
camp committed
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
                          &rend->alpha, &rend->omega, buf)) {
        if (buf[1] == '-' || rend->alpha < brk)
            continue;
        else if (rend > rngv && rend->alpha == rend[-1].omega)
            rend[-1].omega = rend->omega;
        else if (++rend == rngv+MAXRNGS)
            break;
    }
    fclose(fp);
}

// On my home system, "sbrk(0)" takes about .015 usec.
int maccess(void const *mem, int len)
{
    if ((intptr_t)mem < 0 && (intptr_t)mem + len >= 0)
        return 0;
    if ((char const*)mem + len < (char const*)sbrk(0))
        return mem > (void*)&etext;
    if (!rend)
        maccess_init();
    struct rng *p;
    for (p = rngv; p != rend; ++p)
        if ((uintptr_t)mem + len <= p->omega)
            return (uintptr_t)mem >= p->alpha;
    return 0;
}

118 119 120
#define MACCESS(curArgTypeName, num) if( maccess(curArgTypeName, num) == 0 ) break;

#endif
camp's avatar
camp committed
121

122
// ****************************************************************************
123
//  Function: RelevantString
124 125 126 127
//
//  Purpose: Return a string containing only the relevant characters of the
//  input string. Relevant characters are those NOT in IGNORE_CHARS
//
128
//  Programmer: Mark C. Miller
129 130 131
//  Creation:   Unknown
//
// ****************************************************************************
hrchilds's avatar
hrchilds committed
132 133 134 135 136 137 138 139
string RelevantString(string inStr)
{
   string outStr;
   string::size_type n;

   n = inStr.find_first_not_of(IGNORE_CHARS);
   while (n != string::npos)
   {
140
       outStr += inStr[n];
hrchilds's avatar
hrchilds committed
141 142 143 144 145 146
       n = inStr.find_first_not_of(IGNORE_CHARS, n+1);
   }

   return outStr;
}

147 148 149
// ****************************************************************************
//  Function: CompareRelevantStrings
//
150
//  Purpose: Compare two strings using only their relevant characters
151
//
152
//  Programmer: Mark C. Miller
153 154 155 156
//  Creation:   Unknown
//
// ****************************************************************************

hrchilds's avatar
hrchilds committed
157 158 159 160 161 162 163
static int CompareRelevantStrings(const void *arg1, const void *arg2)
{
    string str1 = RelevantString(*((char **) arg1));
    string str2 = RelevantString(*((char **) arg2));
    return strcmp(str1.c_str(),str2.c_str());
}

164
// ****************************************************************************
165
//  Function: GroupStrings
166 167 168
//
//  Purpose: Groups a list of strings by finding identical leading substrings
//  of length numLeadingVals.
hrchilds's avatar
hrchilds committed
169
//
170
//  Programmer: Mark C. Miller
171
//  Creation:   Unknown
hrchilds's avatar
hrchilds committed
172
//
173
// ****************************************************************************
hrchilds's avatar
hrchilds committed
174 175 176
void
StringHelpers::GroupStrings(vector<string> stringList,
                            vector<vector<string> > &stringGroups,
hrchilds's avatar
hrchilds committed
177 178 179
                            vector<string> &groupNames,
                            int numLeadingVals,
                            string nonRelevantChars)
hrchilds's avatar
hrchilds committed
180 181 182 183 184
{

   int i;
   int nStrings = stringList.size();

hrchilds's avatar
hrchilds committed
185 186 187
   if (nStrings == 0)
       return;

hrchilds's avatar
hrchilds committed
188 189 190
   // prime the input to the compare functions
   IGNORE_CHARS = nonRelevantChars;

hrchilds's avatar
hrchilds committed
191 192 193 194 195 196 197 198 199 200
   // first, we need to sort the strings. Well, we don't really sort the
   // strings. Instead we sort an array of pointers to the strings. We
   // build that array here.
   const char **stringPtrs = new const char*[nStrings];
   for (i = 0; i < nStrings; i++)
       stringPtrs[i] = stringList[i].c_str();

   // now, call qsort for this array of string pointers
   qsort(stringPtrs, nStrings, sizeof(char *), CompareRelevantStrings);

201
   // adjust numLeadingVals if its too big
hrchilds's avatar
hrchilds committed
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
   int len = strlen(stringPtrs[0]);
   if (numLeadingVals < 0)
   {
       if (-numLeadingVals > len)
           numLeadingVals  = -len;
   }
   else
   {
       if (numLeadingVals > len)
           numLeadingVals  = len;
   }


   // initialize the 'lastVal' for the loop below
   string lastVal;
   if (numLeadingVals < 0)
   {
       for (i = len+numLeadingVals; i < len; i++)
           lastVal += stringPtrs[0][i];
   }
   else
   {
       if (numLeadingVals == 0)
           lastVal = stringPtrs[0];
       else
       {
           for (i = 0; i < numLeadingVals; i++)
               lastVal += stringPtrs[0][i];
       }
   }

hrchilds's avatar
hrchilds committed
233
   //
hrchilds's avatar
hrchilds committed
234
   // now, scan the sorted list of strings for value transitions
hrchilds's avatar
hrchilds committed
235
   // in first N (default 3) chars. Each such transition indicates the end of
hrchilds's avatar
hrchilds committed
236 237
   // one group and the beginning of the next.
   //
hrchilds's avatar
hrchilds committed
238 239 240 241 242 243
   groupNames.push_back(RelevantString(stringPtrs[0]));
   vector<string> curGroup;
   curGroup.push_back(stringPtrs[0]);
   for (i = 1; i < nStrings; i++)
   {
       string thisVal;
hrchilds's avatar
hrchilds committed
244
       int j;
hrchilds's avatar
hrchilds committed
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261

       if (numLeadingVals < 0)
       {
           int len = stringList[i].size()-1;
           for (j = len+numLeadingVals; j < len; j++)
               lastVal += stringPtrs[i][j];
       }
       else
       {
           if (numLeadingVals == 0)
               thisVal = stringPtrs[i];
           else
           {
               for (j = 0; j < numLeadingVals; j++)
                   thisVal += stringPtrs[i][j];
           }
       }
hrchilds's avatar
hrchilds committed
262 263 264 265 266 267

       if (thisVal != lastVal)
       {
           lastVal = thisVal;
           groupNames.push_back(RelevantString(stringPtrs[i]));
           stringGroups.push_back(curGroup);
hrchilds's avatar
hrchilds committed
268 269 270 271 272 273 274 275 276 277 278 279 280
           curGroup.clear();
           curGroup.push_back(stringPtrs[i]);
       }
       else
       {
           curGroup.push_back(stringPtrs[i]);
       }
   }
   stringGroups.push_back(curGroup);

   delete [] stringPtrs;
}

281 282 283 284 285
// ****************************************************************************
//  Function: GroupStringsAsPaths
//
//  Purpose: Groups a list of strings that look like file paths into groups
//  that have same dirname
hrchilds's avatar
hrchilds committed
286
//
287
//  Programmer: Mark C. Miller
288
//  Creation:   Unknown
hrchilds's avatar
hrchilds committed
289
//
290
// ****************************************************************************
hrchilds's avatar
hrchilds committed
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
void
StringHelpers::GroupStringsAsPaths(vector<string> stringList,
                            vector<vector<string> > &stringGroups,
                            vector<string> &groupNames)
{

   int i;
   int nStrings = stringList.size();

   if (nStrings == 0)
       return;

   // prime the input to the compare functions
   IGNORE_CHARS = "`~!@#$%^&*()|\\\"'?";

   // first, we need to sort the strings. Well, we don't really sort the
   // strings. Instead we sort an array of pointers to the strings. We
   // build that array here.
   const char **stringPtrs = new const char*[nStrings];
   for (i = 0; i < nStrings; i++)
       stringPtrs[i] = stringList[i].c_str();

   // now, call qsort for this array of string pointers
   qsort(stringPtrs, nStrings, sizeof(char *), CompareRelevantStrings);

   // now, scan the sorted list of strings for value transitions
   // in the Dirname of each member
318
   string lastVal = FileFunctions::Dirname(stringPtrs[0]);
hrchilds's avatar
hrchilds committed
319 320 321 322 323
   groupNames.push_back(lastVal);
   vector<string> curGroup;
   curGroup.push_back(stringPtrs[0]);
   for (i = 1; i < nStrings; i++)
   {
324
       string thisVal = FileFunctions::Dirname(stringPtrs[i]);
hrchilds's avatar
hrchilds committed
325 326 327 328 329 330

       if (thisVal != lastVal)
       {
           lastVal = thisVal;
           groupNames.push_back(RelevantString(thisVal));
           stringGroups.push_back(curGroup);
hrchilds's avatar
hrchilds committed
331 332 333 334 335 336 337 338 339 340 341 342
           curGroup.clear();
           curGroup.push_back(stringPtrs[i]);
       }
       else
       {
           curGroup.push_back(stringPtrs[i]);
       }
   }
   stringGroups.push_back(curGroup);

   delete [] stringPtrs;
}
hrchilds's avatar
hrchilds committed
343

hrchilds's avatar
hrchilds committed
344

345 346
// ****************************************************************************
//  Function: GroupStringsAsFixedAlpha
hrchilds's avatar
hrchilds committed
347
//
348 349
//  Purpose: Groups a list of strings into a fixed number of groups
//  by alphabetizing and then dividing the alphabetized list into pieces
hrchilds's avatar
hrchilds committed
350
//
351
//  Programmer: Brad Whitlock
352 353 354
//  Creation:   Unknown
//
// ****************************************************************************
hrchilds's avatar
hrchilds committed
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
void
StringHelpers::GroupStringsFixedAlpha(vector<string> stringList,
                            int numGroups,
                            vector<vector<string> > &stringGroups)
{

   int i;
   int nStrings = stringList.size();

   if (nStrings == 0)
       return;

   // prime the input to the compare functions
   IGNORE_CHARS = "";

   // first, we need to sort the strings. Well, we don't really sort the
   // strings. Instead we sort an array of pointers to the strings. We
   // build that array here.
   const char **stringPtrs = new const char*[nStrings];
   for (i = 0; i < nStrings; i++)
       stringPtrs[i] = stringList[i].c_str();

   // now, call qsort for this array of string pointers
   qsort(stringPtrs, nStrings, sizeof(char *), CompareRelevantStrings);

   int groupSize = nStrings / numGroups;
   if (nStrings % numGroups)
       groupSize++;
   for (i = 0; i < nStrings; i++)
   {
       int groupNum = i / groupSize;
       int groupIdx = i % groupSize;

       if (groupIdx == 0)
       {
           vector<string> newGroup;
           stringGroups.push_back(newGroup);
       }
       stringGroups[groupNum].push_back(stringPtrs[i]);
    }
}

397 398 399 400 401 402 403 404 405 406
// ****************************************************************************
//  Function: GroupStringsAsFixedAlpha
//
//  Purpose: Groups a list of strings into a fixed number of groups
//  by alphabetizing and then dividing the alphabetized list into pieces
//
//  This version does not need to sort the strings since they are already
//  sorted because they're in a set. The sort rule for the set is the same
//  as that for the other GroupStringsFixedAlpha because IGNORE_CHARS gets
//  set to "", which means use the entire string in comparisons.
hrchilds's avatar
hrchilds committed
407
//
408
//  Programmer: Brad Whitlock
409
//  Creation:   Unknown
hrchilds's avatar
hrchilds committed
410
//
411
// ****************************************************************************
hrchilds's avatar
hrchilds committed
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
void
StringHelpers::GroupStringsFixedAlpha(
    const std::set<std::string> &stringList,
    int groupSize, std::vector<std::set<std::string> > &stringGroups)
{
    int nStrings = stringList.size();

    if (nStrings == 0)
        return;

    int i = 0;
    stringGroups.reserve(stringList.size() / groupSize);
    for(std::set<std::string>::const_iterator it = stringList.begin();
        it != stringList.end(); ++it, ++i)
    {
        int groupNum = i / groupSize;
        int groupIdx = i % groupSize;

        if (groupIdx == 0)
        {
            std::set<std::string> newGroup;
            stringGroups.push_back(newGroup);
        }
        stringGroups[groupNum].insert(*it);
    }
}

439
// ****************************************************************************
440
//  Function: FindRE
441 442 443 444
//
//  Purpose: Find match of a regular expression in a given string. Return the
//  starting offset into the string where the match occured.
//
445
//  Programmer: Mark C. Miller
446 447
//  Creation:   Unknown
//
448 449 450 451
//  Modifications:
//
//    Mark C. Miller, Wed Aug 26 11:16:31 PDT 2009
//    Made version with string args.
452 453 454
//
//    Mark C. Miller, Mon Aug 31 14:37:23 PDT 2009
//    Made string version use const references.
455
// ****************************************************************************
456 457

int
458
StringHelpers::FindRE(const string &s, const string &re)
459 460 461
{
    return StringHelpers::FindRE(s.c_str(), re.c_str());
}
hrchilds's avatar
hrchilds committed
462 463 464 465 466 467 468 469 470 471 472
int
StringHelpers::FindRE(const char *strToSearch, const char *re)
{
    regex_t cre;
    regmatch_t pm;

    if (regcomp(&cre, re, REG_EXTENDED))
        return FindError;

    int rval = regexec(&cre, strToSearch, 1, &pm, 0);

hrchilds's avatar
hrchilds committed
473 474
    regfree(&cre);

hrchilds's avatar
hrchilds committed
475 476 477
    if (rval == REG_NOMATCH)
        return FindNone;

478
    if (pm.rm_so >= (int)strlen(strToSearch))
hrchilds's avatar
hrchilds committed
479 480 481 482 483 484 485
        return FindError;

    if (pm.rm_so < 0)
        return FindError;

    return (int) pm.rm_so;
}
hrchilds's avatar
hrchilds committed
486

487
// ****************************************************************************
488
//  Function: ReplaceRE
489
//
490
//  Purpose: Replace portion of string matching RE with replacement string
491
//
492 493
//  Programmer: Mark C. Miller
//  Creation:   August 17, 2009
494
//
495 496 497
//  Modifications:
//    Mark C. Miller, Mon Aug 31 14:37:45 PDT 2009
//    Made it use const (where possible) references to strings.
498 499
// ****************************************************************************
bool
500
StringHelpers::ReplaceRE(string &s, const string &re, const string &repl)
501 502 503 504 505 506 507 508 509
{
    int n = FindRE(s, re);
    if (n < 0)
        return false;

    string news = string(s,0,n) + repl;
    s = news;
    return true;
}
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

// ****************************************************************************
//  Function: Replace
//
//  Purpose: Simple string replace helper.
//
//  Programmer: Cyrus Harrison
//  Creation:   Wed Mar 17 13:00:43 PDT 2010
//
//
//  Modifications:
//
// ****************************************************************************

string
StringHelpers::Replace(const string &source,
                       const string &before,
                       const string &after)
{
    string res = source;
    string::size_type before_len = before.size();
    string::size_type after_len  = after.size();
    if(before_len == 0)
        return res;
    string::size_type pos = 0; // Must initialize
    while ( ( pos = res.find (before,pos) ) != string::npos )
    {
        res.replace(pos,before_len,after);
        pos += after_len;
    }

    return res;
}

545
// ****************************************************************************
546
//  Function: ExtractRESubstr
547
//
548
//  Purpose: Extract the (sub)string matched by the regular expression.
549
//
550 551 552 553 554 555
//  The format of RE string passed here is an opening '<' followed by the
//  actual regular expression string followed by a closing '>', optionally
//  followed by a ' ' (space) and a backslashed substring reference. For
//  example, to extract the cycle digits from strings looking like
//  'run_23_0010_yana.silo' where '0010' is the cycle digits, the string to
//   pass here would look like...
556 557
//
//                                               V--substring reference
558
//                      "<.*_([0-9]{4})_.*\\..*> \0"
559 560 561 562 563
//          opening char-^                     ^--closing char
//                        ^------RE part------^
//
//  Do a 'man 7 regex' to get more information on regular expression syntax
//
564 565 566 567
//  Note: The substring reference implemented here is a zero-origin index.
//  That is NOT consistent with 'man 7 regex' which uses a one-origin index.
//  We should probably update this logic to use one-origin index.
//
568 569
//  Programmer: Mark C. Miller
//  Creation:   June 12, 2007
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
//
// ****************************************************************************
std::string
StringHelpers::ExtractRESubstr(const char *strToSearch, const char *re)
{
    regex_t cre;
    regmatch_t pm[255];
    string reToUse;
    string retval = "";

    //
    // extract actual RE from VisIt's required format ('<RE> \i')
    //
    int len = strlen(re);
    int matchToExtract;
    if (re[0] != '<')
        return retval;
587
    const char *last = strrchr(re, '>');
588 589 590 591 592 593 594 595 596 597
    if (last == 0)
        return retval;
    if (*(last+1) == '\0')
    {
        reToUse = string(re, 1, len-2);
        matchToExtract = 0;
    }
    else if (*(last+1) == ' ' && *(last+2) == '\\')
    {
        reToUse = string(re, 1, (last-re+1)-2); // -2 for '<' and '>' chars
miller86's avatar
miller86 committed
598
        errno = 0;
599
        matchToExtract = strtol(last+3, 0, 10);
ahern's avatar
ahern committed
600 601
        if (errno != 0)
            return retval;
602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
    }
    else
    {
        return retval;
    }

    if (regcomp(&cre, reToUse.c_str(), REG_EXTENDED))
        return retval;

    int rval = regexec(&cre, strToSearch, 255, pm, 0);

    regfree(&cre);

    if (rval == REG_NOMATCH)
        return retval;

    for (int i = 0; i < 255; i++)
    {
        if (pm[i].rm_so == -1)
ahern's avatar
ahern committed
621 622 623 624 625 626
            continue;
        if (i == matchToExtract)
        {
            retval = std::string(strToSearch, pm[i].rm_so,
                                              pm[i].rm_eo - pm[i].rm_so);
            break;
627 628 629 630 631
        }
    }
    return retval;
}

632 633 634 635 636 637 638 639
// ****************************************************************************
//  Function: InitTypeNameToFmtREMap
//
//  Purpose: Support routine to build map of regular expressions for different
//  data type names.
//
//  Do a 'man 7 regex' for information on format of the regular expression.
//
640 641
//  Programmer: Mark C. Miller
//  Creation:   September 20, 2007
642
//
643 644 645 646
//  Modifications:
//    Mark C. Miller, Fri Sep 21 20:26:18 PDT 2007
//    Fixed bug(s) in RE's allowing bad width/precision flags
//
647 648 649 650 651 652 653
// ****************************************************************************
static map<string,string> typeNameToFmtREMap;
static void InitTypeNameToFmtREMap()
{
    if (typeNameToFmtREMap.size())
        return;

miller86's avatar
miller86 committed
654 655 656 657 658 659 660 661 662 663 664
    typeNameToFmtREMap["float"]                   = "[^%]*%#?0?-? ?\\+?'?(([1-9][0-9]*)?(\\.[0-9]*)?)?[eEfFgGaA]{1}";
    typeNameToFmtREMap["double"]                  = "[^%]*%#?0?-? ?\\+?'?(([1-9][0-9]*)?(\\.[0-9]*)?)?[eEfFgGaA]{1}";
    typeNameToFmtREMap["long double"]             = "[^%]*%#?0?-? ?\\+?'?(([1-9][0-9]*)?(\\.[0-9]*)?)?L[eEfFgGaA]{1}";
    typeNameToFmtREMap["int"]                     = "[^%]*%#?0?-? ?\\+?'?I?(([1-9][0-9]*)?(\\.[0-9]*)?)?[di]{1}";
    typeNameToFmtREMap["long int"]                = "[^%]*%#?0?-? ?\\+?'?I?(([1-9][0-9]*)?(\\.[0-9]*)?)?l[di]{1}";
    typeNameToFmtREMap["long long int"]           = "[^%]*%#?0?-? ?\\+?'?I?(([1-9][0-9]*)?(\\.[0-9]*)?)?ll[di]{1}";
    typeNameToFmtREMap["unsigned int"]            = "[^%]*%#?0?-? ?\\+?'?I?(([1-9][0-9]*)?(\\.[0-9]*)?)?[ouxX]{1}";
    typeNameToFmtREMap["unsigned long int"]       = "[^%]*%#?0?-? ?\\+?'?I?(([1-9][0-9]*)?(\\.[0-9]*)?)?l[ouxX]{1}";
    typeNameToFmtREMap["unsigned long long int"]  = "[^%]*%#?0?-? ?\\+?'?I?(([1-9][0-9]*)?(\\.[0-9]*)?)?ll[ouxX]{1}";
    typeNameToFmtREMap["short int"]               = "[^%]*%#?0?-? ?\\+?'?I?(([1-9][0-9]*)?(\\.[0-9]*)?)?h[di]{1}";
    typeNameToFmtREMap["unsigned short int"]      = "[^%]*%#?0?-? ?\\+?'?I?(([1-9][0-9]*)?(\\.[0-9]*)?)?h[ouxX]{1}";
665
    typeNameToFmtREMap["char"]                    = "[^%]*%c{1}";
miller86's avatar
miller86 committed
666 667
    typeNameToFmtREMap["unsigned char"]           = "[^%]*%#?0?-? ?\\+?'?I?(([1-9][0-9]*)?(\\.[0-9]*)?)?hh[ouxX]{1}";
    typeNameToFmtREMap["char*"]                   = "[^%]*%#?0?-? ?\\+?'?I?(([1-9][0-9]*)?(\\.[0-9]*)?)?s{1}";
668
    typeNameToFmtREMap["void*"]                   = "[^%]*%p{1}";
miller86's avatar
miller86 committed
669
    typeNameToFmtREMap["size_t"]                  = "[^%]*%#?0?-? ?\\+?'?I?(([1-9][0-9]*)?(\\.[0-9]*)?)?z[ouxX]{1}";
670 671

    // aliases
672 673 674 675 676 677
    typeNameToFmtREMap["long"]                    = typeNameToFmtREMap["long int"];
    typeNameToFmtREMap["long long"]               = typeNameToFmtREMap["long long int"];
    typeNameToFmtREMap["unsigned"]                = typeNameToFmtREMap["unsigned int"];
    typeNameToFmtREMap["unsigned long"]           = typeNameToFmtREMap["unsigned long int"];
    typeNameToFmtREMap["unsigned long long"]      = typeNameToFmtREMap["unsigned long long int"];
    typeNameToFmtREMap["short"]                   = typeNameToFmtREMap["short int"];
678 679 680 681 682 683 684
    typeNameToFmtREMap["unsigned short"]          = typeNameToFmtREMap["unsigned short int"];
}

// ****************************************************************************
//  Function: ValidatePrintfFormatString
//
//  Purpose: Validates a printf style format string against a variable length
685
//  list of argument type names.
686
//
687 688
//  Programmer: Mark C. Miller
//  Creation:   September 20, 2007
689
//
miller86's avatar
miller86 committed
690 691 692
//  Modifications:
//    Mark C. Miller, Fri Sep 21 07:31:02 PDT 2007
//    Fixed end anchor to be any chars not a '%'
693 694 695 696
//
//    Mark C. Miller, Wed Dec  5 17:53:06 PST 2007
//    Fixed issue with missing REG_EXTENDED on Mac by adding check for simple
//    case and falling back to REs for more complicated cases.
697 698 699 700
// ****************************************************************************
bool
StringHelpers::ValidatePrintfFormatString(const char *fmtStr, const char *arg1Type, ... )
{
701
    int n;
702
    int i;
703

704 705 706 707 708
    //
    // fall back to RE based validation
    //
    string re = "^"; // anchor first char to beginning of line

709
    // compute length up to max of 4096
710
    n = 0;
711 712 713 714 715 716 717
    while (n < 4096 && fmtStr[n] != '\0')
        n++;
    if (n == 4096)
        return false;

    // count conversion specs.
    int ncspecs = 0;
718
    for (i = 0; i < n-1; i++)
719 720
    {
        if (fmtStr[i] == '%' && fmtStr[i+1] != '%')
ahern's avatar
ahern committed
721
            ncspecs++;
722 723 724 725
    }
    if (ncspecs == 0)
        return true;

726 727 728 729 730
    InitTypeNameToFmtREMap();

    // start processing the varargs list
    va_list ap;
    va_start(ap, arg1Type);
731
    const char *currentArgTypeName = arg1Type;
732
    // loop adding RE terms for each argument type
733
    for (i = 0; i < ncspecs; i++)
734
    {
735
        //MACCESS(currentArgTypeName, 1);
ahern's avatar
ahern committed
736 737
        if (typeNameToFmtREMap.find(string(currentArgTypeName)) == typeNameToFmtREMap.end())
            break;
738
        re += typeNameToFmtREMap[string(currentArgTypeName)];
ahern's avatar
ahern committed
739
        currentArgTypeName = va_arg(ap, const char *);
740 741 742
    }
    va_end(ap);

743 744 745 746
    // if we broke out of loop early, a bad type name was encountered
    if (i < ncspecs)
        return false;

miller86's avatar
miller86 committed
747
    re += "[^%]*$"; // anchor last char to end of line
748 749 750

    return StringHelpers::FindRE(fmtStr, re.c_str()) >= 0;
}
751 752 753 754

// ****************************************************************************
//  Function: car
//
755
//  Purpose: Pulls the first word out of a delimited string.
756 757 758 759
//
//  Programmer: Tom Fogal
//  Creation:   August 5, 2008
//
760 761 762 763 764
//  Modifications:
//
//    Tom Fogal, Wed Nov  4 17:14:29 MST 2009
//    Take an argument to use as the separating character.
//
765 766
// ****************************************************************************
std::string
767
StringHelpers::car(const std::string s, const char separator)
768
{
769 770
    if(s.find(separator) != std::string::npos) {
        return s.substr(0, s.find(separator));
771 772 773 774 775 776 777
    }
    return s;
}

// ****************************************************************************
//  Function: cdr
//
778
//  Purpose: Removes the first word from a delimited string.
779 780 781 782
//
//  Programmer: Tom Fogal
//  Creation:   August 5, 2008
//
783 784 785 786 787
//  Modifications:
//
//    Tom Fogal, Wed Nov  4 17:14:29 MST 2009
//    Take an argument to use as the separating character.
//
788 789
// ****************************************************************************
std::string
790
StringHelpers::cdr(const std::string s, const char separator)
791
{
792 793 794
    std::string::size_type sep;
    if((sep = s.find(separator)) != std::string::npos) {
        return s.substr(sep+1);
795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
    }
    return s;
}


//****************************************************************************
//  Function: has_nonspace_chars
//
//  Purpose: Predicate to determine if a string has any useful content.
//
//  Programmer: Tom Fogal
//  Creation:   August 20, 2008
//
//  Modifications:
//
//****************************************************************************
bool
has_nonspace_chars(const std::string &s)
{
    std::string::const_iterator iter = s.begin();

    while(iter != s.end())
    {
        if(!isspace(*iter))
        {
            return true;
        }
    }
    return false;
}

// ****************************************************************************
//  Function: append
//
//  Purpose: Append all elements from one vector to another.
//
//  Programmer: Tom Fogal
//  Creation:   August 5, 2008
//
//  Modifications:
//
//    Tom Fogal, Thu Aug  7 16:39:39 EDT 2008
//    Remove/ignore empty strings.
//
// ****************************************************************************
void
StringHelpers::append(std::vector<std::string> &argv,
                      std::vector<std::string> lst)
{
    if(lst.empty()) { return; }

    if(has_nonspace_chars(lst.front()))
    {
        argv.push_back(lst.front());
    }
    lst.erase(lst.begin());
    append(argv, lst);
}
853

fogal1's avatar
fogal1 committed
854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880
// ****************************************************************************
//  Function: split
//
//  Purpose: Splits a string based on a delimiter
//
//  Programmer: Tom Fogal
//  Creation:   December 7, 2009
//
//  Modifications:
//
// ****************************************************************************
std::vector<std::string>
StringHelpers::split(const std::string input, const char separator)
{
    std::istringstream iss(input);
    std::string cur;
    std::vector<std::string> retval;
    while(std::getline(iss, cur, separator))
    {
        if(iss)
        {
            retval.push_back(cur);
        }
    }
    return retval;
}

881 882 883
// ****************************************************************************
//  Function: Plural (and support structures)
//
884
//  Purpose: Given singular english noun, compute plural form
885
//
886 887
//  Programmer: Mark C. Miller
//  Creation:   August 17, 2009
888 889 890 891 892 893 894 895
//
//  Notes: The regular expression table below is by no means complete in that
//  it covers all nouns in the english language. However, it does cover most
//  of those likely to be used in VisIt (for names of set for example). It was
//  compiled and re-coded for C++ after reading several sources on the web
//  including http://www.csse.monash.edu.au/~damian/papers/HTML/Plurals.html
//  and http://www.emacswiki.org/emacs/plural.el
//
896 897 898 899
//  Modifications:
//
//    Mark C. Miller, Mon Aug 31 14:38:18 PDT 2009
//    Made function arg a reference.
900 901 902 903 904
//
//    Jeremy Meredith, Tue Mar 29 14:38:02 EDT 2011
//    Added a new flavor of this function which only pluralizes if
//    a passed integer is greater than one.
//
905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
// ****************************************************************************
typedef struct _plural_rule_t {
    const char *re;
    const char *repl;
} plural_rule_t;

static const plural_rule_t plural_rules_table[] = {
    {"ss$", "sses"},
    {"zz$", "zzes"},
    {"sh$", "shes"},
    {"tch$", "tches"},
    {"eaf$", "eaves"},
    {"ief$", "ieves"},
    {"roof$", "roofs"},
    {"ife$", "ives"},
    {"lf$", "lves"},
    {"ay$", "ays"},
    {"ey$", "eys"},
    {"iy$", "iys"},
    {"oy$", "oys"},
    {"uy$", "uys"},
    {"ndum$", "nda"},
    {"um$", "a"},
    {"schema$", "schemas"},
    {"ia$", "ium"},
    {"ma$", "mata"},
    {"na$", "nae"},
    {"ta$", "tum"},
    {"atlas$", "atlases"},
    {"aircraft$", "aircraft"},
    {"alga$", "algae"},
    {"alumna$", "alumnae"},
    {"automaton$", "automata"},
    {"corpus$", "corpora"},
    {"cs$", "csen"},
    {"foot$", "feet"},
    {"formula$", "formulae"},
    {"rion$", "ria"},
    {"focus$", "foci"},
    {"genus$", "genera"},
    {"hedron$", "hedra"},
    {"index$", "indices"},
    {"ouse$", "ice"},
    {"man$", "men"},
    {"matrix$", "matrices"},
    {"nucleus$", "nuclei"},
    {"offspring", "offspring"},
    {"phenomenon$", "phenomena"},
    {"people$", "people"},
    {"perch$", "perch"},
    {"piano$", "pianos"},
    {"police$", "police"},
    {"portico$", "porticos"},
    {"quarto$", "quartos"},
    {"radius$", "radii"},
    {"solo$", "solos"},
    {"syllabus$", "syllabi"},
    {"terminus$", "termini"},
    {"ulus$", "uli"},
    {"tooth$", "teeth"},
    {"uterus$", "uteri"},
    {"virtuoso", "virtuosi"},
    {"viscus$", "viscera"},
    {"is$", "es"},
    {"us$", "uses"},
    {"io$", "ios"},
    {"oo$", "oos"},
    {"o$", "oes"},
    {"y$", "ies"},
    {"ex$", "ices"},
    {"ix$", "ices"},
    {"x$", "xes"}
};
static const int NPluralRules = sizeof(plural_rules_table) / sizeof(plural_rules_table[0]);

string
981
StringHelpers::Plural(const string &s)
982 983 984 985 986 987 988 989 990 991
{
    string ps = s;
    for (int n = 0; n < NPluralRules; n++)
    {
        if (ReplaceRE(ps, plural_rules_table[n].re, plural_rules_table[n].repl))
            return ps;
    }
    // We have no other choice but to simply try adding 's'
    return ps + "s";
}
992

993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
string
StringHelpers::Plural(int n, const std::string &s)
{
    if (n == 1)
        return s;
    else
        return Plural(s);
}

// ****************************************************************************
// Method:  StringHelpers::HumanReadableList
//
// Purpose:
//   Turns a vector of strings into a comma-delimited single string
//   appropriate for insertion into a paragraph of text.
//
// Arguments:
//   sv         the string vector to turn into a single comma-delimited string
//
// Programmer:  Jeremy Meredith
// Creation:    March 29, 2011
//
// ****************************************************************************
string
StringHelpers::HumanReadableList(const std::vector<std::string> &sv)
{
    int n = sv.size();
    string s;
    for (int i=0; i<n; i++)
    {
        if (i > 0 && i == n-1)
            s += ", and "; // to serial comma, or not to serial comma?
        else if (i > 0)
            s += ", ";
        s += sv[i];
    }
    return s;
}

1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053

// ****************************************************************************
// Method:  StringHelpers::IsPureASCII
//
// Purpose:
//   Check to see if a string is purely ASCII printable characters.
//
// Arguments:
//   txt        the string data
//   length     the maximum number of bytes to check
//
// Programmer:  Jeremy Meredith
// Creation:    January  7, 2010
//
// ****************************************************************************
bool
StringHelpers::IsPureASCII(const std::string &txt)
{
    return IsPureASCII(txt.c_str(), txt.length());
}

bool
bonnell's avatar
bonnell committed
1054
StringHelpers::IsPureASCII(const char *const txt, size_t length)
1055
{
bonnell's avatar
bonnell committed
1056
    for (size_t i=0; i<length; i++)
1057
    {
1058
        const unsigned char c = txt[i];
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069

        if ((c>1 && c<7) || (c>13 && c<32) || c>127)
            return false;

        // if it is an ascii string, don't check past its terminator
        if (c==0)
            break;
    }
    return true;
}

1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
// ****************************************************************************
// Method:  StringHelpers::CaseInsenstiveEqual
//
// Purpose:
//   Check to see two strings compare as equal, after result of ::tolower.
//
// Arguments:
//   str_a, str_b   Input strings.
//
// Programmer:  Cyrus Harrison
// Creation:    Mon Sep 19 16:23:05 PDT 2011
//
// ****************************************************************************
bool
StringHelpers::CaseInsenstiveEqual(const std::string &str_a,
                                   const std::string &str_b)
{
    std::string sa_l = str_a;
    std::string sb_l = str_b;
    std::transform(sa_l.begin(),sa_l.end(),sa_l.begin(),::tolower);
    std::transform(sb_l.begin(),sb_l.end(),sb_l.begin(),::tolower);
    return sa_l == sb_l;
}
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157

// ****************************************************************************
// Method:  StringHelpers::rtrim
//
// Purpose:
//  Trim whitespace off the right of a string.
//
//
// Programmer:  Cyrus Harrison
// Creation:   Tue Mar 12 12:07:21 PDT 2013
//
// ****************************************************************************
void
StringHelpers::rtrim(string &val)
{
    // trim trailing spaces & tabs
    size_t pos = val.find_last_not_of(" \t");
    if( string::npos != pos)
    {
        val = val.substr( 0, pos+1 );
    }
}


// ****************************************************************************
// Method:  StringHelpers::ltrim
//
// Purpose:
//  Trim whitespace off the left of a string.
//
//
// Programmer:  Cyrus Harrison
// Creation:   Tue Mar 12 12:07:21 PDT 2013
//
// ****************************************************************************
void
StringHelpers::ltrim(string &val)
{
    // trim leading spaces & tabs
    size_t pos = val.find_first_not_of(" \t");
    if( string::npos != pos )
    {
        val = val.substr( pos );
    }
}


// ****************************************************************************
// Method:  StringHelpers::trim
//
// Purpose:
//  Trim whitespace off the left and right of a string.
//
// Programmer:  Cyrus Harrison
// Creation:   Tue Mar 12 12:07:21 PDT 2013
//
// ****************************************************************************

void
StringHelpers::trim(string &val)
{
    rtrim(val);
    ltrim(val);
}

1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
// ****************************************************************************
// Method: StringHelpers::UpperCase
//
// Purpose:
//   Make the string all upper case.
//
// Arguments:
//   src : The source string.
//
// Returns:    An upper case string.
//
// Note:       
//
// Programmer: Brad Whitlock
// Creation:   Mon Sep  8 14:42:48 PDT 2014
//
// Modifications:
//
// ****************************************************************************
1177

1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
std::string
StringHelpers::UpperCase(const std::string &src)
{
    std::string tmp(src);
    for(size_t i = 0; i < tmp.size(); ++i)
    {
        if(tmp[i] >= 'a' && tmp[i] <= 'z')
            tmp[i] -= 'a' - 'A';
    }
    return tmp;
}
1189