- becoming more frequently used and there is no ambiguity in calling
parameters either - identity(label) vs identity(labelUList&).
Provide both int32 and int64 versions.
- changes the addressed list size without affecting list allocation.
Can be useful for the following type of coding pattern:
- pre-allocate a List with some max content length
- populate with some content (likely not the entire pre-allocated size)
- truncate the list to the length of valid content
- process the List
- discard the List
Since the List is being discarded, using resize_unsafe() instead of
resize() avoids an additional allocation with the new size and
copying/moving of the elements.
This programming pattern can also be used when the List is being
returned from a subroutine, and carrying about a bit of unused memory
is less important than avoiding reallocation + copy/move.
If used improperly, it can obviously result in addressing into
unmanaged memory regions (ie, 'unsafe').
ENH: add pTraits and IO for std::int8_t
STYLE: cull some implicitly available includes
- pTraits.H is included by label/scalar etc
- zero.H is included by UList
STYLE: cull redundant forward declarations for Istream/Ostream
- previously returned the range slice as a UList,
but this prevents convenient assignment.
Apply similar handling for Field/SubField
Allows the following
labelRange range(...);
fullList.slice(range) = identity(range.size());
and
fullList.slice(range) = UIndirectList<T>(other, addr);
ENH: create SubList from full FixedList (simplifies interface)
- allow default constructed SubList. Use shallowCopy to 'reset' later
- this constructor was added for similarity with std::vector,
but continues to cause various annoyances.
The main problem is that the templated parameter tends to grab
anything that is not a perfect match for other constructors.
Typically seen with two integers (in 64-bit mode), but various other
cases as well.
If required, the ListOps::create() function provides a lengthier
alternative but one that can also incorporate transformations.
Eg,
pointField pts = ....;
List<scalar> mags
(
List<scalar>::create
(
pts.begin(),
pts.end(),
[](const vector& v){ return magSqr(v); }
);
- additional dummy template parameter to assist with supporting
derived classes. Currently just used for string types, but can be
extended.
- provide hash specialization for various integer types.
Removes the need for any forwarding.
- change default hasher for HashSet/HashTable from 'string::hash'
to `Hash<Key>`. This avoids questionable hashing calls and/or
avoids compiler resolution problems.
For example,
HashSet<label>::hasher and labelHashSet::hasher now both properly
map to Hash<label> whereas previously HashSet<label> would have
persistently mapped to string::hash, which was incorrect.
- standardize internal hashing functors.
Functor name is 'hasher', as per STL set/map and the OpenFOAM
HashSet/HashTable definitions.
Older code had a local templated name, which added unnecessary
clutter and the template parameter was always defaulted.
For example,
Old: `FixedList<label, 3>::Hash<>()`
New: `FixedList<label, 3>::hasher()`
Unchanged: `labelHashSet::hasher()`
Existing `Hash<>` functor namings are still supported,
but deprecated.
- define hasher and Hash specialization for bitSet and PackedList
- add symmetric hasher for 'face'.
Starts with lowest vertex value and walks in the direction
of the next lowest value. This ensures that the hash code is
independent of face orientation and face rotation.
NB:
- some of keys for multiphase handling (eg, phasePairKey)
still use yet another function naming: `hash` and `symmHash`.
This will be targeted for alignment in the future.
ENH: support construction of zero-sized IndirectList
- useful when addressing is to be generated in-place after construction.
Eg,
indirectPrimitivePatch myPatches
(
IndirectList<face>(mesh.faces(), Zero),
mesh.points()
);
labelList& patchFaces = myPatches.addressing();
patchFaces.resize(...);
// populate patchFaces
STYLE: add noexcept for zero/one fields and remove old dependency files
COMP: correct typedefs for geometricOneField, geometricZeroField
- add reverse iterators and replace std::iterator
(deprecated in C++17) with full definitions
- simplify construction of iterators
- construct labelRange from a single single parameter.
This creates a (0,len) range.
- make basic constructors forms constexpr.
Remove unused size checks.
- Derive labelRange from new IntRange template class.
Allows reuse of base functionality with different integral sizes.
Deprecations:
- deprecate labelRange::valid() in favour of using
labelRange::empty() or the bool operator.
For example,
if (range) ... vs older if (range.valid()) ...
DEFEATURE: drop labelRange::null, scalarRange::null static variables
- turned out to be not particularly useful.
Can simply use constexpr contructor forms
DEFEATURE: drop labelRange::identity static method
- simply use the single-parameter constructor
- change contiguous from a series of global functions to separate
templated traits classes:
- is_contiguous
- is_contiguous_label
- is_contiguous_scalar
The static constexpr 'value' and a constexpr conversion operator
allow use in template expressions. The change also makes it much
easier to define general traits and to inherit from them.
The is_contiguous_label and is_contiguous_scalar are special traits
for handling data of homogeneous components of the respective types.
- introduced a ListPolicy details to make the transition between
a short list (space separated) and a long list (newline separated)
more configurable.
We suppress line breaks for commonly used types that often have
short content: (word, wordRes, keyType).
- there were previously no hashing mechanisms for lists so they
would fall back to the definition for primitives and hash the
memory location of the allocated List object.
- provide a UList::Hash<> sub-class for inheritance, and also a global
specialization for UList<T>, List<T> such that the hash value for
List<List<T>> cascades properly.
- provide similar function in triFace to ensure that it remains
similar in behaviour to face.
- added SymmHash to Pair, for use when order is unimportant.
STYLE: use string::hash() more consistently
- no particular reason to use Hash<word>() which forwards to
string::hash() anyhow
- The bitSet class replaces the old PackedBoolList class.
The redesign provides better block-wise access and reduced method
calls. This helps both in cases where the bitSet may be relatively
sparse, and in cases where advantage of contiguous operations can be
made. This makes it easier to work with a bitSet as top-level object.
In addition to the previously available count() method to determine
if a bitSet is being used, now have simpler queries:
- all() - true if all bits in the addressable range are empty
- any() - true if any bits are set at all.
- none() - true if no bits are set.
These are faster than count() and allow early termination.
The new test() method tests the value of a single bit position and
returns a bool without any ambiguity caused by the return type
(like the get() method), nor the const/non-const access (like
operator[] has). The name corresponds to what std::bitset uses.
The new find_first(), find_last(), find_next() methods provide a faster
means of searching for bits that are set.
This can be especially useful when using a bitSet to control an
conditional:
OLD (with macro):
forAll(selected, celli)
{
if (selected[celli])
{
sumVol += mesh_.cellVolumes()[celli];
}
}
NEW (with const_iterator):
for (const label celli : selected)
{
sumVol += mesh_.cellVolumes()[celli];
}
or manually
for
(
label celli = selected.find_first();
celli != -1;
celli = selected.find_next()
)
{
sumVol += mesh_.cellVolumes()[celli];
}
- When marking up contiguous parts of a bitset, an interval can be
represented more efficiently as a labelRange of start/size.
For example,
OLD:
if (isA<processorPolyPatch>(pp))
{
forAll(pp, i)
{
ignoreFaces.set(i);
}
}
NEW:
if (isA<processorPolyPatch>(pp))
{
ignoreFaces.set(pp.range());
}
This class is largely a pre-C++11 holdover. It is now possible to
simply use move construct/assignment directly.
In a few rare cases (eg, polyMesh::resetPrimitives) it has been
replaced by an autoPtr.
- relocated HashSetPlusEqOp and HashTablePlusEqOp to
HashSetOps::plusEqOp and HashTableOps::plusEqOp, respectively
- additional functions for converting between a labelHashSet
and a PackedBoolList or List<bool>:
From lists selections to labelHashSet indices:
HashSetOps::used(const PackedBoolList&);
HashSetOps::used(const UList<bool>&);
From labelHashSet to list forms:
PackedBoolList bitset(const labelHashSet&);
List<bool> bools(const labelHashSet&);
- relocated ListAppendEqOp and ListUniqueEqOp to ListOps::appendEqOp
and ListOps::UniqueEqOp, respectively for better code isolation and
documentation of purpose.
- relocated setValues to ListOps::setValue() with many more
alternative selectors possible
- relocated createWithValues to ListOps::createWithValue
for better code isolation. The default initialization value is itself
now a default parameter, which allow for less typing.
Negative indices in the locations to set are now silently ignored,
which makes it possible to use an oldToNew mapping that includes
negative indices.
- additional ListOps::createWithValue taking a single position to set,
available both in copy assign and move assign versions.
Since a negative index is ignored, it is possible to combine with
the output of List::find() etc.
STYLE: changes for PackedList
- code simplication in the PackedList iterators, including dropping
the unused operator() on iterators, which is not available in plain
list versions either.
- improved sizing for PackedBoolList creation from a labelUList.
ENH: additional List constructors, for handling single element list.
- can assist in reducing constructor ambiguity, but can also helps
memory optimization when creating a single element list.
For example,
labelListList labels(one(), identity(mesh.nFaces()));
- add copy construct from UList
- remove copy construct from dissimilar types.
This templated constructor was too generous in what it accepted.
For the special cases where a copy constructor is required with
a change in the data type, now use the createList factory method,
which accepts a unary operator. Eg,
auto scalars = scalarList::createList
(
labels,
[](const label& val){ return 1.5*val; }
);
- use succincter method names that more closely resemble dictionary
and HashTable method names. This improves method name consistency
between classes and also requires less typing effort:
args.found(optName) vs. args.optionFound(optName)
args.readIfPresent(..) vs. args.optionReadIfPresent(..)
...
args.opt<scalar>(optName) vs. args.optionRead<scalar>(optName)
args.read<scalar>(index) vs. args.argRead<scalar>(index)
- the older method names forms have been retained for code compatibility,
but are now deprecated
- consistent with C++ STL conventions, the reverse iterators should
use operator++ to transit the list from rbegin() to rend().
The previous implementation used raw pointers, which meant that they
had the opposite behaviour: operator-- to transit from rbegin() to
rend().
The updated version only has operator++ defined, thus the compiler
should catch any possible instances where people were using the old
(incorrect) versions.
- updated forAllReverseIters() and forAllConstReverseIters() macros to
be consistent with new implementation and with C++ STL conventions.
- improve functional compatibility with DynList (remove methods)
* eg, remove an element from any position in a DynamicList
* reduce the number of template parameters
* remove/subset regions of DynamicList
- propagate Swap template specializations for lists, hashtables
- move construct/assignment to various containers.
- add find/found methods for FixedList and UList for a more succinct
(and clearer?) usage than the equivalent global findIndex() function.
- simplify List_FOR_ALL loops
- use allocator class to wrap the stream pointers instead of passing
them into ISstream, OSstream and using a dynamic cast to delete
then. This is especially important if we will have a bidirectional
stream (can't delete twice!).
STYLE:
- file stream constructors with std::string (C++11)
- for rewind, explicit about in|out direction. This is not currently
important, but avoids surprises with any future bidirectional access.
- combined string streams in StringStream.H header.
Similar to <sstream> include that has both input and output string
streams.
- inherit from std::iterator to obtain the full STL typedefs, meaning
that std::distance works and the following is now possible:
labelRange range(100, 1500);
scalarList list(range.begin(), range.end());
--
Note that this does not work (mismatched data-types):
scalarList list = identity(12345);
But this does, since the *iter promotes label to scalar:
labelList ident = identity(12345);
scalarList list(ident.begin(), ident.end());
It is however more than slightly wasteful to create a labelList
just for initializing a scalarList. An alternative could be a
a labelRange for the same purpose.
labelRange ident = labelRange::identity(12345);
scalarList list(ident.begin(), ident.end());
Or this
scalarList list
(
labelRange::null.begin(),
labelRange::identity(12345).end()
);
This uses a concept similar to what std::valarray and std::slice do.
A labelRange provides a convenient container for holding start/size
and lends itself to addressing 'sliced' views of lists.
For safety, the operations and constructors restricts the given input range
to a valid addressible region of the underlying list, while the labelRange
itself precludes negative sizes.
The SubList version is useful for patches or other things that have a
SubList as its parameter. Otherwise the UList [] operator will be the
more natural solution. The slices can be done with a labelRange, or
a {start,size} pair.
Examples,
labelList list1 = identity(20);
list1[labelRange(18,10)] = -1;
list1[{-20,25}] = -2;
list1[{1000,5}] = -3;
const labelList list2 = identity(20);
list2[{5,10}] = -3; // ERROR: cannot assign to const!
- Introduce writeList(Ostream&, label) method in various List classes to
provide more flexibility and avoid hard-coded limits when deciding if a
list is too long and should be broken up into multiple lines (ASCII only).
- The old hard-code limit (10) is retained in the operator<< versions
- This functionality is wrapped in the FlatOutput output adapter class
and directly accessible via the 'flatOutput()' function.
Eg,
#include "ListOps.H"
Info<< "methods: " << flatOutput(myLongList) << endl;
// OR
Info<< "methods: ";
myLongList.writeList(os) << endl;
Until C++ supports 'concepts' the only way to support construction from
two iterators is to provide a constructor of the form:
template<class InputIterator>
List(InputIterator first, InputIterator last);
which for some types conflicts with
//- Construct with given size and value for all elements
List(const label, const T&);
e.g. to construct a list of 5 scalars initialized to 0:
List<scalar> sl(5, 0);
causes a conflict because the initialization type is 'int' rather than
'scalar'. This conflict may be resolved by specifying the type of the
initialization value:
List<scalar> sl(5, scalar(0));
The new initializer list contructor provides a convenient and efficient alternative
to using 'IStringStream' to provide an initial list of values:
List<vector> list4(IStringStream("((0 1 2) (3 4 5) (6 7 8))")());
or
List<vector> list4
{
vector(0, 1, 2),
vector(3, 4, 5),
vector(6, 7, 8)
};