Merge branch 'style-string-methods' into 'develop'

Style string methods

See merge request !136
This commit is contained in:
Mark Olesen 2017-08-02 16:28:42 +01:00
commit 8e4f015253
43 changed files with 379 additions and 378 deletions

View File

@ -40,7 +40,8 @@ using namespace Foam;
int main(void)
{
string st("sfdsf sdfs23df sdf32f . sdfsdff23/2sf32");
Info<< word(string::validate<word>(st)) << "END" << endl;
Info<<"string: " << st << nl;
Info<<"word: \"" << string::validate<word>(st) << "\"" << endl;
string st1("1234567");

View File

@ -84,7 +84,7 @@ int main(int argc, char *argv[])
for (const auto& s : { " text with \"spaces'", "08/15 value" })
{
Info<<"validated \"" << s << "\" => "
<< word::validated(s, true) << nl;
<< word::validate(s, true) << nl;
}
Info<< nl;

View File

@ -207,7 +207,7 @@ int main(int argc, char *argv[])
// #include "checkHasMovingMesh.H"
// #include "checkHasLagrangian.H"
IOobjectList objects(mesh, timeDirs[timeDirs.size()-1].name());
IOobjectList objects(mesh, timeDirs.last().name());
forAll(timeDirs, timeI)
{

View File

@ -488,7 +488,7 @@ mtype {space}"MTYPE:"{space}
<cellStreamTitle>{spaceNl}{word}{spaceNl} {
word streamName(Foam::string::validate<word>(YYText()));
const word streamName(word::validate(YYText()));
BEGIN(cellStreamFlags);
}

View File

@ -370,7 +370,7 @@ void readPhysNames(IFstream& inFile, Map<word>& physicalNames)
lineStr >> regionI >> regionName;
Info<< " " << regionI << '\t'
<< string::validate<word>(regionName) << endl;
<< word::validate(regionName) << endl;
}
else if (nSpaces == 2)
{
@ -380,21 +380,21 @@ void readPhysNames(IFstream& inFile, Map<word>& physicalNames)
if (physType == 1)
{
Info<< " " << "Line " << regionI << '\t'
<< string::validate<word>(regionName) << endl;
<< word::validate(regionName) << endl;
}
else if (physType == 2)
{
Info<< " " << "Surface " << regionI << '\t'
<< string::validate<word>(regionName) << endl;
<< word::validate(regionName) << endl;
}
else if (physType == 3)
{
Info<< " " << "Volume " << regionI << '\t'
<< string::validate<word>(regionName) << endl;
<< word::validate(regionName) << endl;
}
}
physicalNames.insert(regionI, string::validate<word>(regionName));
physicalNames.insert(regionI, word::validate(regionName));
}
inFile.getLine(line);

View File

@ -512,7 +512,7 @@ void readSets
>> dofSet >> tempSet >> contactSet >> nFaces;
is.getLine(line);
word groupName = string::validate<word>(line);
const word groupName = word::validate(line);
Info<< "For group " << group
<< " named " << groupName

View File

@ -598,10 +598,7 @@ int main(int argc, char *argv[])
// Pass2: reconstruct the cloud
forAllConstIter(HashTable<IOobjectList>, cloudObjects, iter)
{
const word cloudName = string::validate<word>
(
iter.key()
);
const word cloudName = word::validate(iter.key());
// Objects (on arbitrary processor)
const IOobjectList& sprayObjs = iter();

View File

@ -149,7 +149,7 @@ bool Foam::IOobject::fileNameComponents
// No '/' found (or empty entirely)
// => no instance or local
name = word::validated(path, false);
name = word::validate(path);
}
else if (first == 0)
{
@ -160,7 +160,7 @@ bool Foam::IOobject::fileNameComponents
const std::string ending = path.substr(last+1);
nameLen = ending.size(); // The raw length of name
name = word::validated(ending, false);
name = word::validate(ending);
}
else
{
@ -176,7 +176,7 @@ bool Foam::IOobject::fileNameComponents
const std::string ending = path.substr(last+1);
nameLen = ending.size(); // The raw length of name
name = word::validated(ending, false);
name = word::validate(ending);
}
// Check for valid (and stripped) name, regardless of the debug level

View File

