Small-size-optimized Appender

Per Nordlöw per.nordlow at gmail.com
Fri Oct 16 19:06:33 UTC 2020


Would appreciated feedback on this small-size-optimized Appender

/** Small-Size-Optimized (SSO) `Appender`.
  */
struct SSOAppender(T, size_t smallCapacity)
if (smallCapacity >= 1)
{
     import std.array : Appender;
     import fixed_array : FixedArray;

     void put(T x) @trusted
     {
         if (_isLarge)
             _large.put(x);
         else if (_small.full)
         {
             import std.algorithm.mutation : moveEmplaceAll;
             T[smallCapacity] tmp = void;
             moveEmplaceAll(_small[], tmp[0 .. _small.length]);
             import core.lifetime : emplace;
             emplace!Large(&_large);
             _large.put(tmp[]);
             _large.put(x);
             _isLarge = 1;
         }
         else
             _small.put(x);
     }

     inout(T)[] data() inout return scope
     {
         if (_isLarge)
             return _large.data[];
         else
             return _small[];
     }

private:
     alias Small = FixedArray!(T, smallCapacity);
     alias Large = Appender!(T[]);
     union
     {
         Small _small;
         Large _large;
     }
     bool _isLarge;
}

I can inline `FixedArray` into a static array if wanted. It's 
basically a static array with a length that provides a put API.

Source: 
https://github.com/nordlow/phobos-next/blob/e914975613e9a5153313acf29b1b183326823ca3/src/nxt/sso_appender.d


More information about the Digitalmars-d mailing list