Files CCore/inc/gadget/Len.h CCore/src/gadget/Len.cpp
Len.h contains number of length related types, constants and functions. CCore uses the type ulen to represent a length. This is a substitute for the standard type size_t. ulen is defined in the target header PlatformBase.h. This type is introduced by several reasons:
TextBufLen is a length, used for small text buffers. MaxULen is the maximum value of the type ulen.
const ulen TextBufLen = 256 ; const ulen MaxULen = ulen(-1) ;
To assign a length value you can use user-defined literals with suffixes KByte and MByte:
ulen len1 = 10_KByte ; ulen len2 = 33_MByte ;
There are several functions, used to calculate lengths with the overflow control:
ulen LenAdd(ulen len,ulen extra_len); // return len+extra_len ulen LenAdd(ulen len1,ulen len2,...,ulen lenn); // return len1+len2+...+lenn ulen LenOf(ulen count,ulen size_of,ulen extra=0); // return count*size_of+extra
In case of overflow they call the following guard functions, these functions throw exceptions:
void GuardLenAddOverflow(ulen len,ulen extra_len); void GuardLenOfOverflow(ulen count,ulen size_of,ulen extra);
GuardLen() is another guard function. It ensures the condition len<=maxlen. The function GuardLenFailed() throws an exception.
void GuardLen(ulen len,ulen maxlen); void GuardLenFailed(ulen len,ulen maxlen);
GuardIndex() is a generic guard function, it ensures that index<len. GuardIndexOutOfRange() throws an exception.
void GuardIndex(ulen index,ulen len); void GuardIndexOutOfRange(ulen index,ulen len);
Next functions are alignment functions. The length len is called aligned (on some alignment value A), if it is divisible by A.
constexpr bool NotAligned(ulen len,ulen A=MaxAlign); constexpr ulen Align(ulen len,ulen A=MaxAlign); constexpr ulen AlignDown(ulen len,ulen A=MaxAlign); bool TryAlign(ulen &len,ulen A=MaxAlign);
NotAligned() checks if the argument is not aligned.
Align() aligns the argument up. No overflow check is performed.
AlignDown() aligns the argument down.
TryAlign() tries to align the argument up. If the overflow happens, the return value is false. Otherwise, the return value is true and the first argument is updated with the aligned result.
The second argument of all these functions is an alignment requirement, it must not be equal 0, and defaulted to the MaxAlign value, defined in the target header PlatformBase.h.
The last two functions are DimOf() and Dist():
template <class T,ulen Len> ulen DimOf(T (&)[Len]) { return Len; } template <class T> ulen Dist(const T *from,const T *to) { return ulen(to-from); }
DimOf() returns the length of the array:
C some_array[ArrayLen]; ulen len=DimOf(some_array); // set len to ArrayLen
Dist() returns the distance between two objects from the same array, pointed by pointers:
C some_array[....]; C *ptr1=some_array+index1; C *ptr2=some_array+index2; // index2 >= index1 ulen dist=Dist(ptr1,ptr2); // set dist to index2-index1