@ -185,7 +185,7 @@ Foam::Ostream& Foam::UOPstream::write(const char c)
Foam::Ostream& Foam::UOPstream::write(const char* str)
{
word nonWhiteChars(string::validate<word>(str));
const word nonWhiteChars(string::validate<word>(str));
if (nonWhiteChars.size() == 1)
{

View File

@ -81,9 +81,9 @@ Foam::Ostream& Foam::OSstream::write(const string& str)
os_ << token::BEGIN_STRING;
int backslash = 0;
for (string::const_iterator iter = str.begin(); iter != str.end(); ++iter)
for (auto iter = str.cbegin(); iter != str.cend(); ++iter)
{
char c = *iter;
const char c = *iter;
if (c == '\\')
{
@ -132,14 +132,9 @@ Foam::Ostream& Foam::OSstream::writeQuoted
os_ << token::BEGIN_STRING;
int backslash = 0;
for
(
string::const_iterator iter = str.begin();
iter != str.end();
++iter
)
for (auto iter = str.cbegin(); iter != str.cend(); ++iter)
{
char c = *iter;
const char c = *iter;
if (c == '\\')
{

View File

@ -235,7 +235,7 @@ bool Foam::functionObjectList::readFunctionObject
{
args.append
(
string::validate<word>
word::validate
(
funcNameArgs.substr(start, i - start)
)
@ -255,7 +255,7 @@ bool Foam::functionObjectList::readFunctionObject
}
else if (c == '=')
{
argName = string::validate<word>
argName = word::validate
(
funcNameArgs.substr(start, i - start)
);
@ -330,7 +330,7 @@ bool Foam::functionObjectList::readFunctionObject
// Merge this functionObject dictionary into functionsDict
dictionary funcArgsDict;
funcArgsDict.add(string::validate<word>(funcNameArgs), funcDict);
funcArgsDict.add(word::validate(funcNameArgs), funcDict);
functionsDict.merge(funcArgsDict);
return true;

View File

@ -55,7 +55,7 @@ Foam::objectRegistry::objectRegistry
(
IOobject
(
string::validate<word>(t.caseName()),
word::validate(t.caseName()),
t.path(),
t,
IOobject::NO_READ,

View File

@ -53,13 +53,13 @@ class Ostream;
// * * * * * * * * * * * * * * * IOstream Operators * * * * * * * * * * * * //
//- Output wide character (Unicode) as UTF-8
Ostream& operator<<(Ostream&, const wchar_t);
Ostream& operator<<(Ostream& os, const wchar_t wc);
//- Output wide character (Unicode) string as UTF-8
Ostream& operator<<(Ostream&, const wchar_t*);
Ostream& operator<<(Ostream& os, const wchar_t* wstr);
//- Output wide character (Unicode) string as UTF-8
Ostream& operator<<(Ostream&, const std::wstring&);
Ostream& operator<<(Ostream& os, const std::wstring& wstr);
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //

View File

@ -116,12 +116,7 @@ Foam::Ostream& Foam::operator<<(Ostream& os, const wchar_t* wstr)
Foam::Ostream& Foam::operator<<(Ostream& os, const std::wstring& wstr)
{
for
(
std::wstring::const_iterator iter = wstr.begin();
iter != wstr.end();
++iter
)
for (auto iter = wstr.cbegin(); iter != wstr.cend(); ++iter)
{
os << *iter;
}

View File

@ -104,30 +104,26 @@ Foam::fileName& Foam::fileName::toAbsolute()
}
bool Foam::fileName::clean()
bool Foam::fileName::clean(std::string& str)
{
// The top slash - we are never allowed to go above it
string::size_type top = this->find('/');
// Start with the top slash found - we are never allowed to go above it
char prev = '/';
auto top = str.find(prev);
// No slashes - nothing to do
if (top == string::npos)
if (top == std::string::npos)
{
return false;
}
// Start with the '/' found:
char prev = '/';
string::size_type nChar = top+1;
string::size_type maxLen = this->size();
// Number of output characters
std::string::size_type nChar = top+1;
for
(
string::size_type src = nChar;
src < maxLen;
/*nil*/
)
const string::size_type maxLen = str.size();
for (string::size_type src = nChar; src < maxLen; /*nil*/)
{
char c = operator[](src++);
const char c = str[src++];
if (prev == '/')
{
@ -137,28 +133,27 @@ bool Foam::fileName::clean()
continue;
}
// Could be '/./' or '/../'
// Could be "/./", "/../" or a trailing "/."
if (c == '.')
{
// Found trailing '/.' - skip it
// Trailing "/." - skip it
if (src >= maxLen)
{
continue;
break;
}
// Peek at the next character
char c1 = operator[](src);
const char c1 = str[src];
// Found '/./' - skip it
// Found "/./" - skip it
if (c1 == '/')
{
src++;
++src;
continue;
}
// It is '/..' or '/../'
if (c1 == '.' && (src+1 >= maxLen || operator[](src+1) == '/'))
// Trailing "/.." or intermediate "/../"
if (c1 == '.' && (src+1 >= maxLen || str[src+1] == '/'))
{
string::size_type parent;
@ -168,7 +163,7 @@ bool Foam::fileName::clean()
if
(
nChar > 2
&& (parent = this->rfind('/', nChar-2)) != string::npos
&& (parent = str.rfind('/', nChar-2)) != string::npos
&& parent >= top
)
{
@ -184,47 +179,60 @@ bool Foam::fileName::clean()
}
}
}
operator[](nChar++) = prev = c;
str[nChar++] = prev = c;
}
// Remove trailing slash
if (nChar > 1 && operator[](nChar-1) == '/')
if (nChar > 1 && str[nChar-1] == '/')
{
nChar--;
}
this->resize(nChar);
str.resize(nChar);
return (nChar != maxLen);
}
bool Foam::fileName::clean()
{
return fileName::clean(*this);
}
Foam::fileName Foam::fileName::clean() const
{
fileName fName(*this);
fName.clean();
return fName;
fileName cleaned(*this);
fileName::clean(cleaned);
return cleaned;
}
std::string Foam::fileName::name(const std::string& str)
{
const auto beg = str.rfind('/');
if (beg == npos)
{
return str;
}
else
{
return str.substr(beg+1);
}
}
Foam::word Foam::fileName::name() const
{
const size_type i = rfind('/');
if (i == npos)
{
return *this;
}
else
{
return substr(i+1);
}
return fileName::name(*this);
}
Foam::word Foam::fileName::nameLessExt() const
std::string Foam::fileName::nameLessExt(const std::string& str)
{
size_type beg = rfind('/');
size_type beg = str.rfind('/');
size_type dot = str.rfind('.');
if (beg == npos)
{
@ -235,7 +243,6 @@ Foam::word Foam::fileName::nameLessExt() const
++beg;
}
size_type dot = rfind('.');
if (dot != npos && dot <= beg)
{
dot = npos;
@ -243,18 +250,24 @@ Foam::word Foam::fileName::nameLessExt() const
if (dot == npos)
{
return substr(beg, npos);
return str.substr(beg);
}
else
{
return substr(beg, dot - beg);
return str.substr(beg, dot - beg);
}
}
Foam::fileName Foam::fileName::path() const
Foam::word Foam::fileName::nameLessExt() const
{
const size_type i = rfind('/');
return nameLessExt(*this);
}
std::string Foam::fileName::path(const std::string& str)
{
const auto i = str.rfind('/');
if (i == npos)
{
@ -262,7 +275,7 @@ Foam::fileName Foam::fileName::path() const
}
else if (i)
{
return substr(0, i);
return str.substr(0, i);
}
else
{
@ -271,9 +284,15 @@ Foam::fileName Foam::fileName::path() const
}
Foam::fileName Foam::fileName::path() const
{
return path(*this);
}
Foam::fileName Foam::fileName::lessExt() const
{
const size_type i = find_ext();
const auto i = find_ext();
if (i == npos)
{
@ -330,7 +349,7 @@ Foam::wordList Foam::fileName::components(const char delimiter) const
// Avoid empty trailing element
if (beg < size())
{
wrdList.append(substr(beg, npos));
wrdList.append(substr(beg));
}
// Transfer to wordList

View File

@ -108,7 +108,7 @@ public:
inline fileName(const fileName& fn);
//- Construct as copy of word
inline fileName(const word& s);
inline fileName(const word& w);
//- Construct as copy of string
inline fileName(const string& s, const bool doStripInvalid=true);
@ -135,26 +135,42 @@ public:
//- Is this character valid for a fileName?
inline static bool valid(char c);
//- Cleanup file name
//- Cleanup filename
//
// * Removes repeated slashes
// Removes trailing \c /
// \verbatim
// / --> /
// /abc/ --> /abc
// \endverbatim
//
// Removes repeated slashes
// \verbatim
// /abc////def --> /abc/def
// \endverbatim
//
// * Removes '/./'
// /abc/def/./ghi/. --> /abc/def/./ghi
// Removes \c /./ (current directory)
// \verbatim
// /abc/def/./ghi/. --> /abc/def/ghi
// abc/def/./ --> abc/def
// ./abc/ --> ./abc
// \endverbatim
//
// * Removes '/../'
// Removes \c /../ (parent directory)
// \verbatim
// /abc/def/../ghi/jkl/nmo/.. --> /abc/ghi/jkl
// abc/../def/ghi/../jkl --> abc/../def/jkl
// \endverbatim
//
// * Removes trailing '/'
//
// \return True if any contents changed
// \return True if the content changed
static bool clean(std::string& str);
//- Cleanup filename inplace
// \return True if any contents changed
bool clean();
//- Cleanup file name
// eg, remove repeated slashes, etc.
//- Cleanup filename
// \return cleaned copy of fileName
fileName clean() const;
@ -164,6 +180,9 @@ public:
// LINK (only if followLink=false)
Type type(const bool followLink = true) const;
//- Return true if string starts with a '/'
inline static bool isAbsolute(const std::string& str);
//- Return true if file name is absolute (starts with a '/')
inline bool isAbsolute() const;
@ -174,19 +193,28 @@ public:
// Decomposition
//- Return basename (part beyond last /), including its extension
// The result normally coresponds to a Foam::word
//
// Behaviour compared to /usr/bin/basename:
// \verbatim
// input name() basename
// ----- ------ --------
// "foo" "foo" "foo"
// "/" "" "/"
// "/foo" "foo" "foo"
// "foo/bar" "bar" "bar"
// "/foo/bar" "bar" "bar"
// "/foo/bar/" "" "bar"
// \endverbatim
static std::string name(const std::string& str);
//- Return basename (part beyond last /), including its extension
word name() const;
//- Return basename, without extension
// The result normally coresponds to a Foam::word
static std::string nameLessExt(const std::string& str);
//- Return basename, without extension
word nameLessExt() const;
@ -199,17 +227,22 @@ public:
}
//- Return directory path name (part before last /)
// The result normally coresponds to a Foam::fileName
//
// Behaviour compared to /usr/bin/dirname:
// \verbatim
// input path() dirname
// ----- ------ -------
// "foo" "." "."
// "/" "/" "/"
// "/foo" "/" "foo"
// "foo/bar" "foo" "foo"
// "/foo/bar" "/foo" "/foo"
// "/foo/bar/" "/foo/bar/" "/foo"
// \endverbatim
static std::string path(const std::string& str);
//- Return directory path name (part before last /)
fileName path() const;
//- Return file name without extension (part before last .)
@ -242,11 +275,11 @@ public:
// \verbatim
// Input components()
// ----- ------
// "foo" 1("foo")
// "/foo" 1("foo")
// "foo/bar" 2("foo", "bar")
// "/foo/bar" 2("foo", "bar")
// "/foo/bar/" 2("foo", "bar")
// "foo" ("foo")
// "/foo" ("foo")
// "foo/bar" ("foo", "bar")
// "/foo/bar" ("foo", "bar")
// "/foo/bar/" ("foo", "bar")
// \endverbatim
wordList components(const char delimiter = '/') const;

View File

@ -3,7 +3,7 @@
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 2011 OpenFOAM Foundation
\\/ M anipulation | Copyright (C) 2016 OpenCFD Ltd.
\\/ M anipulation | Copyright (C) 2016-2017 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
@ -23,12 +23,13 @@ License
\*---------------------------------------------------------------------------*/
#include <iostream> // for std::cerr
// * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * //
inline void Foam::fileName::stripInvalid()
{
// skip stripping unless debug is active to avoid
// costly operations
// Skip stripping unless debug is active (to avoid costly operations)
if (debug && string::stripInvalid<fileName>(*this))
{
std::cerr
@ -115,6 +116,12 @@ inline bool Foam::fileName::valid(char c)
}
inline bool Foam::fileName::isAbsolute(const std::string& str)
{
return !str.empty() && str[0] == '/';
}
inline bool Foam::fileName::isAbsolute() const
{
return !empty() && operator[](0) == '/';

View File

@ -111,6 +111,11 @@ public:
// Member functions
//- Is this character valid for a keyType?
// This is largely identical with what word accepts, but also
// permit brace-brackets, which are valid for some regexs.
inline static bool valid(char c);
//- Treat as a pattern rather than a literal string?
inline bool isPattern() const;

View File

@ -23,6 +23,21 @@ License
\*---------------------------------------------------------------------------*/
// * * * * * * * * * * * * Static Member Functions * * * * * * * * * * * * * //
inline bool Foam::keyType::valid(char c)
{
return
(
!isspace(c)
&& c != '"' // string quote
&& c != '\'' // string quote
&& c != '/' // path separator
&& c != ';' // end statement
);
}
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
inline Foam::keyType::keyType()

View File

@ -46,8 +46,8 @@ inline Foam::CStringList::CStringList()
:
argc_(0),
len_(0),
argv_(0),
data_(0)
argv_(nullptr),
data_(nullptr)
{}
@ -69,12 +69,12 @@ inline void Foam::CStringList::clear()
if (data_)
{
delete[] data_;
data_ = 0;
data_ = nullptr;
}
if (argv_)
{
delete[] argv_;
argv_ = 0;
argv_ = nullptr;
}
}

View File

@ -33,8 +33,8 @@ Foam::CStringList::CStringList
:
argc_(0),
len_(0),
argv_(0),
data_(0)
argv_(nullptr),
data_(nullptr)
{
reset(input);
}
@ -50,42 +50,40 @@ void Foam::CStringList::reset
{
clear();
argc_ = input.size();
forAll(input, argI)
if (input.empty())
{
len_ += input[argI].size();
++len_; // nul terminator for C-strings
// Special handling of an empty list
argv_ = new char*[1];
argv_[0] = nullptr; // Final nullptr terminator
return;
}
argv_ = new char*[argc_+1];
argv_[argc_] = nullptr; // extra terminator
if (argc_ > 0)
// Count overall required string length, including each trailing nul char
for (const auto& str : input)
{
// allocation includes final nul terminator,
// but overall count does not
data_ = new char[len_--];
len_ += str.size() + 1;
}
char* ptr = data_;
forAll(input, argI)
argv_ = new char*[input.size()+1];
data_ = new char[len_];
--len_; // Do not include final nul terminator in overall count
argv_[argc_] = nullptr; // extra terminator
// Copy contents
char* ptr = data_;
for (const auto& str : input)
{
argv_[argc_++] = ptr; // The start of this string
for (auto iter = str.cbegin(); iter != str.cend(); ++iter)
{
argv_[argI] = ptr;
const std::string& str =
static_cast<const std::string&>(input[argI]);
for
(
std::string::const_iterator iter = str.begin();
iter != str.end();
++iter
)
{
*(ptr++) = *iter;
}
*(ptr++) = '\0';
*(ptr++) = *iter;
}
*(ptr++) = '\0';
}
argv_[argc_] = nullptr; // Final nullptr terminator
}

View File

@ -101,17 +101,17 @@ bool Foam::string::hasExt(const wordRe& ending) const
Foam::string::size_type Foam::string::count(const char c) const
{
size_type cCount = 0;
size_type nChar = 0;
for (const_iterator iter = cbegin(); iter != cend(); ++iter)
for (auto iter = cbegin(); iter != cend(); ++iter)
{
if (*iter == c)
{
++cCount;
++nChar;
}
}
return cCount;
return nChar;
}
@ -119,14 +119,14 @@ Foam::string& Foam::string::replace
(
const string& oldStr,
const string& newStr,
size_type start
const size_type start
)
{
size_type newStart = start;
size_type pos = start;
if ((newStart = find(oldStr, newStart)) != npos)
if ((pos = find(oldStr, pos)) != npos)
{
std::string::replace(newStart, oldStr.size(), newStr);
std::string::replace(pos, oldStr.size(), newStr);
}
return *this;
@ -137,17 +137,22 @@ Foam::string& Foam::string::replaceAll
(
const string& oldStr,
const string& newStr,
size_type start
const size_type start
)
{
if (oldStr.size())
{
size_type newStart = start;
const size_type lenOld = oldStr.size();
const size_type lenNew = newStr.size();
while ((newStart = find(oldStr, newStart)) != npos)
if (lenOld)
{
for
(
size_type pos = start;
(pos = find(oldStr, pos)) != npos;
pos += lenNew
)
{
std::string::replace(newStart, oldStr.size(), newStr);
newStart += newStr.size();
std::string::replace(pos, lenOld, newStr);
}
}
@ -168,19 +173,14 @@ bool Foam::string::removeRepeated(const char character)
if (character && find(character) != npos)
{
string::size_type nChar=0;
iterator iter2 = begin();
string::size_type nChar = 0;
iterator outIter = begin();
char prev = 0;
for
(
string::const_iterator iter1 = iter2;
iter1 != end();
iter1++
)
for (auto iter = cbegin(); iter != cend(); ++iter)
{
char c = *iter1;
const char c = *iter;
if (prev == c && c == character)
{
@ -188,11 +188,12 @@ bool Foam::string::removeRepeated(const char character)
}
else
{
*iter2 = prev = c;
++iter2;
*outIter = prev = c;
++outIter;
++nChar;
}
}
resize(nChar);
}
@ -210,16 +211,14 @@ Foam::string Foam::string::removeRepeated(const char character) const
bool Foam::string::removeTrailing(const char character)
{
bool changed = false;
string::size_type nChar = size();
const string::size_type nChar = size();
if (character && nChar > 1 && operator[](nChar-1) == character)
{
resize(nChar-1);
changed = true;
return true;
}
return changed;
return false;
}
@ -245,10 +244,8 @@ bool Foam::string::removeStart(const std::string& text)
this->erase(0, txtLen);
return true;
}
else
{
return false;
}
return false;
}
@ -266,10 +263,8 @@ bool Foam::string::removeEnd(const std::string& text)
this->resize(strLen - txtLen);
return true;
}
else
{
return false;
}
return false;
}

View File

@ -190,22 +190,22 @@ public:
//- Avoid masking the normal std::string replace
using std::string::replace;
//- Replace first occurence of sub-string oldStr with newStr
// starting at start
//- Replace first occurence of sub-string oldStr with newStr,
// beginning at start
string& replace
(
const string& oldStr,
const string& newStr,
size_type start = 0
const size_type start = 0
);
//- Replace all occurences of sub-string oldStr with newStr
// starting at start
//- Replace all occurences of sub-string oldStr with newStr,
// beginning at start. This is a no-op if oldStr is empty.
string& replaceAll
(
const string& oldStr,
const string& newStr,
size_type start = 0
const size_type start = 0
);
//- Expand initial tildes and all occurences of environment variables
@ -224,20 +224,23 @@ public:
// Foam::findEtcFile
string& expand(const bool allowEmpty = false);
//- Remove repeated characters returning true if string changed
//- Remove repeated characters
// \return True if string changed
bool removeRepeated(const char character);
//- Return string with repeated characters removed
string removeRepeated(const char character) const;
//- Remove trailing character returning true if string changed
//- Remove trailing character, unless string is a single character
// \return True if string changed
bool removeTrailing(const char character);
//- Return string with trailing character removed
//- Return string with trailing character removed,
// unless string is a single character
string removeTrailing(const char character) const;
//- Remove the given text from the start of the string.
// Always true if the removal occurred or the given text is empty.
// \return True if the removal occurred or the given text is empty.
bool removeStart(const std::string& text);
//- Remove the given text from the end of the string.

View File

@ -23,7 +23,6 @@ License
\*---------------------------------------------------------------------------*/
#include <iostream>
// * * * * * * * * * * * * Protected Member Functions * * * * * * * * * * * //
@ -76,21 +75,18 @@ inline Foam::string::string(const std::string& str)
{}
// Copy character array
inline Foam::string::string(const char* str)
:
std::string(str)
{}
// Construct from a given number of characters in a character array
inline Foam::string::string(const char* str, const size_type len)
:
std::string(str, len)
{}
// Construct from a single character
inline Foam::string::string(const char c)
:
std::string(1, c)
@ -102,13 +98,14 @@ inline Foam::string::string(const char c)
template<class String>
inline bool Foam::string::valid(const std::string& str)
{
for (const_iterator iter = str.begin(); iter != str.end(); ++iter)
for (auto iter = str.cbegin(); iter != str.cend(); ++iter)
{
if (!String::valid(*iter))
{
return false;
}
}
return true;
}
@ -118,27 +115,22 @@ inline bool Foam::string::stripInvalid(std::string& str)
{
if (!valid<String>(str))
{
size_type nValid = 0;
iterator iter2 = str.begin();
size_type nChar = 0;
iterator outIter = str.begin();
for
(
const_iterator iter1 = iter2;
iter1 != const_cast<const std::string&>(str).end();
iter1++
)
for (auto iter = str.cbegin(); iter != str.cend(); ++iter)
{
const char c = *iter1;
const char c = *iter;
if (String::valid(c))
{
*iter2 = c;
++iter2;
++nValid;
*outIter = c;
++outIter;
++nChar;
}
}
str.resize(nValid);
str.resize(nChar);
return true;
}
@ -151,7 +143,7 @@ template<class String>
inline bool Foam::string::meta(const std::string& str, const char quote)
{
int escaped = 0;
for (const_iterator iter = str.begin(); iter != str.end(); ++iter)
for (auto iter = str.cbegin(); iter != str.cend(); ++iter)
{
const char c = *iter;
if (quote && c == quote)
@ -181,10 +173,10 @@ Foam::string::quotemeta(const std::string& str, const char quote)
}
string sQuoted;
sQuoted.reserve(2*str.length());
sQuoted.reserve(2*str.size());
int escaped = 0;
for (const_iterator iter = str.begin(); iter != str.end(); ++iter)
for (auto iter = str.cbegin(); iter != str.cend(); ++iter)
{
const char c = *iter;
if (c == quote)
@ -203,7 +195,7 @@ Foam::string::quotemeta(const std::string& str, const char quote)
sQuoted += c;
}
sQuoted.resize(sQuoted.length());
sQuoted.resize(sQuoted.size());
return sQuoted;
}
@ -212,9 +204,22 @@ Foam::string::quotemeta(const std::string& str, const char quote)
template<class String>
inline String Foam::string::validate(const std::string& str)
{
string ss = str;
stripInvalid<String>(ss);
return ss;
String out;
out.resize(str.size());
size_type count = 0;
for (auto iter = str.cbegin(); iter != str.cend(); ++iter)
{
const char c = *iter;
if (String::valid(c))
{
out[count++] = c;
}
}
out.resize(count);
return out;
}
@ -257,4 +262,5 @@ inline unsigned Foam::string::hash::operator()
return Hasher(str.data(), str.size(), seed);
}
// ************************************************************************* //

View File

@ -123,12 +123,12 @@ Foam::string& Foam::stringOps::inplaceExpand
}
else
{
string::iterator iter = s.begin() + begVar + 1;
string::const_iterator iter = s.cbegin() + begVar + 1;
// more generous in accepting keywords than for env variables
while
(
iter != s.end()
iter != s.cend()
&&
(
std::isalnum(*iter)
@ -180,8 +180,7 @@ Foam::string& Foam::stringOps::inplaceExpand
}
HashTable<string, word, string::hash>::const_iterator fnd =
mapping.find(varName);
auto fnd = mapping.cfind(varName);
if (fnd.found())
{
@ -290,7 +289,9 @@ Foam::string Foam::stringOps::getVariable
string::size_type altPos = 0;
// check for parameter:-word or parameter:+word
int altType = findParameterAlternative(name, altPos, name.size()-1);
const int altType =
findParameterAlternative(name, altPos, name.size()-1);
if (altType)
{
value = getEnv
@ -414,13 +415,13 @@ Foam::string& Foam::stringOps::inplaceExpand
}
else
{
string::iterator iter = s.begin() + begVar + 1;
string::const_iterator iter = s.cbegin() + begVar + 1;
string::size_type endVar = begVar;
// more generous in accepting keywords than for env variables
while
(
iter != s.end()
iter != s.cend()
&&
(
std::isalnum(*iter)
@ -552,12 +553,12 @@ Foam::string& Foam::stringOps::inplaceExpand
}
else
{
string::iterator iter = s.begin() + begVar + 1;
string::const_iterator iter = s.cbegin() + begVar + 1;
// more generous in accepting keywords than for env variables
while
(
iter != s.end()
iter != s.cend()
&&
(
std::isalnum(*iter)
@ -700,11 +701,11 @@ Foam::string& Foam::stringOps::inplaceExpand
}
else
{
string::iterator iter = s.begin() + begVar + 1;
string::const_iterator iter = s.cbegin() + begVar + 1;
while
(
iter != s.end()
iter != s.cend()
&& (std::isalnum(*iter) || *iter == '_')
)
{

View File

@ -35,52 +35,28 @@ const Foam::word Foam::word::null;
// * * * * * * * * * * * * * Static Member Functions * * * * * * * * * * * * //
Foam::word Foam::word::validated(const std::string& s, const bool prefix)
Foam::word Foam::word::validate(const std::string& s, const bool prefix)
{
std::string::size_type count = 0;
bool extra = false;
word out;
out.resize(s.size() + (prefix ? 1 : 0));
// Count number of valid characters and detect if the first character
// happens to be a digit, which we'd like to avoid having since this
// will cause parse issues when read back later.
for (std::string::const_iterator it = s.cbegin(); it != s.cend(); ++it)
std::string::size_type count = 0;
// As per validate, but optionally detect if the first character
// is a digit, which we'd like to avoid having since this will
// cause parse issues when read back later.
for (auto iter = s.cbegin(); iter != s.cend(); ++iter)
{
const char c = *it;
const char c = *iter;
if (word::valid(c))
{
if (prefix && !count && isdigit(c))
if (!count && prefix && isdigit(c))
{
// First valid character was a digit - prefix with '_'
extra = true;
++count;
out[count++] = '_';
}
++count;
}
}
if (count == s.size() && !extra)
{
return word(s, false); // Already checked, can just return as word
}
word out;
out.resize(count);
count = 0;
// Copy valid content.
if (extra)
{
out[count++] = '_';
}
for (std::string::const_iterator it = s.cbegin(); it != s.cend(); ++it)
{
const char c = *it;
if (word::valid(c))
{
out[count++] = c;
}
}

View File

@ -64,6 +64,7 @@ class word
// Private Member Functions
//- Strip invalid characters from this word
// Trips an abort on invalid characters for debug 2 or greater
inline void stripInvalid();
@ -112,10 +113,10 @@ public:
//- Is this character valid for a word?
inline static bool valid(char c);
//- Construct a validated word, in which all invalid characters have
// been stripped out. Optionally prefix any leading digit
// with '_' to have words that work nicely as dictionary keywords.
static word validated(const std::string& s, const bool prefix=false);
//- Construct validated word (no invalid characters).
// Optionally prefix any leading digit with '_' to have words
// that work nicely as dictionary keywords.
static word validate(const std::string& s, const bool prefix=false);
// File-like functions

View File

@ -24,12 +24,13 @@ License
\*---------------------------------------------------------------------------*/
#include <cctype>
#include <iostream> // for std::cerr
// * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * //
inline void Foam::word::stripInvalid()
{
// skip stripping unless debug is active (to avoid costly operations)
// Skip stripping unless debug is active (to avoid costly operations)
if (debug && string::stripInvalid<word>(*this))
{
std::cerr

View File

@ -107,6 +107,11 @@ public:
//- Is this a meta character?
inline static bool meta(const char c);
//- Is this character valid for a wordRe?
// This is largely identical with what word accepts, but also
// permit brace-brackets, which are valid for some regexs.
inline static bool valid(char c);
//- Test string for regular expression meta characters
inline static bool isPattern(const std::string& str);

View File

@ -31,6 +31,12 @@ inline bool Foam::wordRe::meta(const char c)
}
inline bool Foam::wordRe::valid(char c)
{
return keyType::valid(c);
}
inline bool Foam::wordRe::isPattern(const std::string& str)
{
return string::meta<regExp>(str);

View File

@ -365,7 +365,7 @@ void Foam::ccm::reader::readProblemDescription_boundaryRegion
}
else
{
dict.add(opt, word::validated(str, true));
dict.add(opt, word::validate(str, true));
}
}
@ -407,7 +407,7 @@ void Foam::ccm::reader::readProblemDescription_boundaryRegion
if (!str.empty())
{
dict.add(opt, word::validated(str, true));
dict.add(opt, word::validate(str, true));
}
}
@ -472,7 +472,7 @@ void Foam::ccm::reader::readProblemDescription_cellTable
str = "zone_" + ::Foam::name(Id);
}
dict.add(opt, word::validated(str, true));
dict.add(opt, word::validate(str, true));
}
@ -484,7 +484,7 @@ void Foam::ccm::reader::readProblemDescription_cellTable
if (!str.empty())
{
dict.add(opt, word::validated(str, true));
dict.add(opt, word::validate(str, true));
}
}

View File

@ -155,7 +155,7 @@ void Foam::fileFormats::FIREMeshReader::readSelections(ISstream& is)
// index starting at 1
const label selId = ++nCellSelections;
cellTable_.setName(selId, word::validated(name, true));
cellTable_.setName(selId, word::validate(name, true));
cellTable_.setMaterial(selId, "fluid");
for (label i = 0; i < count; ++i)
@ -170,7 +170,7 @@ void Foam::fileFormats::FIREMeshReader::readSelections(ISstream& is)
// index starting at 0
const label selId = nFaceSelections++;
faceNames.append(word::validated(name, true));
faceNames.append(word::validate(name, true));
for (label i = 0; i < count; ++i)
{

View File

@ -243,7 +243,7 @@ endsolid {space}("endsolid"|"ENDSOLID")({some_space}{word})*
}
<readSolidName>{string} {
const word solidName(Foam::string::validate<word>(YYText()));
const word solidName(word::validate(YYText()));
auto iter = lookup_.cfind(solidName);
if (iter.found())

View File

@ -116,10 +116,9 @@ bool Foam::fileFormats::OBJedgeFormat::read(const fileName& filename)
{
string line = this->getLineNoComment(is);
// handle continuations
if (line.back() == '\\')
// Handle continuations
if (line.removeEnd("\\"))
{
line.resize(line.size()-1);
line += this->getLineNoComment(is);
}

View File

@ -121,10 +121,8 @@ bool Foam::fileFormats::AC3DsurfaceFormat<Face>::read
if (cmd == "name")
{
// name %s
string str = parse<string>(args);
string::stripInvalid<word>(str);
names[zoneI] = str;
const string str = parse<string>(args);
names[zoneI] = word::validate(str);
}
else if (cmd == "rot")
{

View File

@ -111,14 +111,8 @@ bool Foam::fileFormats::NASsurfaceFormat<Face>::read
string rawName;
is.getLine(rawName);
if (rawName.back() == '\r')
{
rawName.resize(rawName.size()-1);
}
rawName = rawName.substr(1);
string::stripInvalid<word>(rawName);
ansaName = rawName;
rawName.removeEnd("\r");
ansaName = word::validate(rawName.substr(1));
// Info<< "ANSA tag for NastranID:" << ansaId
// << " of type " << ansaType
@ -140,11 +134,9 @@ bool Foam::fileFormats::NASsurfaceFormat<Face>::read
string rawName;
lineStream >> rawName;
string::stripInvalid<word>(rawName);
word groupName(rawName);
const word groupName = word::validate(rawName);
nameLookup.insert(groupId, groupName);
// Info<< "group " << groupId << " => " << groupName << endl;
}

View File

@ -119,14 +119,9 @@ Foam::Ostream& Foam::OBJstream::writeQuoted
OFstream::write(token::BEGIN_STRING);
int backslash = 0;
for
(
std::string::const_iterator iter = str.begin();
iter != str.end();
++iter
)
for (auto iter = str.cbegin(); iter != str.cend(); ++iter)
{
char c = *iter;
const char c = *iter;
if (c == '\\')
{
@ -161,12 +156,7 @@ Foam::Ostream& Foam::OBJstream::writeQuoted
else
{
// output unquoted string, only advance line number on newline
for
(
std::string::const_iterator iter = str.begin();
iter != str.end();
++iter
)
for (auto iter = str.cbegin(); iter != str.cend(); ++iter)
{
writeAndCheck(*iter);
}

View File

@ -81,10 +81,9 @@ bool Foam::fileFormats::OBJsurfaceFormat<Face>::read
{
string line = this->getLineNoComment(is);
// handle continuations
if (line.back() == '\\')
// Handle continuations
if (line.removeEnd("\\"))
{
line.resize(line.size()-1);
line += this->getLineNoComment(is);
}

View File

@ -64,7 +64,7 @@ Foam::fileFormats::STARCDsurfaceFormatCore::readInpCellTable
if (ctnameRE.match(line, groups))
{
const label tableId = atoi(groups[0].c_str());
const word tableName = word::validated(groups[1], true);
const word tableName = word::validate(groups[1], true);
if (!tableName.empty())
{

View File

@ -86,12 +86,11 @@ bool Foam::fileFormats::TRIsurfaceFormatCore::read
{
string line = this->getLineNoComment(is);
// handle continuations ?
// if (line.back() == '\\')
// {
// line.resize(line.size()-1);
// line += this->getLineNoComment(is);
// }
// Handle continuations?
// if (line.removeEnd("\\"))
// {
// line += this->getLineNoComment(is);
// }
IStringStream lineStream(line);

View File

@ -152,10 +152,9 @@ bool triSurface::readNAS(const fileName& fName)
string nameString;
is.getLine(ansaName);
if (ansaName.back() == '\r')
{
ansaName.resize(ansaName.size()-1);
}
ansaName.removeEnd("\r"); // Possible CR-NL
ansaName = ansaName.substr(1);
// Info<< "ANSA tag for NastranID:" << ansaId
// << " of type " << ansaType
@ -178,8 +177,9 @@ bool triSurface::readNAS(const fileName& fName)
string rawName;
lineStream >> rawName;
groupToName.insert(groupId, string::validate<word>(rawName));
Info<< "group " << groupId << " => " << rawName << endl;
const word groupName = word::validate(rawName);
groupToName.insert(groupId, groupName);
Info<< "group " << groupId << " => " << groupName << endl;
}
@ -275,8 +275,9 @@ bool triSurface::readNAS(const fileName& fName)
readLabel(IStringStream(readNASToken(line, 8, linei))());
if (groupId == ansaId && ansaType == "PSHELL")
{
groupToName.insert(groupId, string::validate<word>(ansaName));
Info<< "group " << groupId << " => " << ansaName << endl;
const word groupName = word::validate(ansaName);
groupToName.insert(groupId, groupName);
Info<< "group " << groupId << " => " << groupName << endl;
}
}
else if (cmd == "GRID")

View File

@ -51,13 +51,10 @@ bool Foam::triSurface::readOBJ(const fileName& OBJfileName)
{
string line = getLineNoComment(OBJfile);
const label sz = line.size();
if (sz)
if (line.size())
{
if (line.back() == '\\')
if (line.removeEnd("\\"))
{
line.resize(sz-1);
line += getLineNoComment(OBJfile);
}

View File

@ -65,29 +65,6 @@ int yyFlexLexer::yywrap()
//! \endcond
Foam::string foamSpecieString(const char* YYText)
{
Foam::string specieString(YYText);
return specieString;
}
Foam::word foamName(const char* YYText)
{
Foam::string fn(YYText);
Foam::string::stripInvalid<Foam::word>(fn);
return fn;
}
Foam::word foamName(const Foam::string& s)
{
Foam::string fn(s);
Foam::string::stripInvalid<Foam::word>(fn);
return fn;
}
/* ------------------------------------------------------------------------- *\
------ cppLexer::yylex()
\* ------------------------------------------------------------------------- */
@ -344,7 +321,7 @@ bool finishReaction = false;
}
<readElements>{elementName} {
currentElementName = foamName(YYText());
currentElementName = word::validate(YYText());
correctElementName(currentElementName);
if (!elementIndices_.found(currentElementName))
@ -382,7 +359,7 @@ bool finishReaction = false;
}
<readSpecies>{specieName} {
const word specieName(foamName(foamSpecieString(YYText())));
const word specieName = word::validate(YYText());
if (specieName == "THERMO")
{
@ -437,7 +414,7 @@ bool finishReaction = false;
}
<readThermoSpecieName>{thermoSpecieName} {
string specieString(foamSpecieString(YYText()));
string specieString(YYText());
if (newFormat_)
{
specieString.replaceAll(" ", "_");
@ -474,7 +451,7 @@ bool finishReaction = false;
for (int i=0; i<4; i++)
{
word elementName(foamName(thermoFormula.substr(5*i, 2)));
word elementName = word::validate(thermoFormula.substr(5*i, 2));
label nAtoms = atoi(thermoFormula.substr(5*i + 2, 3).c_str());
if (elementName.size() && nAtoms)
@ -494,17 +471,9 @@ bool finishReaction = false;
switch (phaseChar)
{
case 'S':
speciePhase_.insert(currentSpecieName, solid);
break;
case 'L':
speciePhase_.insert(currentSpecieName, liquid);
break;
case 'G':
speciePhase_.insert(currentSpecieName, gas);
break;
case 'S': speciePhase_.insert(currentSpecieName, solid); break;
case 'L': speciePhase_.insert(currentSpecieName, liquid); break;
case 'G': speciePhase_.insert(currentSpecieName, gas); break;
}
BEGIN(readThermoTemps);
@ -526,7 +495,7 @@ bool finishReaction = false;
<readThermoFormula2>{thermoFormula2} {
const string thermoFormula(YYText());
word elementName(foamName(thermoFormula.substr(0, 2)));
word elementName = word::validate(thermoFormula.substr(0, 2));
const label nAtoms = atoi(thermoFormula.substr(2, 3).c_str());
if
@ -695,7 +664,7 @@ bool finishReaction = false;
<readReactionKeyword>{reactionKeyword} {
word keyword(foamName(YYText()));
const word keyword = word::validate(YYText());
HashTable<int>::iterator reactionKeywordIter
(
@ -807,7 +776,7 @@ bool finishReaction = false;
}
else
{
currentSpecieName = foamName(foamSpecieString(YYText()));
currentSpecieName = word::validate(YYText());
HashTable<label>::iterator specieIndexIter
(
@ -853,7 +822,7 @@ bool finishReaction = false;
<readReactionKeyword>{reactionKeywordSlash} {
word keyword(foamName(YYText()));
word keyword = word::validate(YYText());
HashTable<int>::iterator reactionKeywordIter
(
@ -1328,8 +1297,7 @@ bool finishReaction = false;
<readPDependentSpecie>{pDependentSpecie} {
const word rhsPDependentSpecieName = pDependentSpecieName;
pDependentSpecieName =
foamName(foamSpecieString(YYText()));
pDependentSpecieName = word::validate(YYText());
pDependentSpecieName.resize(pDependentSpecieName.size()-1);
if (rrType == thirdBodyArrhenius)
@ -1399,7 +1367,7 @@ bool finishReaction = false;
}
<readTdepSpecie>{specieName} {
word specieName(foamName(foamSpecieString(YYText())));
word specieName = word::validate(YYText());
FatalErrorInFunction
<< "Temperature-dependent reaction on line "
<< lineNo_ << "not yet supported"
@ -1408,8 +1376,7 @@ bool finishReaction = false;
}
<readReactionOrderSpecie>{specieName} {
currentSpecieName =
word(foamName(foamSpecieString(YYText())));
currentSpecieName = word::validate(YYText());
HashTable<label>::iterator specieIndexIter
(