Merge branch 'update-stringIO-and-containers' into 'develop'

updates for resizing containers, reduced overhead for std::string output etc

See merge request Development/openfoam!632
This commit is contained in:
Andrew Heather
2023-10-11 18:12:09 +00:00
192 changed files with 2823 additions and 1995 deletions

View File

@ -34,7 +34,6 @@ Description
#include "argList.H"
#include "ListOps.H"
#include "CircularBuffer.H"
#include "StringStream.H"
#include "FlatOutput.H"
using namespace Foam;
@ -79,7 +78,7 @@ int main(int argc, char *argv[])
Info<< buf1[-12] << nl;
Info<< "found: " << buf1.found(40) << nl;
Info<< "contains: " << buf1.contains(40) << nl;
buf1.push_uniq(100); report(buf1);
buf1 = Zero; report(buf1);

View File

@ -6,7 +6,7 @@
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2011-2016 OpenFOAM Foundation
Copyright (C) 2022 OpenCFD Ltd.
Copyright (C) 2022-2023 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
@ -35,7 +35,7 @@ Description
#include "CompactListList.H"
#include "IndirectList.H"
#include "IOstreams.H"
#include "StringStream.H"
#include "SpanStream.H"
#include "faceList.H"
using namespace Foam;
@ -126,20 +126,20 @@ int main(int argc, char *argv[])
{
// IO
OStringStream ostr;
OCharStream ostr;
ostr << cll4;
IStringStream istr(ostr.str());
ISpanStream istr(ostr.view());
CompactListList<label> cll5(istr);
Info<< "cll5 = " << cll5 << endl;
}
{
// IO
cll4.clear();
OStringStream ostr;
OCharStream ostr;
ostr << cll4;
IStringStream istr(ostr.str());
ISpanStream istr(ostr.view());
CompactListList<label> cll5(istr);
Info<< "cll5 = " << cll5 << endl;
}

View File

@ -76,10 +76,10 @@ Foam::List<StringType> Foam::DirLister::csorted
const bool prune
) const
{
List<StringType> list(list<StringType>(pred, prune));
Foam::sort(list, stringOps::natural_sort());
List<StringType> result(list<StringType>(pred, prune));
Foam::sort(result, stringOps::natural_sort());
return list;
return result;
}

View File

@ -248,7 +248,7 @@ int main(int argc, char *argv[])
addr.emplace_back(2);
// Can also use the return value
Info<< "adding " << addr.emplace_back(4) << endl;
Info<< "adding " << addr.emplace_back(4) << nl;
forAll(dlE2, i)
{
@ -325,7 +325,7 @@ int main(int argc, char *argv[])
input1 = list2;
Info<< nl << "test subset/remove with "
Info<< nl << "test remove with "
<< flatOutput(input1) << endl;
for
@ -344,11 +344,35 @@ int main(int argc, char *argv[])
list2 = input1;
list1.remove(range);
list2.subset(range);
Info<< "input = " << flatOutput(input1) << nl
<< "remove " << range << " = " << flatOutput(list1) << nl
<< "subset " << range << " = " << flatOutput(list2) << nl;
<< "remove " << range << " = " << flatOutput(list1) << nl;
}
{
input1 = identity(5);
list1 = identity(4, 5);
list1.reserve(10);
Info<< nl << "test swap(List)" << nl;
Info<< " input: " << input1.size()
<< '/' << input1.capacity() << ' '
<< flatOutput(input1) << nl;
Info<< " list: " << list1.size() << '/'
<< list1.capacity() << ' '
<< flatOutput(list1) << nl;
// input1.swap(list1); // This is wrong!
list1.swap(input1); // Correct
Info<< "after swap:" << nl;
Info<< " input: " << input1.size()
<< '/' << input1.capacity() << ' '
<< flatOutput(input1) << nl;
Info<< " list: " << list1.size() << '/'
<< list1.capacity() << ' '
<< flatOutput(list1) << nl;
}
}

View File

@ -5,7 +5,7 @@
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2021-2022 OpenCFD Ltd.
Copyright (C) 2021-2023 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
@ -33,7 +33,6 @@ Description
#include "IOstreams.H"
#include "ITstream.H"
#include "OTstream.H"
#include "StringStream.H"
#include "FlatOutput.H"
#include "ListOps.H"
#include "labelRange.H"
@ -144,6 +143,29 @@ int main(int argc, char *argv[])
list1.setCapacity(3);
printInfo("", list1);
std::fill_n(std::back_inserter(list1), 10, 5);
Info<< "back_inserter to fill some values" << nl;
printInfo("", list1);
// Not very efficient, but just test for capability
DynamicList<label, 64> list2;
list2.resize(5);
ListOps::identity(list2);
Info<< "initial list" << nl;
printInfo("", list2);
labelRange range(10, 5);
std::copy(range.begin(), range.end(), std::back_inserter(list2));
Info<< "back_inserter to append some values" << nl;
printInfo("", list2);
range.reset(0, 4);
std::copy_n(range.begin(), range.size(), std::back_inserter(list2));
Info<< "back_inserter to append more values" << nl;
printInfo("", list2);
}
Info<< "\nEnd\n";

View File

@ -211,22 +211,6 @@ int main(int argc, char *argv[])
<< " hash:" << Hash<FixedList<label, 4>>()(list2) << nl;
// Test deprecated form
SLList<label> sllist3;
{
sllist3.push_back(0);
sllist3.push_back(1);
sllist3.push_back(2);
sllist3.push_back(3);
}
FixedList<label, 4> list3(sllist3);
Info<< "list3:" << list3 << nl;
// Test deprecated forms
list3 = array2;
list2 = sllist3;
// Using FixedList for content too
{
List<FixedList<label, 4>> twolists{list1, list2};

View File

@ -6,7 +6,7 @@
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2011-2016 OpenFOAM Foundation
Copyright (C) 2017-2022 OpenCFD Ltd.
Copyright (C) 2017-2023 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
@ -31,7 +31,7 @@ License
#include "DynamicList.H"
#include "FlatOutput.H"
#include "IOstreams.H"
#include "StringStream.H"
#include "SpanStream.H"
#include "ListOps.H"
#include "stringListOps.H"
@ -119,9 +119,9 @@ int main()
<< table1["aaa"] << nl;
{
OStringStream os;
OCharStream os;
os << table1;
HashTable<scalar> readTable(IStringStream(os.str())(), 100);
HashTable<scalar> readTable(ISpanStream(os.view())());
Info<< "Istream constructor:" << readTable << endl;
}

View File

@ -37,12 +37,28 @@ Description
using namespace Foam;
Ostream& writeList(Ostream& os, const UList<char>& list)
Ostream& printString(Ostream& os, const char* first, const char* last)
{
os << '"';
for (; first != last; (void)++first)
{
os << *first;
}
os << '"';
return os;
}
Ostream& printView(Ostream& os, const char* first, const char* last)
{
char buf[4];
os << list.size() << '(';
for (const char c : list)
os << label(last-first) << '(';
for (; first != last; (void)++first)
{
const char c = *first;
if (isprint(c))
{
os << c;
@ -67,16 +83,35 @@ Ostream& writeList(Ostream& os, const UList<char>& list)
}
#if __cplusplus >= 201703L
Ostream& printView(Ostream& os, std::string_view s)
{
return printView(os, s.begin(), s.end());
}
#endif
Ostream& printView(Ostream& os, stdFoam::span<char> s)
{
return printView(os, s.begin(), s.end());
}
Ostream& printView(Ostream& os, const UList<char>& list)
{
return printView(os, list.begin(), list.end());
}
Ostream& writeList(Ostream& os, const UList<char>& list)
{
return printView(os, list.begin(), list.end());
}
Ostream& toString(Ostream& os, const UList<char>& list)
{
os << '"';
for (const char c : list)
{
os << c;
}
os << '"';
return os;
return printString(os, list.begin(), list.end());
}
@ -85,6 +120,7 @@ void printInfo(const BufType& buf)
{
Info<< nl << "=========================" << endl;
buf.print(Info);
Info<< "addr: " << Foam::name(buf.list().cdata()) << nl;
toString(Info, buf.list());
Info<< nl << "=========================" << endl;
}
@ -136,14 +172,16 @@ int main(int argc, char *argv[])
Info<< "transfer contents to a List" << endl;
ICharStream ibuf;
// Reclaim data storage from OCharStream -> ICharStream
{
List<char> data;
obuf.swap(data);
ibuf.swap(data);
}
ICharStream ibuf(std::move(obuf));
// OLD
// ICharStream ibuf;
// {
// List<char> data;
// obuf.swap(data);
// ibuf.swap(data);
// }
Info<< nl;
Info<< nl << "input string:";
@ -194,12 +232,12 @@ int main(int argc, char *argv[])
printInfo(newvalues);
{
iliststream is(std::move(newvalues));
icharstream is(std::move(newvalues));
char c = 0;
Info<< nl
<< "getting values from iliststream of "
<< "getting values from icharstream of "
<< is.list() << endl;
// Info<< " (" << is.tellg() << " " << is.remaining() << ")";

View File

@ -5,7 +5,7 @@
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2020 OpenCFD Ltd.
Copyright (C) 2020-2023 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM, distributed under GPL-3.0-or-later.
@ -20,7 +20,7 @@ Description
#include "argList.H"
#include "labelPair.H"
#include "IntRange.H"
#include "StringStream.H"
#include "SpanStream.H"
using namespace Foam;
@ -75,9 +75,8 @@ int main(int argc, char *argv[])
// Read from stream
{
IStringStream is("(10 100)");
ICharStream is("(10 100)");
intRange range;
is >> range;
Info<< "From stream int32_t: " << range << nl;

View File

@ -40,7 +40,7 @@ See also
#include "wordRes.H"
#include "IOstreams.H"
#include "StringStream.H"
#include "SpanStream.H"
#include "scalar.H"
#include "vector.H"
@ -169,22 +169,31 @@ int main(int argc, char *argv[])
Info<<" " << *iter;
}
Info<< nl;
}
Info<< "data:" << Foam::name(ident.cdata())
<< " size:" << ident.size() << nl;
Info<< "resize_unsafe(10)" << nl;
ident.resize_unsafe(10);
Info<< "data:" << Foam::name(ident.cdata())
<< " size:" << ident.size() << nl;
}
if (false)
{
labelList intlist(IStringStream("(0 1 2)")());
labelList intlist(ICharStream("(0 1 2)")());
Info<<"construct from Istream: " << intlist << endl;
IStringStream("(3 4 5)")() >> static_cast<labelUList&>(intlist);
ICharStream("(3 4 5)")() >> static_cast<labelUList&>(intlist);
Info<<"is >>: " << intlist << endl;
IStringStream("(6 7 8)")() >> intlist;
ICharStream("(6 7 8)")() >> intlist;
Info<<"is >>: " << intlist << endl;
}
List<vector> list1(IStringStream("1 ((0 1 2))")());
List<vector> list1(ICharStream("1 ((0 1 2))")());
Info<< "list1: " << list1 << endl;
List<vector> list2

View File

@ -37,7 +37,6 @@ Description
#include "IOstreams.H"
#include "Fstream.H"
#include "StringStream.H"
#include "scalar.H"
#include "vector.H"

View File

@ -37,12 +37,28 @@ Description
using namespace Foam;
Ostream& writeList(Ostream& os, const UList<char>& list)
Ostream& printString(Ostream& os, const char* first, const char* last)
{
os << '"';
for (; first != last; (void)++first)
{
os << *first;
}
os << '"';
return os;
}
Ostream& printView(Ostream& os, const char* first, const char* last)
{
char buf[4];
os << list.size() << '(';
for (const char c : list)
os << label(last-first) << '(';
for (; first != last; (void)++first)
{
const char c = *first;
if (isprint(c))
{
os << c;
@ -67,16 +83,35 @@ Ostream& writeList(Ostream& os, const UList<char>& list)
}
#if __cplusplus >= 201703L
Ostream& printView(Ostream& os, std::string_view s)
{
return printView(os, s.begin(), s.end());
}
#endif
Ostream& printView(Ostream& os, stdFoam::span<char> s)
{
return printView(os, s.begin(), s.end());
}
Ostream& printView(Ostream& os, const UList<char>& list)
{
return printView(os, list.begin(), list.end());
}
Ostream& writeList(Ostream& os, const UList<char>& list)
{
return printView(os, list);
}
Ostream& toString(Ostream& os, const UList<char>& list)
{
os << '"';
for (const char c : list)
{
os << c;
}
os << '"';
return os;
return printString(os, list.begin(), list.end());
}
@ -85,6 +120,7 @@ void printInfo(const BufType& buf)
{
Info<< nl << "=========================" << endl;
buf.print(Info);
Info<< "addr: " << Foam::name(buf.list().cdata()) << nl;
toString(Info, buf.list());
Info<< nl << "=========================" << endl;
}
@ -152,11 +188,6 @@ int main(int argc, char *argv[])
printInfo(obuf);
obuf.shrink();
Info<< "after shrink" << nl;
printInfo(obuf);
// Add some more
for (label i=10; i < 15; ++i)
{
@ -175,13 +206,16 @@ int main(int argc, char *argv[])
Info<< "transfer contents to a List or ICharStream" << nl;
ICharStream ibuf;
// Reclaim data storage from OCharStream -> ICharStream
{
List<char> data;
obuf.swap(data);
ibuf.swap(data);
}
ICharStream ibuf(std::move(obuf));
// OLD
// ICharStream ibuf;
// {
// List<char> data;
// obuf.swap(data);
// ibuf.swap(data);
// }
Info<<"original:";
printInfo(obuf);
@ -253,6 +287,14 @@ int main(int argc, char *argv[])
Info<< "Compact" << nl;
printInfo(os2);
Info<< "address: " << Foam::name(os2.list().cdata()) << nl;
DynamicList<char> chars(os2.release());
Info<< "chars: " << chars.size() << '/' << chars.capacity() << nl;
Info<< "address: " << Foam::name(chars.cdata()) << nl;
Info<< "release" << nl;
printInfo(os2);
}

View File

@ -5,7 +5,7 @@
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2017-2020 OpenCFD Ltd.
Copyright (C) 2017-2023 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
@ -29,6 +29,7 @@ Description
\*---------------------------------------------------------------------------*/
#include "OCountStream.H"
#include "SpanStream.H"
#include "StringStream.H"
#include "Fstream.H"
#include "IOstreams.H"
@ -63,9 +64,11 @@ int main(int argc, char *argv[])
#include "setRootCase.H"
OCountStream cnt;
OCharStream cstr;
OStringStream str;
ocountstream plain;
generateOutput(cstr);
generateOutput(str);
generateOutput(cnt);
generateOutput(plain);
@ -73,6 +76,7 @@ int main(int argc, char *argv[])
cnt.print(Info);
Info<< "counter state: " << (cnt.stdStream().rdstate()) << nl
<< "via char-stream: " << label(cstr.view().size()) << " chars" << nl
<< "via string-stream: " << str.str().size() << " chars" << nl
<< "via ocountstream: " << plain.count() << " chars" << endl;

View File

@ -28,18 +28,15 @@ Description
\*---------------------------------------------------------------------------*/
#include "IOstreams.H"
#include "SpanStream.H"
#include "StringStream.H"
using namespace Foam;
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// Main program:
int main(int argc, char *argv[])
template<class OStreamType>
void doTest()
{
Info<< "Begin test OStringStream" << endl;
OStringStream os;
OStreamType os;
os << "output with some values " << 1 << " entry" << endl;
Info<< "contains:" << nl
@ -59,8 +56,20 @@ int main(int argc, char *argv[])
Info<< "after reset:" << nl
<< os.str() << endl;
}
Info<< "End\n" << endl;
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// Main program:
int main(int argc, char *argv[])
{
Info<< "Begin test OStringStream" << endl;
doTest<OStringStream>();
// No reset() method: doTest<OCharStream>();
Info<< "\nEnd\n" << endl;
return 0;
}

View File

@ -39,12 +39,28 @@ Description
using namespace Foam;
Ostream& writeList(Ostream& os, const UList<char>& list)
Ostream& printString(Ostream& os, const char* first, const char* last)
{
os << '"';
for (; first != last; (void)++first)
{
os << *first;
}
os << '"';
return os;
}
Ostream& printView(Ostream& os, const char* first, const char* last)
{
char buf[4];
os << list.size() << '(';
for (const char c : list)
os << label(last-first) << '(';
for (; first != last; (void)++first)
{
const char c = *first;
if (isprint(c))
{
os << c;
@ -69,29 +85,41 @@ Ostream& writeList(Ostream& os, const UList<char>& list)
}
#if __cplusplus >= 201703L
Ostream& printView(Ostream& os, std::string_view s)
{
return printView(os, s.begin(), s.end());
}
#endif
Ostream& printView(Ostream& os, stdFoam::span<char> s)
{
return printView(os, s.begin(), s.end());
}
Ostream& printView(Ostream& os, const UList<char>& list)
{
return printView(os, list.begin(), list.end());
}
Ostream& writeList(Ostream& os, const UList<char>& list)
{
return printView(os, list.begin(), list.end());
}
Ostream& toString(Ostream& os, const UList<char>& list)
{
os << '"';
for (const char c : list)
{
os << c;
}
os << '"';
return os;
return printString(os, list.begin(), list.end());
}
Ostream& toString(Ostream& os, const std::vector<char>& list)
{
os << '"';
for (const char c : list)
{
os << c;
}
os << '"';
return os;
return printString(os, list.data(), list.data() + list.size());
}

View File

@ -5,7 +5,7 @@
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2017-2019 OpenCFD Ltd.
Copyright (C) 2017-2023 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
@ -36,7 +36,7 @@ See also
#include "OSspecific.H"
#include "IOstreams.H"
#include "StringStream.H"
#include "SpanStream.H"
#include "labelList.H"
#include "ListOps.H"
@ -95,7 +95,7 @@ int main(int argc, char *argv[])
{
Info<<"Read from " << inputSLList << nl;
IStringStream is(inputSLList);
ISpanStream is(inputSLList);
is >> ulist;
// Info<<"source: "; print(source);
@ -107,7 +107,7 @@ int main(int argc, char *argv[])
{
Info<<"Read from " << inputCompound << nl;
IStringStream is(inputCompound);
ISpanStream is(inputCompound);
is >> ulist;
// Info<<"source: "; print(source);

View File

@ -31,7 +31,6 @@ Description
#include "IOstreams.H"
#include "MinMax.H"
#include "Switch.H"
#include "StringStream.H"
using namespace Foam;

View File

@ -37,7 +37,7 @@ Description
#include "HashSet.H"
#include "ListOps.H"
#include "cpuTime.H"
#include "StringStream.H"
#include "SpanStream.H"
#include "FlatOutput.H"
#include <vector>
#include <unordered_set>
@ -124,7 +124,7 @@ int main(int argc, char *argv[])
Info<< "Test read/write (ASCII)" << nl;
OStringStream ostr;
OCharStream ostr;
undecorated(ostr, set3a); // like flatOutput
ostr << bitSet();
@ -132,7 +132,7 @@ int main(int argc, char *argv[])
undecorated(ostr, set3a); // like flatOutput
{
IStringStream istr(ostr.str());
ISpanStream istr(ostr.view());
Info<< "parse: " << istr.str() << nl;
bitSet bset1(istr);

View File

@ -36,7 +36,7 @@ Description
#include "DynamicList.H"
#include "IOstreams.H"
#include "ITstream.H"
#include "StringStream.H"
#include "SpanStream.H"
#include "bitSet.H"
#include "FlatOutput.H"
@ -415,7 +415,7 @@ int main(int argc, char *argv[])
Info<< "\nassign from indices\n";
list4.readList
(
IStringStream
ICharStream
(
"{0 1 2 3 12 13 14 19 20 21}"
)()

View File

@ -5,7 +5,7 @@
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2021 OpenCFD Ltd.
Copyright (C) 2021-2023 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
@ -38,7 +38,7 @@ Description
#include "charList.H"
#include "labelList.H"
#include "StringStream.H"
#include "SpanStream.H"
#include "ListOps.H"
#include "SubList.H"
#include "FlatOutput.H"
@ -61,7 +61,7 @@ int main(int argc, char *argv[])
// Info<< "Known compound tokens: "
// << token::compound::emptyConstructorTablePtr_->sortedToc() << nl;
OStringStream ostr;
OCharStream ostr;
{
List<char> alphabet(64);
@ -75,7 +75,8 @@ int main(int argc, char *argv[])
}
{
IStringStream istr(ostr.str());
// ICharStream istr(ostr.release());
ISpanStream istr(ostr.view());
List<char> alphabet(istr);
Info<< "re-read: " << alphabet << nl;
@ -88,6 +89,8 @@ int main(int argc, char *argv[])
Info<< "blanked: " << alphabet << nl;
}
Info<< "\nEnd\n" << nl;
return 0;
}

View File

@ -31,7 +31,6 @@ Description
#include "IOobject.H"
#include "IOstreams.H"
#include "IFstream.H"
#include "StringStream.H"
#include "cpuTime.H"
#include "labelList.H"
#include "DynamicList.H"
@ -57,7 +56,7 @@ class IFstreamDelayed
:
public IFstream
{
virtual bool readCompoundToken(token& tok, const word& type)
virtual bool readCompoundToken(token& tok, const word& type) override
{
auto& is = *this;

View File

@ -5,7 +5,7 @@
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2017-2021 OpenCFD Ltd.
Copyright (C) 2017-2023 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
@ -36,6 +36,7 @@ Description
#include "IOobject.H"
#include "IFstream.H"
#include "dictionary.H"
#include "SpanStream.H"
#include "ops.H"
#include "scalarRange.H"
#include "stringOps.H"
@ -348,7 +349,7 @@ int main(int argc, char *argv[])
Info<< nl << "Test reading good/bad/empty scalar entries" << nl;
dictionary dict2
(
IStringStream
ICharStream
(
"good 3.14159;\n"
"negative -3.14159;\n"
@ -418,7 +419,7 @@ int main(int argc, char *argv[])
dictionary mydict
(
IStringStream
ICharStream
(
"scalar 3.14159;\n"
"label 10;\n"

View File

@ -5,7 +5,7 @@
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2021 OpenCFD Ltd.
Copyright (C) 2021-2023 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
@ -35,7 +35,7 @@ Description
#include "IOstreams.H"
#include "dictionary.H"
#include "vector.H"
#include "StringStream.H"
#include "SpanStream.H"
using namespace Foam;
@ -47,7 +47,7 @@ int main(int argc, char *argv[])
argList::noParallel();
{
IStringStream is
ICharStream is
(
"value 10;"
"scalar1 $value;"

View File

@ -29,6 +29,7 @@ License
#include "dictionary.H"
#include "primitiveEntry.H"
#include "dimensionedTypes.H"
#include "SpanStream.H"
using namespace Foam;
@ -53,7 +54,7 @@ int main(int argc, char *argv[])
{
string dimString("[Pa m^2 s^-2]");
IStringStream is("[Pa m^2 s^-2]");
ICharStream is("[Pa m^2 s^-2]");
Pout<< nl;
Pout<< "dimensionSet construct from (is) with contents "
@ -70,23 +71,23 @@ int main(int argc, char *argv[])
{
Pout<< nl
<< "construct from (is) = "
<< dimensionedScalar(IStringStream("bla [Pa mm^2 s^-2] 3.0")())
<< dimensionedScalar(ICharStream("bla [Pa mm^2 s^-2] 3.0")())
<< endl;
Pout<< "construct from (name,is) = "
<< dimensionedScalar
(
"ABC",
IStringStream("[Pa mm^2 s^-2] 3.0")()
ICharStream("[Pa mm^2 s^-2] 3.0")()
) << endl;
Pout<< "construct from (name,dims,is) = "
<< dimensionedScalar
(
"ABC",
dimLength,
IStringStream("bla [mm] 3.0")()
ICharStream("bla [mm] 3.0")()
) << endl;
{
IStringStream is("bla [mm] 3.0");
ICharStream is("bla [mm] 3.0");
dimensionedScalar ds;
is >> ds;
Pout<< "read:" << ds << endl;

View File

@ -0,0 +1,3 @@
Test-fileHandler-writing.C
EXE = $(FOAM_USER_APPBIN)/Test-fileHandler-writing

View File

@ -0,0 +1,18 @@
EXE_INC = \
-I$(LIB_SRC)/finiteVolume/lnInclude \
-I$(LIB_SRC)/meshTools/lnInclude \
-I$(LIB_SRC)/sampling/lnInclude \
-I$(LIB_SRC)/TurbulenceModels/turbulenceModels/lnInclude \
-I$(LIB_SRC)/TurbulenceModels/incompressible/lnInclude \
-I$(LIB_SRC)/transportModels \
-I$(LIB_SRC)/transportModels/incompressible/singlePhaseTransportModel
EXE_LIBS = \
-lfiniteVolume \
-lfvOptions \
-lmeshTools \
-lsampling \
-lturbulenceModels \
-lincompressibleTurbulenceModels \
-lincompressibleTransportModels \
-latmosphericModels

View File

@ -0,0 +1,169 @@
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2023 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM 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 3 of the License, or
(at your option) any later version.
OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Application
Test-fileHandler-writing
Description
Simple test of file writing, including timings
\*---------------------------------------------------------------------------*/
#include "argList.H"
#include "profiling.H"
#include "clockTime.H"
#include "fileName.H"
#include "fileOperation.H"
#include "IOstreams.H"
#include "OSspecific.H"
#include "ReadFields.H"
#include "volFields.H"
using namespace Foam;
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// Main program:
int main(int argc, char *argv[])
{
argList::addNote
(
"Loads mesh and fields from latest time and writes multiple times"
);
argList::noFunctionObjects(); // Disallow function objects
argList::addVerboseOption("additional verbosity");
argList::addOption("output", "Begin output iteration (default: 10000)");
argList::addOption("count", "Number of writes (default: 1)");
#include "setRootCase.H"
#include "createTime.H"
const label firstOutput = args.getOrDefault("output", 10000);
const label nOutput = args.getOrDefault("count", 1);
const int verbose = args.verbose();
// Select latestTime, including 0 and constant
{
const auto& times = runTime.times();
const label timeIndex = (times.size()-1);
if (timeIndex < 0)
{
FatalErrorInFunction
<< "No times!"
<< exit(FatalError);
}
runTime.setTime(times[timeIndex], timeIndex);
}
// #include "createMesh.H"
Info << "Create mesh time = " << runTime.timeName() << nl;
fvMesh mesh
(
IOobject
(
polyMesh::defaultRegion,
runTime.timeName(),
runTime,
Foam::IOobject::MUST_READ
),
false
);
mesh.init(true); // initialise all (lower levels and current)
Info<< endl;
// Read objects in time directory
IOobjectList objects(mesh, runTime.timeName());
// List of stored objects to clear after (as required)
DynamicList<regIOobject*> storedObjects;
// Read GeometricFields
Info<< nl << "Load fields" << nl;
#undef ReadFields
#define ReadFields(FieldType) \
readFields<FieldType>(mesh, objects, predicates::always{}, storedObjects);
// Read volFields
ReadFields(volScalarField);
ReadFields(volVectorField);
ReadFields(volSphericalTensorField);
ReadFields(volSymmTensorField);
ReadFields(volTensorField);
// Set fields to AUTO_WRITE
for (regIOobject* io : storedObjects)
{
io->writeOpt(IOobjectOption::AUTO_WRITE);
}
Info<< nl
<< "Writing " << nOutput << " times starting at "
<< firstOutput << nl;
clockTime timing;
if (verbose) Info<< "Time:";
for
(
label timeIndex = firstOutput, count = 0;
count < nOutput;
++timeIndex, ++count
)
{
runTime.setTime(timeIndex, timeIndex);
if (verbose) Info<< ' ' << runTime.timeName() << flush;
runTime.writeNow();
}
if (verbose) Info<< nl;
Info<< nl << "Writing took "
<< timing.timeIncrement() << "s" << endl;
Info<< nl
<< "Cleanup newly generated files with" << nl << nl
<< " foamListTimes -rm -time "
<< firstOutput << ":" << nl
<< " foamListTimes -processor -rm -time "
<< firstOutput << ":" << nl;
Info<< "\nEnd\n" << endl;
return 0;
}
// ************************************************************************* //

View File

@ -6,7 +6,7 @@
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2011-2016 OpenFOAM Foundation
Copyright (C) 2017 OpenCFD Ltd.
Copyright (C) 2017-2023 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
@ -30,6 +30,7 @@ License
#include "fvMesh.H"
#include "volFields.H"
#include "surfaceFields.H"
#include "SpanStream.H"
using namespace Foam;
@ -76,9 +77,9 @@ int main(int argc, char *argv[])
PtrList<dictionary> boundaryDicts(pbm.size());
forAll(pbm, patchi)
{
OStringStream os;
OCharStream os;
os << pbm[patchi];
IStringStream is(os.str());
ISpanStream is(os.view());
boundaryDicts.set(patchi, new dictionary(is));
}

View File

@ -117,8 +117,7 @@ void cell_labels
nVerts += meshFaces[facei].size();
}
// pointLabels.clear();
pointLabels.expandStorage();
pointLabels.resize(pointLabels.capacity()); // Use full storage
// The first face has no duplicates, can copy in values
const labelList& firstFace = meshFaces[cFaces[0]];

View File

@ -34,7 +34,6 @@ Description
#include "scalar.H"
#include "FlatOutput.H"
#include "SpanStream.H"
#include "StringStream.H"
#include "NASCore.H"
#include "parsing.H"
#include "Tuple2.H"
@ -443,6 +442,7 @@ int main(int argc, char *argv[])
<< " read " << sizeof(scalar) << nl;
List<otherType> srcList(15);
List<scalar> dstList; // Read back
forAll(srcList, i)
{
@ -452,13 +452,8 @@ int main(int argc, char *argv[])
OCharStream os(IOstreamOption::BINARY);
os << srcList;
DynamicList<char> buf;
os.swap(buf); // Recover written contents
// Read back
List<scalar> dstList;
ISpanStream is(buf, IOstreamOption::BINARY);
// Recover written contents
ICharStream is(os.release(), IOstreamOption::BINARY);
is.setScalarByteSize(sizeof(otherType));
Info<< "Stream scalar-size ("

View File

@ -37,7 +37,7 @@ Description
#include "scalarPredicates.H"
#include "FlatOutput.H"
#include "Tuple2.H"
#include "StringStream.H"
#include "SpanStream.H"
#include "ops.H"
#include "bitSet.H"
@ -164,7 +164,7 @@ int main(int argc, char *argv[])
Info<< nl << "Construct from Istream" << nl;
{
IStringStream is("((less 10) (greater 100) (less -8) (le -9))");
ICharStream is("((less 10) (greater 100) (less -8) (le -9))");
predicates::scalars accept(is);
doTest(values, accept);

View File

@ -6,7 +6,7 @@
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2011-2015 OpenFOAM Foundation
Copyright (C) 2019 OpenCFD Ltd.
Copyright (C) 2019-2023 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
@ -32,6 +32,7 @@ Description
\*---------------------------------------------------------------------------*/
#include "OSHA1stream.H"
#include "SpanStream.H"
#include "StringStream.H"
#include "dictionary.H"
@ -118,7 +119,7 @@ int main(int argc, char * argv[])
{
dictionary dict
(
IStringStream
ICharStream
(
"parent { Default_Boundary_Region { type zeroGradient; } }"
"inlet_1 { value inlet_1; }"

View File

@ -34,7 +34,6 @@ Description
#include "argList.H"
#include "IOstreams.H"
#include "StringStream.H"
#include "scalar.H"
#include "vector.H"
#include "labelRange.H"

View File

@ -6,7 +6,7 @@
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2011 OpenFOAM Foundation
Copyright (C) 2019-2021 OpenCFD Ltd.
Copyright (C) 2019-2023 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
@ -32,7 +32,7 @@ Description
#include "ListOps.H"
#include "FlatOutput.H"
#include "IOstreams.H"
#include "StringStream.H"
#include "SpanStream.H"
using namespace Foam;
@ -55,7 +55,7 @@ int main(int argc, char *argv[])
};
labelList matches;
wordRes matcher1(IStringStream("( okey \"[hy]e+.*\" )")());
wordRes matcher1(ICharStream("( okey \"[hy]e+.*\" )")());
Info<< "stringList " << strings << nl;

View File

@ -0,0 +1,3 @@
Test-string_view1.C
EXE = $(FOAM_USER_APPBIN)/Test-string_view1

View File

@ -0,0 +1,2 @@
/* EXE_INC = */
/* EXE_LIBS = */

View File

@ -0,0 +1,94 @@
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2023 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM 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 3 of the License, or
(at your option) any later version.
OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Description
Test some string_view functionality
\*---------------------------------------------------------------------------*/
#include "string.H"
#include "IOstreams.H"
#include "List.H"
using namespace Foam;
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// Main program:
int main(int argc, char *argv[])
{
Info<< "Compiled with C++ " << __cplusplus;
#if __cplusplus >= 201703L
Info<< " - has std::string_view" << nl << nl;
#else
Info<< " - NO std::string_view" << nl << nl;
#endif
// basics
{
for
(
const auto& cstr
:
{
"abcdef"
}
)
{
const auto len = strlen(cstr);
Info<< nl
<< "input: <" << cstr << '>'
<< " type: " << typeid(cstr).name() << " len:" << len << nl;
#if __cplusplus >= 201703L
Info<< " view: " << std::string_view(cstr) << nl;
#endif
Info<< " span: "
<< stdFoam::span<const char>(cstr, len) << nl;
Info<< " span: "
<< stdFoam::span<char>(const_cast<char*>(cstr), len) << nl;
}
}
// This should fail to compile:
#if 0
{
labelList values(identity(4));
Info<< "values: " << values << nl;
Info<< " span: "
<< stdFoam::span<label>(values.data(), values.size()) << nl;
}
#endif
Info<< "\nEnd\n" << endl;
return 0;
}
// ************************************************************************* //

View File

@ -6,7 +6,7 @@
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2011-2016 OpenFOAM Foundation
Copyright (C) 2016-2020 OpenCFD Ltd.
Copyright (C) 2016-2023 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
@ -66,8 +66,7 @@ Note
#include "MeshedSurfaces.H"
#include "ModifiableMeshedSurface.H"
#include "UnsortedMeshedSurfaces.H"
#include "StringStream.H"
#include "SpanStream.H"
using namespace Foam;
@ -180,9 +179,9 @@ int main(int argc, char *argv[])
// check: output to ostream, construct from istream
{
OStringStream os;
OCharStream os;
os << surf;
IStringStream is(os.str());
ISpanStream is(os.view());
// both work:
triSurface surf2(is);
@ -245,9 +244,9 @@ int main(int argc, char *argv[])
// check: output to ostream, construct from istream
{
OStringStream os;
OCharStream os;
os << surf;
IStringStream is(os.str());
ISpanStream is(os.view());
// both work:
UnsortedMeshedSurface<face> surf2(is);
@ -309,9 +308,9 @@ int main(int argc, char *argv[])
// check: output to ostream, construct from istream
{
OStringStream os;
OCharStream os;
os << surf;
IStringStream is(os.str());
ISpanStream is(os.view());
// both work:
MeshedSurface<face> surf2(is);
@ -373,9 +372,9 @@ int main(int argc, char *argv[])
// check: output to ostream, construct from istream
{
OStringStream os;
OCharStream os;
os << surf;
IStringStream is(os.str());
ISpanStream is(os.view());
// both work:
MeshedSurface<face> surf2(is);

View File

@ -31,7 +31,6 @@ Description
#include "IOobject.H"
#include "IOstreams.H"
#include "IFstream.H"
#include "StringStream.H"
#include "cpuTime.H"
#include "labelList.H"
#include "scalarList.H"

View File

@ -6,7 +6,7 @@
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2011 OpenFOAM Foundation
Copyright (C) 2020-2021 OpenCFD Ltd.
Copyright (C) 2020-2023 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
@ -34,7 +34,7 @@ Description
#include "IOobject.H"
#include "IOstreams.H"
#include "IFstream.H"
#include "StringStream.H"
#include "SpanStream.H"
#include "cpuTime.H"
#include "DynamicList.H"
@ -69,7 +69,7 @@ int main(int argc, char *argv[])
Info<< "input string: " << rawArg << nl;
}
IStringStream is(rawArg);
ISpanStream is(rawArg);
DynamicList<token> tokens;

View File

@ -5,7 +5,7 @@
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2021 OpenCFD Ltd.
Copyright (C) 2021-2023 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM, distributed under GPL-3.0-or-later.
@ -33,11 +33,7 @@ Description
OBJstream os(runTime.globalPath()/outputName);
os.writeQuoted
(
("# " + outputName + "\n"),
false
);
os.writeComment(outputName);
os.write(aMesh.patch().edges(), aMesh.patch().localPoints());
}

View File

@ -148,7 +148,7 @@ void Foam::cellSplitter::setRefinement
)
{
addedPoints_.clear();
addedPoints_.resize(cellToMidPoint.size());
addedPoints_.reserve(cellToMidPoint.size());
//
@ -184,7 +184,7 @@ void Foam::cellSplitter::setRefinement
// Add cells (first one is modified original cell)
//
Map<labelList> cellToCells(cellToMidPoint.size());
Map<labelList> cellToCells(2*cellToMidPoint.size());
forAllConstIters(cellToMidPoint, iter)
{

View File

@ -200,7 +200,7 @@ int main(int argc, char *argv[])
)
{
patchMasterBlocks[patchi] = -1;
rawPatches[patchi].setSize(0);
rawPatches[patchi].clear();
}
else
{

View File

@ -102,7 +102,7 @@ void Foam::fileFormats::ensightMeshReader::readIDs
foamToElem.resize(sz+nShapes);
if (doRead)
{
elemToFoam.resize(sz+nShapes);
elemToFoam.reserve(elemToFoam.size()+nShapes);
for (label shapei = 0; shapei < nShapes; shapei++)
{
label elemi;

View File

@ -76,14 +76,14 @@ label nCells = 0;
bool hangingNodes = false;
pointField points(0);
faceList faces(0);
labelList owner(0);
labelList neighbour(0);
pointField points;
faceList faces;
labelList owner;
labelList neighbour;
// Group type and name
Map<word> groupType(128);
Map<word> groupName(128);
Map<word> groupType;
Map<word> groupName;
// Point groups
DynamicList<label> pointGroupZoneID;
@ -1211,7 +1211,7 @@ int main(int argc, char *argv[])
{
meshMod.addPoint(points[pointi], pointi, -1, true);
}
points.setSize(0);
points.clear();
// Add all cells
for (label celli = 0; celli < nCells; celli++)
@ -1411,9 +1411,9 @@ int main(int argc, char *argv[])
}
// Reclaim storage
faces.setSize(0);
owner.setSize(0);
neighbour.setSize(0);
faces.clear();
owner.clear();
neighbour.clear();
// Modify mesh

View File

@ -1059,7 +1059,7 @@ int main(int argc, char *argv[])
}
}
patchFaces.setSize(0); // Assume that this is no patch at all
patchFaces.clear(); // Assume that this is no patch at all
if (cellCorrespondence[faceIndices[0]] >= 0)
{

View File

@ -357,7 +357,7 @@ Foam::DelaunayMesh<Triangulation>::createMesh
List<DynamicList<face>> patchFaces(1, DynamicList<face>());
List<DynamicList<label>> patchOwners(1, DynamicList<label>());
vertexMap.resize(vertexCount());
vertexMap.reserve(vertexCount());
cellMap.setSize(Triangulation::number_of_finite_cells(), -1);
// Calculate pts and a map of point index to location in pts.

View File

@ -71,8 +71,8 @@ bool uniform::sizeLocations
scalarField& shapeSizes
) const
{
shapePts.setSize(0);
shapeSizes.setSize(0);
shapePts.clear();
shapeSizes.clear();
return true;
}

View File

@ -240,13 +240,13 @@ bool Foam::checkWedges
if (setPtr)
{
setPtr->resize(2*nEdgesInError);
setPtr->reserve(2*nEdgesInError);
forAllConstIters(edgesInError, iter)
{
if (iter() >= 0)
if (iter.val() >= 0)
{
setPtr->insert(iter.key()[0]);
setPtr->insert(iter.key()[1]);
setPtr->insert(iter.key().first());
setPtr->insert(iter.key().second());
}
}
}

View File

@ -375,7 +375,7 @@ bool doCommand
topoSet& currentSet = currentSetPtr();
// Presize it according to current mesh data.
currentSet.resize(max(currentSet.size(), typSize));
currentSet.reserve(max(currentSet.size(), typSize));
}
}

View File

@ -2164,12 +2164,9 @@ Foam::label Foam::dynamicIndexedOctree<Type>::findBox
if (!nodes_.empty())
{
if (!elements.capacity())
{
// Some arbitrary minimal size estimate (eg, 1/100 are found)
label estimatedCapacity(max(256, 2*(shapes_.size() / 100)));
elements.resize(estimatedCapacity);
}
// Some arbitrary minimal size estimate (eg, 1/100 are found)
label estimatedCount(max(128, (shapes_.size() / 100)));
elements.reserve(estimatedCount);
// start node=0, store results
findBox(0, searchBox, &elements);
@ -2223,12 +2220,9 @@ Foam::label Foam::dynamicIndexedOctree<Type>::findSphere
if (!nodes_.empty())
{
if (!elements.capacity())
{
// Some arbitrary minimal size estimate (eg, 1/100 are found)
label estimatedCapacity(max(256, 2*(shapes_.size()/100)));
elements.resize(estimatedCapacity);
}
// Some arbitrary minimal size estimate (eg, 1/100 are found)
label estimatedCount(max(128, (shapes_.size() / 100)));
elements.reserve(estimatedCount);
// start node=0, store results
findSphere(0, centre, radiusSqr, &elements);

View File

@ -2517,12 +2517,9 @@ Foam::label Foam::indexedOctree<Type>::findBox
if (!nodes_.empty())
{
if (!elements.capacity())
{
// Some arbitrary minimal size estimate (eg, 1/100 are found)
label estimatedCapacity(max(256, 2*(shapes_.size() / 100)));
elements.resize(estimatedCapacity);
}
// Some arbitrary minimal size estimate (eg, 1/100 are found)
label estimatedCount(max(128, (shapes_.size() / 100)));
elements.reserve(estimatedCount);
// start node=0, store results
findBox(0, searchBox, &elements);
@ -2576,12 +2573,9 @@ Foam::label Foam::indexedOctree<Type>::findSphere
if (!nodes_.empty())
{
if (!elements.capacity())
{
// Some arbitrary minimal size estimate (eg, 1/100 are found)
label estimatedCapacity(max(256, 2*(shapes_.size() / 100)));
elements.resize(estimatedCapacity);
}
// Some arbitrary minimal size estimate (eg, 1/100 are found)
label estimatedCount(max(128, (shapes_.size() / 100)));
elements.reserve(estimatedCount);
// start node=0, store results
findSphere(0, centre, radiusSqr, &elements);

View File

@ -232,17 +232,16 @@ public:
//- The contents of the first internal array
SubList<T> array_one();
//- The contents of the first internal array
//- The contents of the second internal array
SubList<T> array_two();
//- The contents of the second internal array
//- The contents of the first internal array
const SubList<T> array_one() const;
//- The contents of the second internal array
const SubList<T> array_two() const;
// Access
//- Access the first element (front). Requires !empty().
@ -352,9 +351,6 @@ public:
// Member Operators
//- Return the buffer flattened as a single List. Use sparingly!
List<T> operator()() const { return this->list(); }
//- Non-const access to an element in the list.
// The index is allowed to wrap in both directions
inline T& operator[](const label i);
@ -489,47 +485,6 @@ public:
//- Return a const_iterator at end of buffer
inline const_iterator end() const { return cend(); }
// Housekeeping
//- Same as contains()
bool found(const T& val, label pos = 0) const
{
return contains(val, pos);
}
//- Access the first element (front). Requires !empty().
//FOAM_DEPRECATED_FOR(2022-10, "front()")
T& first() { return front(); }
//- Access the first element (front). Requires !empty().
//FOAM_DEPRECATED_FOR(2022-10, "front()")
const T& first() const { return front(); }
//- Access the last element (back). Requires !empty().
//FOAM_DEPRECATED_FOR(2022-10, "back()")
T& last() { return back(); }
//- Access the last element (back). Requires !empty().
//FOAM_DEPRECATED_FOR(2022-10, "back()")
const T& last() const { return back(); }
//- Copy append an element to the end of the buffer
//FOAM_DEPRECATED_FOR(2022-10, "push_back()")
void append(const T& val) { this->push_back(val); }
//- Move append an element to the end of the buffer
//FOAM_DEPRECATED_FOR(2022-10, "push_back()")
void append(T&& val) { this->push_back(std::move(val)); }
//- Copy append multiple elements the end of the buffer
//FOAM_DEPRECATED_FOR(2022-10, "push_back()")
void append(const UList<T>& list) { this->push_back(list); }
//- Same as push_uniq()
FOAM_DEPRECATED_STRICT(2022-10, "push_uniq()")
label appendUniq(const T& val) { return this->push_uniq(val); }
};

View File

@ -160,6 +160,7 @@ inline Foam::CircularBuffer<T>::CircularBuffer
template<class T>
inline Foam::label Foam::CircularBuffer<T>::capacity() const noexcept
{
// or storage_.capacity();
return storage_.size();
}

View File

@ -101,8 +101,11 @@ public:
// Constructors
//- Construct with given or default (128) table capacity
explicit DictionaryBase(const label initialCapacity = 128)
//- Default construct: empty without allocation (capacity=0).
DictionaryBase() = default;
//- Construct empty with initial table capacity
explicit DictionaryBase(const label initialCapacity)
:
hashedTs_(initialCapacity)
{}

View File

@ -62,8 +62,11 @@ public:
// Constructors
//- Default construct, or with initial table capacity
explicit PtrDictionary(const label initialCapacity = 128)
//- Default construct: empty without allocation (capacity=0).
PtrDictionary() = default;
//- Construct empty with initial table capacity
explicit PtrDictionary(const label initialCapacity)
:
dict_type(initialCapacity)
{}

View File

@ -6,6 +6,7 @@
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2011-2016 OpenFOAM Foundation
Copyright (C) 2023 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
@ -63,8 +64,11 @@ public:
// Constructors
//- Default construct, or with initial table capacity
explicit UDictionary(const label initialCapacity = 128)
//- Default construct: empty without allocation (capacity=0).
UDictionary() = default;
//- Construct empty with initial table capacity
explicit UDictionary(const label initialCapacity)
:
dict_type(initialCapacity)
{}

View File

@ -6,6 +6,7 @@
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2011-2016 OpenFOAM Foundation
Copyright (C) 2023 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
@ -63,8 +64,11 @@ public:
// Constructors
//- Default construct, or with initial table capacity
explicit UPtrDictionary(const label initialCapacity = 128)
//- Default construct: empty without allocation (capacity=0).
UPtrDictionary() = default;
//- Construct empty with initial table capacity
explicit UPtrDictionary(const label initialCapacity)
:
dict_type(initialCapacity)
{}

View File

@ -5,7 +5,7 @@
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2018 OpenCFD Ltd.
Copyright (C) 2018-2023 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
@ -32,11 +32,11 @@ License
Foam::labelHashSet Foam::HashSetOps::used(const bitSet& select)
{
labelHashSet output(0);
labelHashSet output;
if (select.any())
{
output.resize(2*select.count());
output.reserve(select.count());
for (label i = select.find_first(); i >= 0; i = select.find_next(i))
{

View File

@ -6,7 +6,7 @@
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2011-2015 OpenFOAM Foundation
Copyright (C) 2017-2021 OpenCFD Ltd.
Copyright (C) 2017-2023 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
@ -61,10 +61,7 @@ void Foam::HashPtrTable<T, Key, Hash>::readIstream
if (len)
{
if (2*len > this->capacity())
{
this->resize(2*len);
}
this->reserve(this->size() + len);
if (delimiter == token::BEGIN_LIST)
{
@ -133,6 +130,7 @@ void Foam::HashPtrTable<T, Key, Hash>::read
const INew& inew
)
{
this->reserve(this->size() + dict.size());
for (const entry& e : dict)
{
this->set(e.keyword(), inew(e.dict()).ptr());

View File

@ -43,15 +43,8 @@ inline Foam::label Foam::HashSet<Key, Hash>::assignMany
InputIter last
)
{
if (!this->capacity())
{
// Zero-sized from a previous transfer()?
this->resize(2*nItems);
}
else
{
this->clear();
}
this->clear();
this->reserve(nItems);
return insert(first, last);
}
@ -104,7 +97,7 @@ Foam::HashSet<Key, Hash>::HashSet
const HashTable<AnyType, Key, AnyHash>& tbl
)
:
parent_type(tbl.capacity())
parent_type(2*tbl.size())
{
for (auto iter = tbl.cbegin(); iter != tbl.cend(); ++iter)
{

View File

@ -124,10 +124,10 @@ public:
// Constructors
//- Default construct with default (128) initial table capacity
HashSet() = default;
//- Default construct: empty without allocation (capacity=0)
HashSet() noexcept = default;
//- Construct empty with zero table capacity
//- Construct empty without allocation (capacity=0)
explicit HashSet(const Foam::zero) noexcept
:
parent_type(Foam::zero{})

View File

@ -37,7 +37,7 @@ License
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
template<class T, class Key, class Hash>
Foam::HashTable<T, Key, Hash>::HashTable(const Foam::zero) noexcept
Foam::HashTable<T, Key, Hash>::HashTable() noexcept
:
HashTableCore(),
size_(0),
@ -47,30 +47,23 @@ Foam::HashTable<T, Key, Hash>::HashTable(const Foam::zero) noexcept
template<class T, class Key, class Hash>
Foam::HashTable<T, Key, Hash>::HashTable()
Foam::HashTable<T, Key, Hash>::HashTable(const Foam::zero) noexcept
:
HashTable<T, Key, Hash>(128)
HashTable<T, Key, Hash>()
{}
template<class T, class Key, class Hash>
Foam::HashTable<T, Key, Hash>::HashTable(const label initialCapacity)
:
HashTableCore(),
size_(0),
capacity_(0),
table_(nullptr)
HashTable<T, Key, Hash>()
{
if (initialCapacity > 0)
{
// Like resize() but no initial content to transfer
capacity_ = HashTableCore::canonicalSize(initialCapacity);
table_ = new node_type*[capacity_];
for (label i=0; i < capacity_; ++i)
{
table_[i] = nullptr;
}
std::fill_n(table_, capacity_, static_cast<node_type*>(nullptr));
}
}
@ -78,7 +71,7 @@ Foam::HashTable<T, Key, Hash>::HashTable(const label initialCapacity)
template<class T, class Key, class Hash>
Foam::HashTable<T, Key, Hash>::HashTable(const HashTable<T, Key, Hash>& ht)
:
HashTable<T, Key, Hash>(ht.capacity_)
HashTable<T, Key, Hash>(2*ht.size())
{
for (const_iterator iter = ht.cbegin(); iter != ht.cend(); ++iter)
{
@ -367,8 +360,7 @@ bool Foam::HashTable<T, Key, Hash>::setEntry
{
if (!capacity_)
{
// Same as default sizing
resize(128);
setCapacity(128); // Impose an initial capacity
}
const label index = hashKeyIndex(key);
@ -393,9 +385,9 @@ bool Foam::HashTable<T, Key, Hash>::setEntry
new node_type(table_[index], key, std::forward<Args>(args)...);
++size_;
if (0.8*capacity_ < size_) // Resize after 80% fill factor
if (0.8*capacity_ < size_) // Resize after 0.8 load factor
{
if (capacity_ < maxTableSize) resize(2*capacity_);
if (capacity_ < maxTableSize) setCapacity(2*capacity_);
}
}
else if (overwrite)
@ -445,8 +437,7 @@ void Foam::HashTable<T, Key, Hash>::insert_node(node_type* entry)
if (!capacity_)
{
// Same as default sizing
resize(128);
setCapacity(128); // Impose an initial capacity
}
const label index = hashKeyIndex(entry->key());
@ -472,7 +463,7 @@ void Foam::HashTable<T, Key, Hash>::insert_node(node_type* entry)
++size_;
if (0.8*capacity_ < size_) // Resize after 80% fill factor
{
if (capacity_ < maxTableSize) resize(2*capacity_);
if (capacity_ < maxTableSize) setCapacity(2*capacity_);
}
}
else
@ -648,44 +639,43 @@ Foam::label Foam::HashTable<T, Key, Hash>::retain
template<class T, class Key, class Hash>
void Foam::HashTable<T, Key, Hash>::resize(const label requestedCapacity)
void Foam::HashTable<T, Key, Hash>::setCapacity(label newCapacity)
{
const label newCapacity = HashTableCore::canonicalSize(requestedCapacity);
const label oldCapacity = capacity_;
newCapacity = HashTableCore::canonicalSize(newCapacity);
if (newCapacity == oldCapacity)
if (newCapacity == capacity_)
{
return;
}
else if (!newCapacity)
if (!size_)
{
// Special treatment for resize(0)
// Table is unpopulated - can already remove now
capacity_ = 0;
delete[] table_;
table_ = nullptr;
}
if (!newCapacity)
{
// Special handling for capacity = 0.
if (size_)
{
WarningInFunction
<< "HashTable contains " << size_
<< " elements, cannot resize(0)" << nl;
<< " elements, cannot set capacity to 0 buckets!" << nl;
}
else
{
capacity_ = 0;
delete[] table_;
table_ = nullptr;
}
return;
}
// Swap primary table entries: size_ is left untouched
auto oldTable = table_;
capacity_ = newCapacity;
const label oldCapacity = capacity_;
capacity_ = newCapacity;
table_ = new node_type*[capacity_];
for (label i=0; i < capacity_; ++i)
{
table_[i] = nullptr;
}
std::fill_n(table_, capacity_, static_cast<node_type*>(nullptr));
if (!oldTable)
{
@ -718,6 +708,26 @@ void Foam::HashTable<T, Key, Hash>::resize(const label requestedCapacity)
}
template<class T, class Key, class Hash>
void Foam::HashTable<T, Key, Hash>::resize(label newCapacity)
{
setCapacity(newCapacity);
}
template<class T, class Key, class Hash>
void Foam::HashTable<T, Key, Hash>::reserve(label numEntries)
{
if (numEntries > size_)
{
// From number of entries to estimated capacity
// - initial load factor of 0.5
numEntries *= 2;
if (numEntries > capacity_) setCapacity(numEntries);
}
}
template<class T, class Key, class Hash>
void Foam::HashTable<T, Key, Hash>::clear()
{
@ -917,15 +927,8 @@ void Foam::HashTable<T, Key, Hash>::operator=
return; // Self-assignment is a no-op
}
if (!capacity_)
{
// Zero-sized from a previous transfer()?
resize(rhs.capacity_);
}
else
{
clear();
}
this->clear();
this->reserve(rhs.size());
for (const_iterator iter = rhs.cbegin(); iter != rhs.cend(); ++iter)
{
@ -940,15 +943,8 @@ void Foam::HashTable<T, Key, Hash>::operator=
std::initializer_list<std::pair<Key, T>> rhs
)
{
if (!capacity_)
{
// Zero-sized from a previous transfer()?
resize(2*rhs.size());
}
else
{
clear();
}
this->clear();
this->reserve(rhs.size());
for (const auto& keyval : rhs)
{

View File

@ -40,6 +40,12 @@ Description
Internally the table uses closed addressing into a flat storage space
with collisions handled by linked-list chaining.
- The max_load_factor is 0.8, but a load factor 0.5 is generally
assumed when initially creating a HashTable (ie, use an capacity
of twice the expected number elements).
- When inserting into a table without an initial capacity,
a default capacity (bucket count) of 128 is used.
The end iterator of all hash-tables has a nullptr to the hash entry.
Thus avoid separate allocation for each table and use a single one with
a nullptr. The hash-table iterators always have an entry-pointer as the
@ -185,10 +191,10 @@ private:
// Private Data
//- The number of nodes currently stored in table
//- The number of elements currently stored in table
label size_;
//- Number of nodes allocated in table
//- Number of buckets allocated in table
label capacity_;
//- The table of primary nodes
@ -228,18 +234,17 @@ public:
// Constructors
//- Default construct with default (128) initial table capacity
HashTable();
//- Default construct: empty without allocation (capacity=0)
HashTable() noexcept;
//- Construct empty with zero initial table capacity
//- Construct empty without allocation (capacity=0)
explicit HashTable(const Foam::zero) noexcept;
//- Construct empty with initial table capacity
explicit HashTable(const label initialCapacity);
//- Construct from Istream,
//- with default or specified initial table capacity.
HashTable(Istream& is, const label initialCapacity = 128);
//- Construct from Istream
HashTable(Istream& is);
//- Copy construct
HashTable(const this_type& ht);
@ -258,7 +263,7 @@ public:
// Member Functions
// Access
// Capacity
//- True if the hash table is empty
bool empty() const noexcept { return !size_; }
@ -266,9 +271,12 @@ public:
//- The number of elements in table
label size() const noexcept { return size_; }
//- The size of the underlying table
//- The size of the underlying table (the number of buckets)
label capacity() const noexcept { return capacity_; }
// Access
//- Find and return a hashed entry. FatalError if it does not exist.
inline T& at(const Key& key);
@ -526,16 +534,26 @@ public:
);
//- Resize the hash table for efficiency
void resize(const label requestedCapacity);
//- Remove all entries from table
void clear();
//- Remove all entries from table and the table itself.
// Equivalent to clear() followed by resize(0)
// Equivalent to clear() followed by setCapacity(0)
void clearStorage();
//- Change the hash table capacity (number of buckets).
// Setting a zero capacity will only remove the underlying
// storage if the table is empty.
void setCapacity(label newCapacity);
//- Rehash the hash table with new number of buckets.
//- Currently identical to setCapacity()
void resize(label newCapacity);
//- Reserve space for at least the specified number of elements
//- (not the number of buckets) and regenerates the hash table.
void reserve(label numEntries);
//- Swap contents into this table
void swap(HashTable<T, Key, Hash>& rhs) noexcept;

View File

@ -33,13 +33,9 @@ License
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
template<class T, class Key, class Hash>
Foam::HashTable<T, Key, Hash>::HashTable
(
Istream& is,
const label initialCapacity
)
Foam::HashTable<T, Key, Hash>::HashTable(Istream& is)
:
HashTable(initialCapacity)
HashTable<T, Key, Hash>()
{
operator>>(is, *this);
}
@ -170,10 +166,7 @@ Foam::Istream& Foam::HashTable<T, Key, Hash>::readTable
<< exit(FatalIOError);
}
if (2*len > tbl.capacity())
{
tbl.resize(2*len);
}
tbl.reserve(tbl.size() + len);
for (label i=0; i<len; ++i)
{

View File

@ -73,10 +73,10 @@ public:
// Constructors
//- Default construct with default (128) initial table capacity
Map() = default;
//- Default construct: empty without allocation (capacity=0)
Map() noexcept = default;
//- Construct empty with zero initial table capacity
//- Construct empty without allocation (capacity=0)
explicit Map(const Foam::zero) noexcept
:
parent_type(Foam::zero{})

View File

@ -65,10 +65,10 @@ public:
// Constructors
//- Default construct with default (128) initial table capacity
PtrMap() = default;
//- Default construct: empty without allocation (capacity=0)
PtrMap() noexcept = default;
//- Construct empty with zero initial table capacity
//- Construct empty without allocation (capacity=0)
explicit PtrMap(const Foam::zero) noexcept
:
parent_type(Foam::zero{})

View File

@ -69,7 +69,7 @@ Foam::Ostream& Foam::IndirectListBase<T, Addr>::writeList
os.endRawWrite();
}
}
else if (len > 1 && is_contiguous<T>::value && list.uniform())
else if (is_contiguous<T>::value && len > 1 && list.uniform())
{
// Two or more entries, and all entries have identical values.
os << len << token::BEGIN_BLOCK << list[0] << token::END_BLOCK;

View File

@ -152,14 +152,14 @@ public:
inline explicit DynamicList(const IndirectListBase<T, Addr>& lst);
//- Move construct.
inline DynamicList(DynamicList<T, SizeMin>&& lst);
inline DynamicList(DynamicList<T, SizeMin>&& list) noexcept;
//- Move construct with different sizing parameters
template<int AnySizeMin>
inline DynamicList(DynamicList<T, AnySizeMin>&& lst);
inline DynamicList(DynamicList<T, AnySizeMin>&& list) noexcept;
//- Move construct from List
inline DynamicList(List<T>&& lst);
inline DynamicList(List<T>&& list) noexcept;
//- Construct from Istream. Size set to size of list read.
explicit DynamicList(Istream& is);
@ -167,7 +167,7 @@ public:
// Member Functions
// Access
// Capacity
//- Normal lower capacity limit - the SizeMin template parameter
static constexpr label min_size() noexcept { return SizeMin; }
@ -241,20 +241,23 @@ public:
//- Clear the list and delete storage.
inline void clearStorage();
//- Expand the addressable size to fit the allocated capacity.
// Returns the previous addressable size.
inline label expandStorage() noexcept;
//- Shrink the allocated space to the number of elements used.
inline void shrinkStorage();
inline void shrink_to_fit();
//- Shrink the allocated space to the number of elements used.
// Returns a reference to the DynamicList.
//- Shrink the internal bookkeeping of the allocated space to the
//- number of addressed elements without affecting allocation.
// \note when empty() it will delete any allocated memory.
inline void shrink_unsafe();
//- Calls shrink_to_fit() and returns a reference to the DynamicList.
inline DynamicList<T, SizeMin>& shrink();
// Edit
//- Swap with plain List content. Implies shrink_to_fit().
inline void swap(List<T>& list);
//- Swap content, independent of sizing parameter
template<int AnySizeMin>
inline void swap(DynamicList<T, AnySizeMin>& other) noexcept;

View File

@ -260,12 +260,13 @@ inline Foam::DynamicList<T, SizeMin>::DynamicList
template<class T, int SizeMin>
inline Foam::DynamicList<T, SizeMin>::DynamicList
(
DynamicList<T, SizeMin>&& lst
)
DynamicList<T, SizeMin>&& list
) noexcept
:
capacity_(0)
List<T>(std::move(static_cast<List<T>&>(list))),
capacity_(list.capacity())
{
transfer(lst);
list.setCapacity_unsafe(0); // Same as shrink_unsafe() but noexcept
}
@ -273,22 +274,23 @@ template<class T, int SizeMin>
template<int AnySizeMin>
inline Foam::DynamicList<T, SizeMin>::DynamicList
(
DynamicList<T, AnySizeMin>&& lst
)
DynamicList<T, AnySizeMin>&& list
) noexcept
:
capacity_(0)
List<T>(std::move(static_cast<List<T>&>(list))),
capacity_(list.capacity())
{
transfer(lst);
list.setCapacity_unsafe(0); // Same as shrink_unsafe() but noexcept
}
template<class T, int SizeMin>
inline Foam::DynamicList<T, SizeMin>::DynamicList
(
List<T>&& lst
)
List<T>&& list
) noexcept
:
List<T>(std::move(lst)),
List<T>(std::move(list)),
capacity_(List<T>::size())
{}
@ -422,41 +424,64 @@ inline void Foam::DynamicList<T, SizeMin>::clearStorage()
template<class T, int SizeMin>
inline Foam::label Foam::DynamicList<T, SizeMin>::expandStorage() noexcept
{
const label currLen = List<T>::size();
// Address into the entire list
List<T>::setAddressableSize(capacity_);
return currLen;
}
template<class T, int SizeMin>
inline void Foam::DynamicList<T, SizeMin>::shrinkStorage()
inline void Foam::DynamicList<T, SizeMin>::shrink_to_fit()
{
const label currLen = List<T>::size();
if (currLen < capacity_)
{
// Adjust addressable size to trigger proper resizing
List<T>::setAddressableSize(currLen+1);
List<T>::resize(currLen);
capacity_ = List<T>::size();
}
}
template<class T, int SizeMin>
inline void Foam::DynamicList<T, SizeMin>::shrink_unsafe()
{
if (List<T>::empty())
{
// Delete storage if empty
List<T>::clear();
}
capacity_ = List<T>::size();
}
template<class T, int SizeMin>
inline Foam::DynamicList<T, SizeMin>&
Foam::DynamicList<T, SizeMin>::shrink()
{
this->shrinkStorage();
this->shrink_to_fit();
return *this;
}
template<class T, int SizeMin>
inline void
Foam::DynamicList<T, SizeMin>::swap(List<T>& list)
{
if
(
static_cast<const List<T>*>(this)
== static_cast<const List<T>*>(&list)
)
{
return; // Self-swap is a no-op
}
// Remove unused storage
this->shrink_to_fit();
// Swap storage and addressable size
UList<T>::swap(list);
// Update capacity
capacity_ = List<T>::size();
}
template<class T, int SizeMin>
template<int AnySizeMin>
inline void Foam::DynamicList<T, SizeMin>::swap
@ -485,9 +510,8 @@ template<class T, int SizeMin>
inline void
Foam::DynamicList<T, SizeMin>::transfer(List<T>& list)
{
// Take over storage, clear addressing for list
capacity_ = list.size();
List<T>::transfer(list);
capacity_ = List<T>::size();
}
@ -508,12 +532,11 @@ Foam::DynamicList<T, SizeMin>::transfer
return; // Self-assignment is a no-op
}
// Take over storage as-is (without shrink, without using SizeMin)
// clear addressing and storage for old lst.
// Take over storage as-is (without shrink)
capacity_ = list.capacity();
List<T>::transfer(static_cast<List<T>&>(list));
list.clearStorage(); // Ensure capacity=0
list.clearStorage(); // capacity=0 etc.
}
@ -662,7 +685,7 @@ inline void Foam::DynamicList<T, SizeMin>::push_back
)
{
push_back(std::move(static_cast<List<T>&>(list)));
list.clearStorage(); // Ensure capacity=0
list.clearStorage(); // Deletion, capacity=0 etc.
}

View File

@ -222,26 +222,24 @@ Foam::Istream& Foam::DynamicList<T, SizeMin>::readList(Istream& is)
);
}
}
else if (std::is_same<char, T>::value)
else if (std::is_same<char, typename std::remove_cv<T>::type>::value)
{
// Special treatment for char data (always binary and contiguous)
// (see List<char>::readList)
// Special treatment for char data (binary I/O only)
const auto oldFmt = is.format(IOstreamOption::BINARY);
if (len)
{
const auto oldFmt = is.format(IOstreamOption::BINARY);
// read(...) includes surrounding start/end delimiters
is.read(list.data_bytes(), list.size_bytes());
is.format(oldFmt);
is.fatalCheck
(
"DynamicList<char>::readList(Istream&) : "
"reading binary block"
);
}
is.format(oldFmt);
}
else
{
@ -252,9 +250,13 @@ Foam::Istream& Foam::DynamicList<T, SizeMin>::readList(Istream& is)
{
if (delimiter == token::BEGIN_LIST)
{
for (label i=0; i<len; ++i)
auto iter = list.begin();
const auto last = list.end();
// Contents
for (/*nil*/; (iter != last); (void)++iter)
{
is >> list[i];
is >> *iter;
is.fatalCheck
(

View File

@ -282,12 +282,12 @@ Foam::List<T>::List(std::initializer_list<T> list)
template<class T>
Foam::List<T>::List(List<T>&& list)
Foam::List<T>::List(List<T>&& list) noexcept
:
UList<T>()
UList<T>(list.data(), list.size())
{
// Can use transfer or swap to manage content
transfer(list);
list.size_ = 0;
list.v_ = nullptr;
}
@ -351,12 +351,13 @@ template<class T>
template<int SizeMin>
void Foam::List<T>::transfer(DynamicList<T, SizeMin>& list)
{
// Shrink the allocated space to the number of elements used
list.shrink();
transfer(static_cast<List<T>&>(list));
// Remove existing contents before anything else.
clear();
// Ensure DynamicList has proper capacity=0 too
list.clearStorage();
// Shrink the allocated space to the number of elements used
list.shrink_to_fit();
transfer(static_cast<List<T>&>(list));
list.clearStorage(); // Deletion, capacity=0 etc.
}

View File

@ -115,9 +115,6 @@ class List
// Methods as per DynamicList to simplify code maintenance
//- Stub method for internal naming as per DynamicList
label capacity() const noexcept { return UList<T>::size(); }
//- Stub method for internal naming as per DynamicList
void setCapacity_nocopy(const label len) { resize_nocopy(len); }
@ -190,7 +187,7 @@ public:
List(std::initializer_list<T> list);
//- Move construct from List
List(List<T>&& list);
List(List<T>&& list) noexcept;
//- Move construct from DynamicList
template<int SizeMin>
@ -230,6 +227,13 @@ public:
// Otherwise the contents will be uninitialized.
inline void resize_nocopy(const label len);
//- Change the addressed list size directly without affecting
//- any memory management (advanced usage).
//
// It is left to the caller to avoid \em unsafe lengthening beyond
// the allocated memory region.
inline void resize_unsafe(const label len) noexcept;
//- Alias for resize()
void setSize(const label n) { this->resize(n); }
@ -289,7 +293,7 @@ public:
// Member Operators
//- Assignment to UList operator. Takes linear time
void operator=(const UList<T>& a);
void operator=(const UList<T>& list);
//- Assignment operator. Takes linear time
void operator=(const List<T>& list);
@ -410,11 +414,6 @@ public:
// * * * * * * * * * * * * Template Specializations * * * * * * * * * * * * //
//- Specialized list reading for character lists which always uses
//- binary format.
template<>
Istream& List<char>::readList(Istream& is);
//- Hashing for List data
template<class T>
struct Hash<List<T>> : List<T>::hasher {};

View File

@ -185,6 +185,13 @@ inline void Foam::List<T>::resize_nocopy(const label len)
}
template<class T>
inline void Foam::List<T>::resize_unsafe(const label len) noexcept
{
UList<T>::setAddressableSize(len);
}
template<class T>
inline T& Foam::List<T>::newElmt(const label i)
{

View File

@ -222,6 +222,25 @@ Foam::Istream& Foam::List<T>::readList(Istream& is)
);
}
}
else if (std::is_same<char, typename std::remove_cv<T>::type>::value)
{
// Special treatment for char data (binary I/O only)
const auto oldFmt = is.format(IOstreamOption::BINARY);
if (len)
{
// read(...) includes surrounding start/end delimiters
is.read(list.data_bytes(), list.size_bytes());
is.fatalCheck
(
"List<char>::readList(Istream&) : "
"reading binary block"
);
}
is.format(oldFmt);
}
else
{
// Begin of contents marker
@ -231,9 +250,13 @@ Foam::Istream& Foam::List<T>::readList(Istream& is)
{
if (delimiter == token::BEGIN_LIST)
{
for (label i=0; i<len; ++i)
auto iter = list.begin();
const auto last = list.end();
// Contents
for (/*nil*/; (iter != last); (void)++iter)
{
is >> list[i];
is >> *iter;
is.fatalCheck
(

View File

@ -83,7 +83,7 @@ public:
SubList() noexcept = default;
//- Copy construct, shallow copy
SubList(const SubList&) noexcept = default;
SubList(const SubList<T>&) noexcept = default;
// Constructors
@ -93,21 +93,21 @@ public:
//- Construct from FixedList, the entire size
template<unsigned N>
inline explicit SubList(const FixedList<T, N>& list);
inline explicit SubList(const FixedList<T, N>& list) noexcept;
//- Construct from UList and sub-list size, start at 0
inline SubList
(
const UList<T>& list,
const label subSize
const label len
);
//- Construct from UList, sub-list size and start index
inline SubList
(
const UList<T>& list,
const label subSize,
const label startIndex
const label len,
const label start
);
//- Construct from UList and a (start,size) range.
@ -119,8 +119,8 @@ public:
const labelRange& range
);
//- Construct from UList and a (start,size) range, but bypassing
//- run-time range checking.
//- Construct from UList and a (start,size) range,
//- but bypassing run-time range checking.
inline SubList
(
const labelRange& range,
@ -140,15 +140,15 @@ public:
inline UList<T>& reset
(
const UList<T>& list,
const label subSize
const label len
);
//- Reset to use UList with sub-list size and start index
inline UList<T>& reset
(
const UList<T>& list,
const label subSize,
const label startIndex
const label len,
const label start
);
//- Reset to use UList with a (start,size) range.

View File

@ -54,9 +54,9 @@ template<unsigned N>
inline Foam::SubList<T>::SubList
(
const FixedList<T, N>& list
)
) noexcept
:
UList<T>(const_cast<T*>(list.cdata()), static_cast<label>(N))
UList<T>(const_cast<T*>(list.cdata()), list.size())
{}
@ -64,13 +64,13 @@ template<class T>
inline Foam::SubList<T>::SubList
(
const UList<T>& list,
const label subSize
const label len
)
:
UList<T>(const_cast<T*>(list.cdata()), subSize)
UList<T>(const_cast<T*>(list.cdata()), len)
{
#ifdef FULLDEBUG
list.checkSize(subSize);
list.checkSize(len);
#endif
}
@ -79,14 +79,14 @@ template<class T>
inline Foam::SubList<T>::SubList
(
const UList<T>& list,
const label subSize,
const label startIndex
const label len,
const label start
)
:
UList<T>(const_cast<T*>(list.cdata() + startIndex), subSize)
UList<T>(const_cast<T*>(list.cdata() + start), len)
{
#ifdef FULLDEBUG
list.checkRange(startIndex, subSize);
list.checkRange(start, len);
#endif
}
@ -144,14 +144,14 @@ template<class T>
inline Foam::UList<T>& Foam::SubList<T>::reset
(
const UList<T>& list,
const label subSize
const label len
)
{
#ifdef FULLDEBUG
list.checkSize(subSize);
list.checkSize(len);
#endif
UList<T>::shallowCopy(const_cast<T*>(list.cdata()), subSize);
UList<T>::shallowCopy(const_cast<T*>(list.cdata()), len);
return *this;
}
@ -160,18 +160,18 @@ template<class T>
inline Foam::UList<T>& Foam::SubList<T>::reset
(
const UList<T>& list,
const label subSize,
const label startIndex
const label len,
const label start
)
{
#ifdef FULLDEBUG
list.checkRange(startIndex, subSize);
list.checkRange(start, len);
#endif
UList<T>::shallowCopy
(
const_cast<T*>(list.cdata() + startIndex),
subSize
const_cast<T*>(list.cdata() + start),
len
);
return *this;
}

View File

@ -482,9 +482,12 @@ public:
//- True if List is empty (ie, size() is zero)
bool empty() const noexcept { return !size_; }
//- The number of elements in the List
//- The number of elements in the container
label size() const noexcept { return size_; }
//- Size of the underlying storage.
label capacity() const noexcept { return size_; }
//- The size of the largest possible UList
static constexpr label max_size() noexcept { return labelMax; }
@ -497,22 +500,22 @@ public:
//- Equality operation on ULists of the same type.
// Returns true when the ULists are element-wise equal
// (using UList::value_type::operator==). Takes linear time
bool operator==(const UList<T>& a) const;
bool operator==(const UList<T>& list) const;
//- The opposite of the equality operation. Takes linear time
bool operator!=(const UList<T>& a) const;
bool operator!=(const UList<T>& list) const;
//- Compare two ULists lexicographically. Takes linear time
bool operator<(const UList<T>& list) const;
//- Compare two ULists lexicographically. Takes linear time
bool operator>(const UList<T>& a) const;
bool operator>(const UList<T>& list) const;
//- Return true if !(a > b). Takes linear time
bool operator<=(const UList<T>& a) const;
bool operator<=(const UList<T>& list) const;
//- Return true if !(a < b). Takes linear time
bool operator>=(const UList<T>& a) const;
bool operator>=(const UList<T>& list) const;
// Reading/writing
@ -640,19 +643,10 @@ public:
// * * * * * * * * * * * * Template Specializations * * * * * * * * * * * * //
//- Specialized list reading for character lists which always uses
//- binary format.
template<>
Istream& UList<char>::readList(Istream& is);
//- Character list writeEntry - always uses binary format.
//- Character list writeEntry
template<>
void UList<char>::writeEntry(Ostream& os) const;
//- Character list writeList - always uses binary format.
template<>
Ostream& UList<char>::writeList(Ostream& os, const label /*unused*/) const;
//- Character list assign zero - avoids Foam::zero casting ambiguities
template<>
void UList<char>::operator=(const Foam::zero);

View File

@ -46,15 +46,20 @@ void Foam::UList<T>::writeEntry(Ostream& os) const
{
os << *this;
}
else if (os.format() == IOstreamOption::ASCII)
else if
(
os.format() == IOstreamOption::BINARY
|| std::is_same<char, typename std::remove_cv<T>::type>::value
)
{
// Zero-sized ASCII - Write size and delimiters
os << 0 << token::BEGIN_LIST << token::END_LIST;
// Zero-sized binary - Write size only
// NB: special treatment for char data (binary I/O only)
os << label(0);
}
else
{
// Zero-sized binary - Write size only
os << 0;
// Zero-sized ASCII - Write size and delimiters
os << label(0) << token::BEGIN_LIST << token::END_LIST;
}
}
@ -96,7 +101,22 @@ Foam::Ostream& Foam::UList<T>::writeList
os.write(list.cdata_bytes(), list.size_bytes());
}
}
else if (len > 1 && is_contiguous<T>::value && list.uniform())
else if (std::is_same<char, typename std::remove_cv<T>::type>::value)
{
// Special treatment for char data (binary I/O only)
const auto oldFmt = os.format(IOstreamOption::BINARY);
os << nl << len << nl;
if (len)
{
// write(...) includes surrounding start/end delimiters
os.write(list.cdata_bytes(), list.size_bytes());
}
os.format(oldFmt);
}
else if (is_contiguous<T>::value && len > 1 && list.uniform())
{
// Two or more entries, and all entries have identical values.
os << len << token::BEGIN_BLOCK << list[0] << token::END_BLOCK;
@ -120,11 +140,18 @@ Foam::Ostream& Foam::UList<T>::writeList
// Size and start delimiter
os << len << token::BEGIN_LIST;
auto iter = list.cbegin();
const auto last = list.cend();
// Contents
for (label i=0; i < len; ++i)
if (iter != last)
{
if (i) os << token::SPACE;
os << list[i];
os << *iter;
for (++iter; (iter != last); (void)++iter)
{
os << token::SPACE << *iter;
}
}
// End delimiter
@ -135,16 +162,19 @@ Foam::Ostream& Foam::UList<T>::writeList
// Multi-line output
// Size and start delimiter
os << nl << len << nl << token::BEGIN_LIST << nl;
os << nl << len << nl << token::BEGIN_LIST;
auto iter = list.cbegin();
const auto last = list.cend();
// Contents
for (label i=0; i < len; ++i)
for (/*nil*/; (iter != last); (void)++iter)
{
os << list[i] << nl;
os << nl << *iter;
}
// End delimiter
os << token::END_LIST << nl;
os << nl << token::END_LIST << nl;
}
os.check(FUNCTION_NAME);
@ -224,6 +254,25 @@ Foam::Istream& Foam::UList<T>::readList(Istream& is)
);
}
}
else if (std::is_same<char, typename std::remove_cv<T>::type>::value)
{
// Special treatment for char data (binary I/O only)
const auto oldFmt = is.format(IOstreamOption::BINARY);
if (len)
{
// read(...) includes surrounding start/end delimiters
is.read(list.data_bytes(), list.size_bytes());
is.fatalCheck
(
"UList<char>::readList(Istream&) : "
"reading binary block"
);
}
is.format(oldFmt);
}
else
{
// Begin of contents marker

View File

@ -85,8 +85,12 @@ public:
//- Move construct
inline PtrDynList(PtrDynList<T, SizeMin>&& list);
//- Move construct with different sizing parameters
template<int AnySizeMin>
inline PtrDynList(PtrDynList<T, AnySizeMin>&& list);
//- Move construct from PtrList
inline PtrDynList(PtrList<T>&& list);
inline PtrDynList(PtrList<T>&& list) noexcept;
//- Take ownership of pointers in the list, set old pointers to null.
inline explicit PtrDynList(UList<T*>& list);
@ -121,12 +125,16 @@ public:
//- Clear the list and delete storage.
inline void clearStorage();
//- Expand the addressable size to fit the allocated capacity.
// Returns the previous addressable size.
inline label expandStorage() noexcept;
//- Shrink the allocated space to the number of elements used.
inline void shrink();
inline void shrink_to_fit();
//- Shrink the internal bookkeeping of the allocated space to the
//- number of addressed elements without affecting allocation.
// \note when empty() it will delete any allocated memory.
inline void shrink_unsafe();
//- Calls shrink_to_fit()
void shrink() { shrink_to_fit(); }
// Edit
@ -136,9 +144,12 @@ public:
// \return the number of non-null entries
inline label squeezeNull();
//- Swap with plain PtrList content. Implies shrink_to_fit().
inline void swap(PtrList<T>& list);
//- Swap content, independent of sizing parameter
template<int AnySizeMin>
inline void swap(PtrDynList<T, AnySizeMin>& other);
inline void swap(PtrDynList<T, AnySizeMin>& other) noexcept;
//- Transfer contents of the argument PtrList into this.
inline void transfer(PtrList<T>& list);

View File

@ -67,9 +67,29 @@ inline Foam::PtrDynList<T, SizeMin>::PtrDynList
)
:
PtrList<T>(std::move(list)),
capacity_(list.capacity_)
capacity_(list.capacity())
{
list.clearStorage();
// FUTURE:
// list.setCapacity_unsafe(0); // Same as shrink_unsafe() but noexcept
list.clearStorage(); // capacity=0 etc.
}
template<class T, int SizeMin>
template<int AnySizeMin>
inline Foam::PtrDynList<T, SizeMin>::PtrDynList
(
PtrDynList<T, AnySizeMin>&& list
)
:
PtrList<T>(std::move(list)),
capacity_(list.capacity())
{
// FUTURE:
// list.setCapacity_unsafe(0); // Same as shrink_unsafe() but noexcept
list.clearStorage(); // capacity=0 etc.
}
@ -77,7 +97,7 @@ template<class T, int SizeMin>
inline Foam::PtrDynList<T, SizeMin>::PtrDynList
(
PtrList<T>&& list
)
) noexcept
:
PtrList<T>(std::move(list)),
capacity_(PtrList<T>::size())
@ -177,32 +197,31 @@ inline void Foam::PtrDynList<T, SizeMin>::clearStorage()
template<class T, int SizeMin>
inline Foam::label Foam::PtrDynList<T, SizeMin>::expandStorage() noexcept
{
const label currLen = PtrList<T>::size();
// Allow addressing into the entire list
PtrList<T>::setAddressableSize(capacity_);
return currLen;
}
template<class T, int SizeMin>
inline void Foam::PtrDynList<T, SizeMin>::shrink()
inline void Foam::PtrDynList<T, SizeMin>::shrink_to_fit()
{
const label currLen = PtrList<T>::size();
if (currLen < capacity_)
{
// Adjust addressable size to trigger proper resizing
PtrList<T>::setAddressableSize(currLen+1);
PtrList<T>::resize(currLen);
capacity_ = PtrList<T>::size();
}
}
template<class T, int SizeMin>
inline void Foam::PtrDynList<T, SizeMin>::shrink_unsafe()
{
if (PtrList<T>::empty())
{
// Delete empty list
PtrList<T>::clear();
}
capacity_ = PtrList<T>::size();
}
template<class T, int SizeMin>
inline Foam::label Foam::PtrDynList<T, SizeMin>::squeezeNull()
{
@ -212,12 +231,35 @@ inline Foam::label Foam::PtrDynList<T, SizeMin>::squeezeNull()
}
template<class T, int SizeMin>
inline void Foam::PtrDynList<T, SizeMin>::swap(PtrList<T>& list)
{
if
(
static_cast<const PtrList<T>*>(this)
== static_cast<const PtrList<T>*>(&list)
)
{
return; // Self-swap is a no-op
}
// Remove unused storage
this->shrink_to_fit();
// Swap storage and addressable size
UPtrList<T>::swap(list);
// Update capacity
capacity_ = PtrList<T>::size();
}
template<class T, int SizeMin>
template<int AnySizeMin>
inline void Foam::PtrDynList<T, SizeMin>::swap
(
PtrDynList<T, AnySizeMin>& other
)
) noexcept
{
if
(
@ -248,9 +290,8 @@ inline void Foam::PtrDynList<T, SizeMin>::transfer(PtrList<T>& list)
return; // Self assignment is a no-op
}
// Take over storage, clear addressing for list
capacity_ = list.size();
PtrList<T>::transfer(list);
capacity_ = PtrList<T>::size();
}
@ -270,10 +311,11 @@ inline void Foam::PtrDynList<T, SizeMin>::transfer
return; // Self assignment is a no-op
}
// Take over storage as-is (without shrink, without using SizeMin)
// Take over storage as-is (without shrink)
capacity_ = list.capacity();
PtrList<T>::transfer(list);
list.clearStorage(); // Ensure capacity=0
PtrList<T>::transfer(static_cast<PtrList<T>&>(list));
list.clearStorage(); // capacity=0 etc.
}
@ -496,7 +538,7 @@ template<class T, int SizeMin>
inline void Foam::PtrDynList<T, SizeMin>::reorder(const labelUList& oldToNew)
{
// Shrinking first is a bit annoying, but saves needing a special version.
shrink();
this->shrink_to_fit();
PtrList<T>::reorder(oldToNew);
}

View File

@ -93,7 +93,7 @@ public:
inline PtrList(const PtrList<T>& list);
//- Move construct
inline PtrList(PtrList<T>&& list);
inline PtrList(PtrList<T>&& list) noexcept;
//- Take ownership of pointers in the list, set old pointers to null.
inline explicit PtrList(UList<T*>& list);

View File

@ -54,7 +54,7 @@ inline Foam::PtrList<T>::PtrList(const PtrList<T>& list)
template<class T>
inline Foam::PtrList<T>::PtrList(PtrList<T>&& list)
inline Foam::PtrList<T>::PtrList(PtrList<T>&& list) noexcept
:
UPtrList<T>(std::move(list))
{}

View File

@ -81,7 +81,7 @@ public:
inline PtrListDetail(const PtrListDetail<T>& list);
//- Move construct
inline PtrListDetail(PtrListDetail<T>&& list);
inline PtrListDetail(PtrListDetail<T>&& list) noexcept;
//- Copy or move (reuse) construct as specified
inline PtrListDetail(PtrListDetail<T>& list, bool reuse);

View File

@ -57,7 +57,7 @@ inline Foam::Detail::PtrListDetail<T>::PtrListDetail
const PtrListDetail<T>& list
)
:
List<T*>(list)
List<T*>(static_cast<const List<T*>&>(list))
{}
@ -65,9 +65,9 @@ template<class T>
inline Foam::Detail::PtrListDetail<T>::PtrListDetail
(
PtrListDetail<T>&& list
)
) noexcept
:
List<T*>(std::move(list))
List<T*>(std::move(static_cast<List<T*>&>(list)))
{}
@ -78,7 +78,7 @@ inline Foam::Detail::PtrListDetail<T>::PtrListDetail
bool reuse
)
:
List<T*>(list, reuse)
List<T*>(static_cast<List<T*>&>(list), reuse)
{}

View File

@ -124,7 +124,7 @@ protected:
// Constructors
//- Low-level move construct
inline explicit UPtrList(Detail::PtrListDetail<T>&& ptrs);
inline explicit UPtrList(Detail::PtrListDetail<T>&& ptrs) noexcept;
public:
@ -216,7 +216,7 @@ public:
// Constructors
//- Default construct
inline constexpr UPtrList() noexcept;
constexpr UPtrList() noexcept = default;
//- Construct with specified size and set all entries to \c nullptr
inline explicit UPtrList(const label len);
@ -225,7 +225,7 @@ public:
inline UPtrList(const UPtrList<T>& list);
//- Move construct
inline UPtrList(UPtrList<T>&& list);
inline UPtrList(UPtrList<T>&& list) noexcept;
//- Construct as shallow copy or re-use as specified
inline UPtrList(UPtrList<T>& list, bool reuse);
@ -254,6 +254,9 @@ public:
//- The number of entries in the list
inline label size() const noexcept;
//- Size of the underlying storage.
inline label capacity() const noexcept;
//- The number of non-null entries in the list
inline label count() const noexcept;
@ -322,7 +325,7 @@ public:
inline void push_back(UPtrList<T>&& other);
//- Swap content
inline void swap(UPtrList<T>& list);
inline void swap(UPtrList<T>& list) noexcept;
//- Transfer contents into this list and annul the argument
inline void transfer(UPtrList<T>& list);

View File

@ -44,13 +44,6 @@ inline Foam::label Foam::UPtrList<T>::find_next(label pos) const
// * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * * //
template<class T>
inline constexpr Foam::UPtrList<T>::UPtrList() noexcept
:
ptrs_()
{}
template<class T>
inline Foam::UPtrList<T>::UPtrList(const label len)
:
@ -59,7 +52,7 @@ inline Foam::UPtrList<T>::UPtrList(const label len)
template<class T>
inline Foam::UPtrList<T>::UPtrList(Detail::PtrListDetail<T>&& ptrs)
inline Foam::UPtrList<T>::UPtrList(Detail::PtrListDetail<T>&& ptrs) noexcept
:
ptrs_(std::move(ptrs))
{}
@ -73,7 +66,7 @@ inline Foam::UPtrList<T>::UPtrList(const UPtrList<T>& list)
template<class T>
inline Foam::UPtrList<T>::UPtrList(UPtrList<T>&& list)
inline Foam::UPtrList<T>::UPtrList(UPtrList<T>&& list) noexcept
:
ptrs_(std::move(list.ptrs_))
{}
@ -123,6 +116,13 @@ inline Foam::label Foam::UPtrList<T>::size() const noexcept
}
template<class T>
inline Foam::label Foam::UPtrList<T>::capacity() const noexcept
{
return ptrs_.capacity();
}
template<class T>
inline Foam::label Foam::UPtrList<T>::count() const noexcept
{
@ -213,7 +213,7 @@ inline void Foam::UPtrList<T>::free()
template<class T>
inline void Foam::UPtrList<T>::swap(UPtrList<T>& list)
inline void Foam::UPtrList<T>::swap(UPtrList<T>& list) noexcept
{
ptrs_.swap(list.ptrs_);
}

View File

@ -307,6 +307,15 @@ public:
const word& name
);
//- Create scope:name1:name2 or scope_name1_name2 string
// An empty scope is ignored.
static inline word scopedName
(
const std::string& scope,
const word& name1,
const word& name2
);
//- Return the IOobject, but also consider an alternative file name.
//
// \param io The expected IOobject to use
@ -341,7 +350,7 @@ public:
// Constructors
//- Construct from name, instance, registry, io options
// (default: NO_READ, NO_WRITE, register, non-global)
// (default: NO_READ, NO_WRITE, REGISTER, non-global)
IOobject
(
const word& name,
@ -351,7 +360,7 @@ public:
);
//- Construct from name, instance, local, registry, io options
// (default: NO_READ, NO_WRITE, register, non-global)
// (default: NO_READ, NO_WRITE, REGISTER, non-global)
IOobject
(
const word& name,
@ -362,7 +371,7 @@ public:
);
//- Construct from path, registry, io options.
// (default: NO_READ, NO_WRITE, register, non-global)
// (default: NO_READ, NO_WRITE, REGISTER, non-global)
//
// Uses fileNameComponents() to split path into components.
// A path that starts with a '/' is regarded as a file system path.

View File

@ -54,7 +54,40 @@ inline Foam::word Foam::IOobject::scopedName
return name;
}
return scope + (IOobject::scopeSeparator + name);
word output;
output.reserve(scope.size() + name.size() + 1);
output += scope;
output += IOobject::scopeSeparator;
output += name;
return output;
}
inline Foam::word Foam::IOobject::scopedName
(
const std::string& scope,
const word& name1,
const word& name2
)
{
if (scope.empty())
{
return IOobject::scopedName(name1, name2);
}
word output;
output.reserve(scope.size() + name1.size() + name2.size() + 2);
output += scope;
output += IOobject::scopeSeparator;
output += name1;
if (!name2.empty())
{
output += IOobject::scopeSeparator;
output += name2;
}
return output;
}

View File

@ -168,13 +168,13 @@ public:
// Constructors
//- Default construct (empty) with default (128) table capacity
IOobjectList() = default;
//- Default construct: empty without allocation (capacity=0).
IOobjectList() noexcept = default;
//- Construct with zero table capacity
//- Construct empty without allocation (capacity=0)
inline explicit IOobjectList(const Foam::zero) noexcept;
//- Construct given initial table capacity
//- Construct empty with initial table capacity
inline explicit IOobjectList(const label initialCapacity);
//- Copy construct

View File

@ -103,6 +103,76 @@ Foam::decomposedBlockData::decomposedBlockData
// * * * * * * * * * * * * * * * Members Functions * * * * * * * * * * * * * //
std::streamoff Foam::decomposedBlockData::writeBlockEntry
(
OSstream& os,
const label blocki,
const char* str,
const size_t len
)
{
// Offset to the beginning of this output
// This should generally be OK for non-compressed streams
// (eg, std::ofstream)
std::streamoff blockOffset = os.stdStream().tellp();
const word procName("processor" + Foam::name(blocki));
// Write as commented content
// ----------------
// // processorN
// NCHARS
// (...)
// ----------------
{
os << nl << "// " << procName << nl;
if (str && len > 0)
{
// Special treatment for char data (binary I/O only)
const auto oldFmt = os.format(IOstreamOption::BINARY);
os << label(len) << nl;
os.write(str, len);
os << nl;
os.format(oldFmt);
}
else
{
os << label(0) << nl;
}
}
// Write as primitiveEntry
// {
// // Like writeKeyword()
// os << nl << procName << nl;
//
// if (str && len > 0)
// {
// // Special treatment for char data (binary I/O only)
// const auto oldFmt = os.format(IOstreamOption::BINARY);
//
// os << label(len) << nl;
// os.write(str, len);
// os << nl;
//
// os.format(oldFmt);
// }
// else
// {
// os << label(0) << nl;
// }
//
// os.endEntry();
// }
return blockOffset;
}
bool Foam::decomposedBlockData::readBlockEntry
(
Istream& is,
@ -149,7 +219,7 @@ bool Foam::decomposedBlockData::readBlockEntry
bool Foam::decomposedBlockData::skipBlockEntry(Istream& is)
{
// As per readBlockEntry but seeks instead of reading.
// Internals like charList::readList
// Internals like charList::readList - ie, always binary
// Handle any of these:
// 0. NCHARS (...)
@ -184,19 +254,17 @@ bool Foam::decomposedBlockData::skipBlockEntry(Istream& is)
const label len = tok.labelToken();
// Binary, always contiguous
// Special treatment for char data (binary I/O only)
const auto oldFmt = is.format(IOstreamOption::BINARY);
if (len)
{
const auto oldFmt = is.format(IOstreamOption::BINARY);
// read(...) includes surrounding start/end delimiters.
// Note: nullptr to seek instead of reading
// Note: nullptr to ignore instead of reading
is.read(nullptr, std::streamsize(len));
is.format(oldFmt);
}
is.format(oldFmt);
handled = true;
}
@ -288,52 +356,6 @@ bool Foam::decomposedBlockData::hasBlock(Istream& is, const label blockNumber)
}
std::streamoff Foam::decomposedBlockData::writeBlockEntry
(
OSstream& os,
const label blocki,
const UList<char>& charData
)
{
// Offset to the beginning of this output
std::streamoff blockOffset = os.stdStream().tellp();
const word procName("processor" + Foam::name(blocki));
// Write as commented content
{
os << nl << "// " << procName << nl;
charData.writeList(os) << nl;
}
// Write as primitiveEntry
// {
// os << nl << procName << nl;
// charData.writeList(os);
// os.endEntry();
// }
return blockOffset;
}
std::streamoff Foam::decomposedBlockData::writeBlockEntry
(
OSstream& os,
const label blocki,
const std::string& content
)
{
UList<char> charData
(
const_cast<char*>(content.data()),
label(content.size())
);
return decomposedBlockData::writeBlockEntry(os, blocki, charData);
}
std::streamoff Foam::decomposedBlockData::writeBlockEntry
(
OSstream& os,

View File

@ -261,16 +261,31 @@ public:
(
OSstream& os,
const label blocki,
const UList<char>& charData
const char* str,
const size_t len
);
//- Helper: write block of (binary) character data
static std::streamoff writeBlockEntry
(
OSstream& os,
const label blocki,
const UList<char>& s
)
{
return writeBlockEntry(os, blocki, s.cdata(), s.size_bytes());
}
//- Helper: write block of (binary) character content
static std::streamoff writeBlockEntry
(
OSstream& os,
const label blocki,
const std::string& content
);
const std::string& s
)
{
return writeBlockEntry(os, blocki, s.data(), s.size());
}
//- Helper: write block of (binary) character data
// \return -1 on error

View File

@ -105,20 +105,20 @@ public:
// STL stream
//- Access to underlying std::istream
virtual std::istream& stdStream();
virtual std::istream& stdStream() override;
//- Const access to underlying std::istream
virtual const std::istream& stdStream() const;
virtual const std::istream& stdStream() const override;
//- Rewind the stream so that it may be read again.
// Includes special handling for compressed streams.
virtual void rewind();
virtual void rewind() override;
// Print
//- Print stream description
virtual void print(Ostream& os) const;
virtual void print(Ostream& os) const override;
// Member Operators

View File

@ -6,7 +6,7 @@
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2011-2017 OpenFOAM Foundation
Copyright (C) 2017-2022 OpenCFD Ltd.
Copyright (C) 2017-2023 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
@ -130,11 +130,11 @@ public:
// STL stream
//- Access to underlying std::ostream
virtual std::ostream& stdStream();
//- Const access to underlying std::ostream
virtual const std::ostream& stdStream() const;
virtual const std::ostream& stdStream() const override;
//- Access to underlying std::ostream
virtual std::ostream& stdStream() override;
//- Rewind the stream so that it may be written again.
//- Reopens the file (truncation)
@ -144,7 +144,7 @@ public:
// Print
//- Print stream description
void print(Ostream& os) const;
void print(Ostream& os) const override;
// Additional constructors and methods

View File

@ -6,7 +6,7 @@
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2011-2016 OpenFOAM Foundation
Copyright (C) 2016-2019 OpenCFD Ltd.
Copyright (C) 2016-2023 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
@ -48,16 +48,26 @@ void Foam::Ostream::decrIndent()
}
Foam::Ostream& Foam::Ostream::writeQuoted
(
const std::string& str,
const bool quoted
)
{
return writeQuoted(str.data(), str.size(), quoted);
}
Foam::Ostream& Foam::Ostream::write(const keyType& kw)
{
return writeQuoted(kw, kw.isPattern());
return writeQuoted(kw.data(), kw.size(), kw.isPattern());
}
Foam::Ostream& Foam::Ostream::writeKeyword(const keyType& kw)
{
indent();
writeQuoted(kw, kw.isPattern());
writeQuoted(kw.data(), kw.size(), kw.isPattern());
if (indentSize_ <= 1)
{
@ -86,7 +96,7 @@ Foam::Ostream& Foam::Ostream::writeKeyword(const keyType& kw)
Foam::Ostream& Foam::Ostream::beginBlock(const keyType& kw)
{
indent(); writeQuoted(kw, kw.isPattern()); write('\n');
indent(); writeQuoted(kw.data(), kw.size(), kw.isPattern()); write('\n');
beginBlock();
return *this;

View File

@ -6,7 +6,7 @@
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2011-2016 OpenFOAM Foundation
Copyright (C) 2016-2022 OpenCFD Ltd.
Copyright (C) 2016-2023 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
@ -41,6 +41,7 @@ SourceFiles
#include "IOstream.H"
#include "keyType.H"
#include "stdFoam.H" // For span etc.
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
@ -118,28 +119,35 @@ public:
//- Write character
virtual Ostream& write(const char c) = 0;
//- Write character/string content, with/without surrounding quotes
virtual Ostream& writeQuoted
(
const char* str,
std::streamsize len,
const bool quoted=true
) = 0;
//- Write string content, with/without surrounding quotes
virtual Ostream& writeQuoted
(
const std::string& str,
const bool quoted=true
);
//- Write character string
virtual Ostream& write(const char* str) = 0;
//- Write word
//- Write word (unquoted)
virtual Ostream& write(const word& str) = 0;
//- Write string content (usually quoted)
virtual Ostream& write(const std::string& str) = 0;
//- Write keyType
// A plain word is written unquoted.
// A regular expression is written as a quoted string.
virtual Ostream& write(const keyType& kw);
//- Write string
virtual Ostream& write(const string& str) = 0;
//- Write std::string surrounded by quotes.
// Optional write without quotes.
virtual Ostream& writeQuoted
(
const std::string& str,
const bool quoted=true
) = 0;
//- Write int32_t
virtual Ostream& write(const int32_t val) = 0;
@ -317,9 +325,38 @@ public:
};
// --------------------------------------------------------------------
// ------ Manipulators (not taking arguments)
// --------------------------------------------------------------------
// * * * * * * * * * * * * * * * Global Operators * * * * * * * * * * * * * //
#if __cplusplus >= 201703L
//- Write operator for std::string_view
inline Ostream& operator<<(Ostream& os, std::string_view s)
{
os.writeQuoted(s.data(), s.size(), true); // quoted
os.check("Foam::operator<<(Ostream&, std::string_view)");
return os;
}
#endif
//- Write operator for character span. Output like string data
inline Ostream& operator<<(Ostream& os, stdFoam::span<char> s)
{
os.writeQuoted(s.data(), s.size(), true); // quoted
os.check("Foam::operator<<(Ostream&, stdFoam::span<char>)");
return os;
}
//- Write operator for const character span. Output like string data
inline Ostream& operator<<(Ostream& os, stdFoam::span<const char> s)
{
os.writeQuoted(s.data(), s.size(), true); // quoted
os.check("Foam::operator<<(Ostream&, stdFoam::span<const char>)");
return os;
}
/*---------------------------------------------------------------------------*\
Manipulators (without arguments)
\*---------------------------------------------------------------------------*/
//- An Ostream manipulator
typedef Ostream& (*OstreamManip)(Ostream&);

View File

@ -149,77 +149,71 @@ public:
// Member Functions
// Inquiry
// Stream State Functions
//- Return flags of output stream
virtual ios_base::fmtflags flags() const
{
return ios_base::fmtflags(0);
}
//- Return stream flags
virtual ios_base::fmtflags flags() const override
{
return ios_base::fmtflags(0);
}
// Read Functions
//- Return next token from stream
Istream& read(token& t);
//- Read a character
Istream& read(char& c);
//- Read a word
Istream& read(word& str);
// Read a string
Istream& read(string& str);
//- Read a label
Istream& read(label& val);
//- Read a float
Istream& read(float& val);
//- Read a double
Istream& read(double& val);
//- Read binary block with 8-byte alignment.
//- Reading into a null pointer behaves like a forward seek of
//- count characters.
Istream& read(char* data, std::streamsize count);
//- Low-level raw binary read.
//- Reading into a null pointer behaves like a forward seek of
//- count characters.
Istream& readRaw(char* data, std::streamsize count);
//- Start of low-level raw binary read
bool beginRawRead();
//- End of low-level raw binary read
bool endRawRead()
{
return true;
}
// Positioning
//- Rewind the receive stream position so that it may be read again
virtual void rewind();
// Edit
//- Set flags of stream
virtual ios_base::fmtflags flags(const ios_base::fmtflags)
//- Set flags of stream flags
virtual ios_base::fmtflags flags(const ios_base::fmtflags) override
{
return ios_base::fmtflags(0);
}
// Read Functions
//- Return next token from stream
virtual Istream& read(token&) override;
//- Read a character
virtual Istream& read(char& c) override;
//- Read a word
virtual Istream& read(word& str) override;
// Read a string
virtual Istream& read(string& str) override;
//- Read a label
virtual Istream& read(label& val) override;
//- Read a float
virtual Istream& read(float& val) override;
//- Read a double
virtual Istream& read(double& val) override;
//- Read binary block with 8-byte alignment.
//- Reading into a null pointer behaves like a forward seek of
//- count characters.
virtual Istream& read(char* data, std::streamsize count) override;
//- Low-level raw binary read.
//- Reading into a null pointer behaves like a forward seek of
//- count characters.
virtual Istream& readRaw(char* data, std::streamsize count) override;
//- Start of low-level raw binary read
virtual bool beginRawRead() override;
//- End of low-level raw binary read
virtual bool endRawRead() override { return true; }
// Positioning
//- Rewind the receive stream position so that it may be read again
virtual void rewind() override;
// Print
//- Print stream description to Ostream
void print(Ostream& os) const;
void print(Ostream& os) const override;
};

View File

@ -137,7 +137,7 @@ inline void Foam::UIPstreamBase::readFromBuffer
inline Foam::Istream& Foam::UIPstreamBase::readString(std::string& str)
{
// Use std::string::assign() to copy content, including '\0'.
// Use std::string::assign() to copy content, including embedded nul chars.
// Stripping (when desired) is the responsibility of the sending side.
size_t len;

View File

@ -83,8 +83,10 @@ class UOPstreamBase
//- Add a single char to the send buffer. No alignment needed
inline void putChar(const char c);
//- Write string length and string content.
// The content includes the trailing nul char.
//- Write string length and content, including embedded nul chars.
inline void putString(const char* str, const size_t len);
//- Write string length and content, including embedded nul chars.
inline void putString(const std::string& str);
@ -142,124 +144,135 @@ public:
// Member Functions
// Inquiry
// Inquiry
//- Return flags of output stream
virtual ios_base::fmtflags flags() const
{
return ios_base::fmtflags(0);
}
//- Return flags of output stream
virtual ios_base::fmtflags flags() const override
{
return ios_base::fmtflags(0);
}
// Write Functions
// Write Functions
//- Write token to stream or otherwise handle it.
// \return false if the token type was not handled by this method
virtual bool write(const token& tok);
//- Inherit write methods from Ostream
using Ostream::writeQuoted;
//- Write single character. Whitespace is suppressed.
virtual Ostream& write(const char c);
//- Write token to stream or otherwise handle it.
// \return false if the token type was not handled by this method
virtual bool write(const token& tok) override;
//- Write the word-characters of a character string.
// Sends as a single char, or as word.
virtual Ostream& write(const char* str);
//- Write single character. Whitespace is suppressed.
virtual Ostream& write(const char c) override;
//- Write word
virtual Ostream& write(const word& str);
//- Write character/string content, with/without surrounding quotes
virtual Ostream& writeQuoted
(
const char* str,
std::streamsize len,
const bool quoted=true
) override;
//- Write string
virtual Ostream& write(const string& str);
//- Write the word-characters of a character string.
// Sends as a single char, or as word.
virtual Ostream& write(const char* str) override;
//- Write std::string surrounded by quotes.
// Optional write without quotes.
virtual Ostream& writeQuoted
(
const std::string& str,
const bool quoted=true
);
//- Write word
virtual Ostream& write(const word& str) override;
//- Write int32_t as a label
virtual Ostream& write(const int32_t val);
//- Write string
virtual Ostream& write(const std::string& str) override;
//- Write int64_t as a label
virtual Ostream& write(const int64_t val);
//- Write int32_t as a label
virtual Ostream& write(const int32_t val) override;
//- Write float
virtual Ostream& write(const float val);
//- Write int64_t as a label
virtual Ostream& write(const int64_t val) override;
//- Write double
virtual Ostream& write(const double val);
//- Write float
virtual Ostream& write(const float val) override;
//- Write binary block with 8-byte alignment.
virtual Ostream& write(const char* data, std::streamsize count);
//- Write double
virtual Ostream& write(const double val) override;
//- Low-level raw binary output.
virtual Ostream& writeRaw(const char* data, std::streamsize count);
//- Write binary block with 8-byte alignment.
virtual Ostream& write
(
const char* data,
std::streamsize count
) override;
//- Begin marker for low-level raw binary output.
// The count indicates the number of bytes for subsequent
// writeRaw calls.
virtual bool beginRawWrite(std::streamsize count);
//- Low-level raw binary output.
virtual Ostream& writeRaw
(
const char* data,
std::streamsize count
) override;
//- End marker for low-level raw binary output.
virtual bool endRawWrite()
{
return true;
}
//- Begin marker for low-level raw binary output.
// The count indicates the number of bytes for subsequent
// writeRaw calls.
virtual bool beginRawWrite(std::streamsize count) override;
//- Add indentation characters
virtual void indent()
{}
//- End marker for low-level raw binary output.
virtual bool endRawWrite() override
{
return true;
}
//- Add indentation characters
virtual void indent() override
{}
// Stream state functions
// Stream state functions
//- Flush stream
virtual void flush()
{}
//- Flush stream
virtual void flush() override
{}
//- Add newline and flush stream
virtual void endl()
{}
//- Add newline and flush stream
virtual void endl() override
{}
//- Get the current padding character
// \return previous padding character
virtual char fill() const
{
return 0;
}
//- Get the current padding character
// \return previous padding character
virtual char fill() const override
{
return 0;
}
//- Set padding character for formatted field up to field width
virtual char fill(const char)
{
return 0;
}
//- Set padding character for formatted field up to field width
virtual char fill(const char) override
{
return 0;
}
//- Get width of output field
virtual int width() const
{
return 0;
}
//- Get width of output field
virtual int width() const override
{
return 0;
}
//- Set width of output field
// \return previous width
virtual int width(const int)
{
return 0;
}
//- Set width of output field
// \return previous width
virtual int width(const int) override
{
return 0;
}
//- Get precision of output field
virtual int precision() const
{
return 0;
}
//- Get precision of output field
virtual int precision() const override
{
return 0;
}
//- Set precision of output field
// \return old precision
virtual int precision(const int)
{
return 0;
}
//- Set precision of output field
// \return old precision
virtual int precision(const int) override
{
return 0;
}
// Positioning
@ -271,7 +284,7 @@ public:
// Edit
//- Set flags of stream
virtual ios_base::fmtflags flags(const ios_base::fmtflags)
virtual ios_base::fmtflags flags(const ios_base::fmtflags) override
{
return ios_base::fmtflags(0);
}
@ -280,7 +293,7 @@ public:
// Print
//- Print stream description to Ostream
void print(Ostream& os) const;
void print(Ostream& os) const override;
};

View File

@ -121,11 +121,20 @@ inline void Foam::UOPstreamBase::putChar(const char c)
}
inline void Foam::UOPstreamBase::putString
(
const char* str,
const size_t len
)
{
writeToBuffer(len);
writeToBuffer(str, len, 1); // no-op when len == 0
}
inline void Foam::UOPstreamBase::putString(const std::string& str)
{
const size_t len = str.size();
writeToBuffer(len);
writeToBuffer(str.data(), len, 1); // no-op when len == 0
putString(str.data(), str.size());
}
@ -253,6 +262,27 @@ Foam::Ostream& Foam::UOPstreamBase::write(const char c)
}
Foam::Ostream& Foam::UOPstreamBase::writeQuoted
(
const char* str,
std::streamsize len,
const bool quoted
)
{
if (quoted)
{
putChar(token::tokenType::STRING);
}
else
{
putChar(token::tokenType::WORD);
}
putString(str, len);
return *this;
}
Foam::Ostream& Foam::UOPstreamBase::write(const char* str)
{
const word nonWhiteChars(string::validate<word>(str));
@ -279,7 +309,7 @@ Foam::Ostream& Foam::UOPstreamBase::write(const word& str)
}
Foam::Ostream& Foam::UOPstreamBase::write(const string& str)
Foam::Ostream& Foam::UOPstreamBase::write(const std::string& str)
{
putChar(token::tokenType::STRING);
putString(str);
@ -288,26 +318,6 @@ Foam::Ostream& Foam::UOPstreamBase::write(const string& str)
}
Foam::Ostream& Foam::UOPstreamBase::writeQuoted
(
const std::string& str,
const bool quoted
)
{
if (quoted)
{
putChar(token::tokenType::STRING);
}
else
{
putChar(token::tokenType::WORD);
}
putString(str);
return *this;
}
Foam::Ostream& Foam::UOPstreamBase::write(const int32_t val)
{
putChar(token::tokenType::LABEL);

Some files were not shown because too many files have changed in this diff Show More