Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
October 6, 2022 03:27 am GMT

Much Faster than std::string, fmt::format, std::to_chars, std::time and more?

xeerx C++ Format Library

A super fast c++ library for managing and formatting strings with the ability to convert from/to any type

  • Cross-Platform - tested by Google Test.

  • Speed - faster than std::string, std::time, std::to_chars, {fmt}, .., tested by Google Benchmark.

  • Light - minimum lines of code, quick compiling, tested by GCC 12.

  • optimization - improved behavior to reduce Memory Allocation, tested by Valgrind.

  • Ability - works with a lot of data types any char numbers time bool ..etc.

you will find test, gtest and benchmark for everything in: tests/

Index

The library contains:

Usage

#include "core.h"using namespace xeerx;
  • String

    How It Works

    To understand how strings work, let's see the following examples:

    // [1]xeerx::string s1 ("Hello World");// [2]xeerx::string s2 ("Hello");s2 += "World";// [3]xeerx::string s3 ("chars:");for(int i = 0; i < 100; i++) s3 += 'C';

    Explanation of examples

    • ### First ExampleIn this case the class will just pointing to the value, like std::string_view so there is no copies, just like normal const char*
    • Second Example

      1- pointing to the value Hello

      2- copy Hello to the stack buffer

      3- copy World to the end of stack buffer to be HelloWorld

    • Third Example

      1- pointing to the value chars:

      2- copy chars: to the stack buffer

      now we need to append C x100 times, and our stack buffer size is 64

      and the current size of the buffer is 6 (chars: is 6 characters)

      so the stack can hold more 64 - 6 = 58 characters

      3- copy C 58 times to the end of stack buffer

      now the stack buffer is full and we need to append more 42 characters

      so allocate an enough space in the heap memory called heap buffer

      4- allocate a space in the heap memory

      5- copy contents of stack buffer to the heap buffer

      6- append the rest 42 characters to the end of the heap buffer

    Typedefs

    TypeDefinition
    xeerx::stringxeerx::basic_string<char>
    xeerx::wstringxeerx::basic_string<wchar_t>
    xeerx::u16stringxeerx::basic_string<char16_t>
    xeerx::u32stringxeerx::basic_string<char32_t>
    • ### Specialization Types
    // prototypetemplate<typename Type, class Alloc = std::allocator<Type>, xeerx::size_t L_Capacity = X_BUFF_SIZE>xeerx::basic_string<Type, Alloc, L_Capacity>// example: basic_string for 'char' with local buffer capacity 256typedef xeerx::basic_string<char, std::allocator<char>, 256> string_256;

    There are two types of characters allowed, char and wchar_t.

    But you can use any type of character because the class takes tamplate parameter to know what type of character to use,

    BUT I'm not sure about anything except char and wchar_t so you should try and test it yourself.

    Macros

    NameValueDefinition
    X_BUFF_SIZE64ULdefault size of the local buffer

    Exceptions

    ExceptionDefinition
    std::length_errorwhen the size of the string >= xeex::size_t_max
    std::out_of_rangewhen the index of the string > size()

    Template Parameters

    ParameterDefinition
    Typecharacter type
    AllocAllocator type used to allocate internal storage

    Member Types

    TypeDefinition
    charsxeerx::char_traits<Type>
    value_typeType
    size_type_traits::size_type xeerx::size_t
    reference_traits::reference Type&
    const_reference_traits::const_reference const Type&
    pointer_traits::pointer Type*
    const_pointer_traits::const_pointer const Type*
    iterator_traits::iterator Type*
    const_iterator_traits::const_iterator const Type*

    Member Functions

    • constructor's | destructor

      Examples

      // empty  constructorstring s0;                          //  ""// assign constructor using array of charactersstring s1("Hello");                 //  "Hello"// assign constructor using single character string s2('C');                     //  "C"// assign constructor using range (iterators)string s3(s1.cbegin(), s1.cend());  //  "Hello"// assign constructor using boolstring s4(true);                    //  "true"// assign constructor using integer (see convert function for more details)string s5(123);                     //  "123"// assign constructor using float   (see convert function for more details)string s6(0.14);                    //  "0.14"// copy constructorstring s7(s1);                      //  "Hello"// move constructorstring s8(std::move(s1));           //  "Hello"

      Benchmark

      BenchmarkTimeIterationsSpeedType
      xeerx::string0.976 ns689897792 1.0empty constructor
      std::string0.978 ns704357784
      xeerx::string1.30 ns531657012 2.2copy constructor
      std::string2.93 ns238350514
      xeerx::string1.30 ns532291700 4.7move constructor
      std::string6.15 ns110840133
      xeerx::string1.30 ns473253168 1.7array constructor
      std::string2.26 ns356990635
      xeerx::string1.41 ns427177908 8.0single char constructor
      std::string11.3 ns62462721
      xeerx::string2.45 ns292649634 1.6range constructor
      std::string3.93 ns186850707
      xeerx::string1.97 ns344396141 ---bool constructor
      std::string--- ns---------
      xeerx::string3.02 ns234255879 2.0long int constructor
      std::string6.31 ns109529125
      xeerx::string8.13 ns84837465 2.8short int constructor
      std::string22.9 ns30325927
      xeerx::string2.60 ns267951182 75.3long float constructor
      std::string196 ns3535237
      xeerx::string3.26 ns214303767 61.0short float constructor
      std::string199 ns3511556

      std::to_string can't convert bool to string.

    • Copy | Move | Swap

      Examples

      string s("Hello World");string s1; s1.copy(s);              //  "Hello World"string s2; s2.move(std::move(s));   //  "Hello World"string s3; s3.swap(s);              //  "Hello World"

      Benchmark

      no benchmark need in this section, you can see constructor section to find copy and move benchmark, as about swap is just std::swap.

    • Assign

      Examples

      string s;string s1("Another String");// assign using array of characterss.assign("Hello");                  //  "Hello"// assign using single character s.assign('C');                      //  "C"// assign using range (iterators)s.assign(s1.cbegin(), s1.cend());   //  "Another String"// assign using bools.assign(true);                     //  "true"// assign using integer (see convert function for more details)s.assign(123);                      //  "123"// assign using float   (see convert function for more details)s.assign(0.14);                     //  "0.14"// assign using another strings.assign(s1);                       //  "Another String"

      Benchmark

      BenchmarkTimeIterationsSpeedType
      xeerx::string1.34 ns531380206 2.2assign using string
      std::string2.93 ns238106163
      xeerx::string1.31 ns528827390 6.7assign using array
      std::string8.81 ns78799728
      xeerx::string1.31 ns534289066 8.6assign using single char
      std::string11.3 ns61128346
      xeerx::string2.28 ns306184756 4.3assign using range
      std::string9.90 ns69530909
      xeerx::string1.95 ns357179984 ---assign using bool
      std::string--- ns---------
      xeerx::string9.09 ns75920717 2.0assign using long int
      std::string18.7 ns37284998
      xeerx::string3.54 ns169905048 1.0assign using short int
      std::string3.91 ns195297191
      xeerx::string3.59 ns195349150 56.5assign using long float
      std::string203 ns3436025
      xeerx::string2.61 ns268187597 76.6assign using short float
      std::string200 ns3430881

      std::to_string can't convert bool to string.

    • Convert

      This function using xeerx::to_chars to convert

      So for more information see the conversion section

      Examples

      // integerstring s1; s1.convert(123);                     //  "123"// integer basestring s2; s2.convert(123, 16);                 //  "7b"// signstring s3; s3.convert(123, 16, '+');            //  "+7b"// letter casestring s4; s4.convert(123, 16, '+', tail, 1);   //  "+7B"// floatstring s5; s5.convert(3.987);                   //  "3.98"// float precisionstring s6; s6.convert(3.987, 3);                //  "3.987"// float trailing zerosstring s7; s7.convert(1.09800, 5, '+', 1);      //  "+1.09800"string s8; s8.convert(1.09800, 5, '+', 0);      //  "+1.098"

      Benchmark

      BenchmarkTimeIterationsSpeedType
      xeerx::string2.49 ns280885493 ---convert using bool
      std::string--- ns---------
      xeerx::string9.13 ns75557257 5.6convert using long int
      std::string52.0 ns13533688
      xeerx::string4.40 ns163482392 3.3convert using short int
      std::string14.8 ns46670954
      xeerx::string3.62 ns195510099 57.4convert using long float
      std::string208 ns3371255
      xeerx::string2.93 ns238643277 69.9convert using short float
      std::string205 ns3402302

      std::to_string can't convert bool to string.

    • Append

      Examples

      string s;string s1("Another String");// append using array of characterss.append("Hello");                  //  "Hello"// append using single character s.append('C');                      //  "...C"// append using range (iterators)s.append(s1.cbegin(), s1.cend());   //  "...Another String"// append using bools.append(true);                     //  "...true"// append using integer (see convert function for more details)s.append(123);                      //  "...123"// append using float   (see convert function for more details)s.append(0.14);                     //  "...0.14"// append using another strings.append(s1);                       //  "...Another String"

      Benchmark

      BenchmarkTimeIterationsSpeedType
      xeerx::string45.0 ns16190001 2.2append using string
      std::string103 ns6637803
      xeerx::string38.2 ns18203461 2.5append using array
      std::string96.0 ns7101166
      xeerx::string21.0 ns32952515 2.2append using single char
      std::string46.8 ns14844033
      xeerx::string44.0 ns15887083 2.7append using range
      std::string122 ns5548724
      xeerx::string20.9 ns34528601 ---append using bool
      std::string--- ns---------
      xeerx::string116 ns5953486 2.6append using long int
      std::string307 ns2270919
      xeerx::string75.4 ns9182231 1.0append using short int
      std::string80.4 ns8533531
      xeerx::string68.6 ns9908682 33.1append using long float
      std::string2253 ns308565
      xeerx::string30.3 ns22941116 74.4append using short float
      std::string2242 ns314610

      std::to_string can't convert bool to string.

    • Insert

      Examples

      You can find the test script in /tests/insert-string.cpp to check it yourself.

      string s("15 : ");// insert using single character s.insert(0, '0');                   //  "015 : "// insert using array of characterss.insert(2, "234");                 //  "012345 : "// insert using another strings.insert(s.size(), s);              //  "012345 : 012345 : "// insert using range (iterators)string s1("Iterator");s.insert(s.size(), s1.cbegin(), s1.cend()); //  "012345 : 012345 : Iterator"

      Benchmark

      BenchmarkTimeIterationsSpeedType
      xeerx::string90.9 ns7302295 1.5insert using string
      std::string143 ns4852644
      xeerx::string92.3 ns7438356 1.3insert using array
      std::string124 ns5604204
      xeerx::string59.6 ns11534530 1.4insert using single char
      std::string83.2 ns8121425
      xeerx::string44.0 ns7648863 ---insert using range
      std::string--- ns---------

      there is no function to insert using range in std::string.

    • Fill

      Examples

      string s;// string is not initialized yet, so append `C` * 10 timess.fill('C', 0, 10);                //  "CCCCCCCCCC"// string is initialized, so replace range(0,9) with `M`s.fill('M', 0, 10);                //  "MMMMMMMMMM"

      Benchmark

      BenchmarkTimeIterationsSpeedType
      xeerx::string13.9 ns49118574 2.6fill using character
      std::string37.0 ns18117575

      there is no function to fill in std::string, so i used replace in benchmark.

    • Replace

      Examples

      // length of "AB" = 2, length of range to replace is (6-4) = 2// so replace "45" with "AB"string s1("0123456789"); s1.replace("AB", 4, 6);             //  "0123AB6789"// length of "A" = 1, length of range to replace is (6-4) = 2// so replace "4" with "A"// and move "6789" to backward by one.// in another word, replace "45" with "A"string s2("0123456789"); s2.replace("A", 4, 6);              //  "0123A6789"// length of "HelloWorld" = 10, length of range to replace is (6-4) = 2// so move "6789" to forward by (10 - 2) = 8.// and replace "45        " with "HelloWorld"// in another word, replace "45" with "HelloWorld"string s3("0123456789"); s3.replace("HelloWorld", 4, 6);     //  "0123HelloWorld6789"

      Benchmark

      BenchmarkTimeIterationsSpeedType
      xeerx::string35.5 ns19680601 1.3replace using array
      std::string46.5 ns15060716
    • Erase

      Examples

      string s("0123456789"); s.erase(4, 2);  //  "01236789"

      Benchmark

      BenchmarkTimeIterationsSpeedType
      xeerx::string9.36 ns74738109 2.2erase part of string
      std::string21.2 ns32678576
    • Clear

      Examples

      string s("0123456789"); s.clear();     //  ""

      Benchmark

      BenchmarkTimeIterationsSpeedType
      xeerx::string1.30 ns536039461 12.6clear string contents
      std::string16.4 ns40010757
    • Resize

      Examples

      string s("0123456789"); s.resize(5);    //  "01234"

      Benchmark

      BenchmarkTimeIterationsSpeedType
      xeerx::string2.86 ns267733338 6.3resize string size
      std::string18.2 ns36673351
    • Reserve

      Examples

      string s; s.reserve(100);               //  heap capacity now is 100

      Benchmark

      BenchmarkTimeIterationsSpeedType
      xeerx::string16.1 ns44328723 2.1reserve space in the heap
      std::string35.3 ns19861444
    • Compare

      Examples

      string s("Hello");  s.compare("Hello");                     //  0s.compare("hello");                     //  -32s.compare("Blah" );                     //  6

      Benchmark

      BenchmarkTimeIterationsSpeedType
      xeerx::string1.63 ns425109330 1.2compare two strings
      std::string1.97 ns354517169
    • Find

      Examples

      string s("12 13 12 14"); // find using arrays.find("12", 0);                        //  0s.find("12", 2);                        //  6// find using characters.find('3' , 0);                        //  4

      Benchmark

      BenchmarkTimeIterationsSpeedType
      xeerx::string1.30 ns519393604 12.8find using array
      std::string16.7 ns41623313
      xeerx::string1.30 ns532126470 12.7find using character
      std::string16.6 ns41633714
    • Letter Case Control

      Examples

      string s("hello World s S 123"); // all to upper cases.upper();                        //  "HELLO WORLD S S 123"// all to lower cases.lower();                        //  "hello world s s 123"// make all words start with upper case characters.wupper();                       //  "Hello World s S 123"
    • Access Functions

      Read-Only

      string.cdata();        // Buffer of charactersstring.cbegin();       // Begin iteratorstring.cend();         // End   iteratorstring.size();         // Size of bufferstring.max_size();     // Maximum size that can be accommodatedstring.capacity();     // Capacity of bufferstring.empty();        // Check if size == 0string.cat(N);         // Get character at position

      Read-Write

      string.data();        // Buffer of charactersstring.begin();       // Begin iteratorstring.end();         // End   iteratorstring.at(N);         // Get character at position

      Benchmark

      no benchmark need in this section, all of this functions just return to the private variables.

    • Operatores

      copy-move

      string A("Hello"), B;B = A;            // copyB = std::move(B); // move

      assign

      string S;S = "Hello";S = 123;S = ...; // same as assign()

      append

      string S;S += "Hello";S += 123;S += ...; // same as append()        

      append plus [The Power Of The Append]

      string A("-> "), S;S += A + false + " 123" + 456 + ' ' + 3.14; //  "-> false 123456 3.14"// [NOTE] A will be also "-> false 123456 3.14"// because the data append to A first, than to S// so you must use a temporary string in the first argument// What if i want to add S1 and S2 to S3 without change S1 and S2 ?string S1("Hello"), S2("World"), S3;S3 = S1; S3 += S2;     // like thisS3 += string(S1) + S2; // or   this

      compare

      string S1("Hello"), S2("World");bool is_same = (S1 == S2);    

      at

      string S1("Hello");S1[0] = 'h';  

      stream

      string S1("Hello");std::cout << S1 << std::endl;

      Benchmark

      no benchmark need in this section, operators do same of it's function, for example += call append, ..etc.

  • Conversions

    • convert numbers to characters array

      Examples

      char c[11] = "N:xxxxxxxx";          // can be wchar_t or type of characters// manual length (overload with 'last' as a parameter)to_chars(c, c + sizeof(c), -10);    // c  "-10" // auto length   (overload with 'last' as a template parameter)to_chars(c,-10);                    // c  "-10" // [integer base] you can use any base between 2 and 36to_chars(c,-123, 36);               // c  "-3f"to_chars(c,-123, 16);               // c  "-7b"to_chars(c,-123, 10);               // c  "-123"to_chars(c,-123,  8);               // c  "-173" to_chars(c,-123,  2);               // c  "-1111011"// [sign]to_chars(c, 1, 10, '+');            // c  "+1"to_chars(c,-1, 10, '+');            // c  "-1"to_chars(c, 1, 10, '-');            // c   "1"to_chars(c,-1, 10, '-');            // c  "-1"to_chars(c, 1, 10, ' ');            // c  " 1"to_chars(c,-1, 10, ' ');            // c  "-1"// [terminate array]to_chars(c, 1, 10, '+', 1);         // c  "+1"to_chars(c, 1, 10, '+', 0);         // c  "+1xxxxxxxx"// [floating precision]float f = -1.09800;to_chars(c,f);                      // c  "-1.09" to_chars(c,f,  1);                  // c  "-1.0" to_chars(c,f,  2);                  // c  "-1.09" to_chars(c,f,  3);                  // c  "-1.098" to_chars(c,f,  4);                  // c  "-1.0980" // [trailing zeros]to_chars(c,f,  5, '+', 1, 0);       // c  "-1.098" to_chars(c,f,  5, '+', 1, 1);       // c  "-1.09800"// [trailing zeros]to_chars(c,f,  5, '+', 1, 0);       // c  "-1.098" to_chars(c,f,  5, '+', 1, 1);       // c  "-1.09800"// [letter case]to_chars(c,-123, 36, '+', 1, 1, 1); // c  "-3F"to_chars(c,-123, 36, '+', 1, 1, 0); // c  "-3f"// [length] if you know the length of the integer part, so put it in last argumentto_chars(c,-123, 36, '+', 1, 1, 3); // c  "-3F"// [return | exception]//  if successed return to last written position //  if failed    return to xeerx::size_t_max//  if X_DEBUG macro is defined, when failed will throw an exceptionx

      Benchmark

      BenchmarkTimeIterationsSpeedType
      xeerx::to_chars0.333 ns1000000000243.8long float
      std::to_chars81.2 ns8665522
      xeerx::to_chars0.327 ns1000000000177.6short float
      std::to_chars58.1 ns12034705
      xeerx::to_chars0.327 ns1000000000 3.9long int
      std::to_chars1.30 ns531564683
      xeerx::to_chars0.326 ns1000000000 2.0short int
      std::to_chars0.652 ns1000000000
    • convert characters array to numbers

      Examples

    chars_to<int>("-123");   //  -123// [integer base] you can use any base between 2 and 36chars_to<int>("-3F",       36);     //  -123chars_to<int>("-7B",       16);     //  -123chars_to<int>("-123",      10);     //  -123chars_to<int>("-173",       8);     //  -123chars_to<int>("-1111011",   2);     //  -123// [floating precision]chars_to<double>("-1.0098765");     //  -1.00chars_to<double>("-1.0098765",  1); //  -1.0chars_to<double>("-1.0098765",  2); //  -1.00chars_to<double>("-1.0098765",  3); //  -1.009chars_to<double>("-1.0098765",  4); //  -1.0098chars_to<double>("-1.0098765",  5); //  -1.00986chars_to<double>("-1.0098765",  6); //  -1.009865// [return | exception]//  if successed return to converted value//  if failed    return to std::numeric_limits::max<N>()//  if X_DEBUG macro is defined, when failed will throw an exceptionx

    Benchmark

    BenchmarkTimeIterationsSpeedType
    xeerx::chars_to0.327 ns1000000000 88.6long float
    std::from_chars29.0 ns24078935
    xeerx::chars_to0.327 ns1000000000 1.6short float
    std::from_chars0.545 ns1000000000
    xeerx::chars_to0.327 ns1000000000 4.0long int
    std::from_chars1.31 ns533874680
    xeerx::chars_to0.328 ns1000000000 1.9short int
    std::from_chars0.652 ns1000000000
  • Time

    • units

      all units using std::chrono

      second;milliseconds;microseconds;nanoseconds;
    • timestamp

      timestamp<unit>();           // autotimestamp<unit>(1664697587); // manual// membersval; // timestamp valuefac; // factor (second = 1, mirosecond = 1000, ...)
    • main time class

      // autotime<second>      t; // timestamp  1664697587          , fac  1time<millisecond> t; // timestamp  1664697587405       , fac  1000time<microsecond> t; // timestamp  1664697587405492    , fac  1000000time<nanosecond>  t; // timestamp  1664697587405492704 , fac  1000000000// manualtime<second>   t(1664697587); // timestamp -> 1664697587 , fac -> 1// specification characters typetime<unit, char_type> t;    // char_type by default is `char`// for string format use itstime<unit, char_type> t;  // this will containts same members of normal `time` class// in addition to the string members
      • numerical members

        t.unit;        // xeerx::timestamp objectt.unit.val;    // timestamp of unit :  1664697587405492704t.unit.fac;    // factor    of unit :  1000000000t.year;        //  2022t.month;       //  10t.week;        //  1t.weekday;     //  2t.day;         //  2t.yday;        //  275t.hour;        //  7t.Hour;        //  7t.minute;      //  59t.second;      //  47t.millisecond; //  405t.microsecond; //  492t.nanosecond;  //  704
      • string members

        to get time members in string format you should using stimg instead of time.

        t.num;          // xeerx::time object, use it to access the numerical memberst.syear;        //  "2022" t.smonth;       //  "10" t.sweek;        //  "01" t.sweekday;     //  "02" t.sday;         //  "02" t.shour;        //  "07"t.sHour;        //  "07"t.sminute;      //  "59"t.ssecond;      //  "47"t.smillisecond; //  "405"t.smicrosecond; //  "492"t.snanosecond ; //  "704"t.m;            //  "AM"// namest.nweekday;     //  "Sun"t.Nweekday;     //  "Sunday"t.nmonth;       //  "Oct"t.Nmonth;       //  "October"
      • convert between time and stime

        // stime -> timetime<nanosecond>  t  = stime<nanosecond>;       // ERRORtime<nanosecond>  t  = stime<nanosecond>().num; // OK// time  -> stimestime<nanosecond> st = time<nanosecond>;        // OK

      Benchmark

      BenchmarkTimeIterationsSpeed
      xeerx::time13.2 ns51969561 200.7
      xeerx::stime29.4 ns24039762 90.1
      local_time2430 ns293162
      to_time_t2844 ns234573
      asctime2847 ns250791
  • Formatting

    • Pattern

      • prototype

        // prototype// N -> How many sections are there in this pattern [for optimization]// C -> Type of characterfpattern<N, C = char> ("...");
      • arguments

        // sequence argumentfpattern<1>("{}");// numbered argumentfpattern<1>("{I}");// mix of sequence and numbered argumentfpattern<4>("{1} {} {0} {}");// [1] -> second "{1}"  - (no effect on the last argument id)// [2] -> first  "{}"   (last argument id is 0, and will be 1)// [3] -> first  "{0}"  - (no effect on the last argument id)// [4] -> second "{}"   (last argument id is 1, and will be 2)// control argumentsfpattern<1>("{:}" || "{I:}");  // wrtie ':' to manage the argument// control integer base | float precisionfpattern<1>("{:N}" || "{I:N}");// for integer, 'N' can be any number between 2 and 36 (default is 10)// for float  , 'N' can be any number between 1 and 36 (default is  2)// control letter case (Without specifying case, it will be left as is)// [NOTE] letter case contoller works only on integer's //        when base numerical base > 10fpattern<1>("{:NC}" || "{I:NC}");  // for all capitalfpattern<1>("{:Nc}" || "{I:Nc}");  // for all small// control sign (see conversion section to know more about sign's)fpattern<1>("{:SN}" || "{I:SN}");// the final patternfpattern<1>("{:SNC}" || "{I:SNC}");// { -> begin of section (Necessary)// I -> argument id      (Not Necessary)// : -> controller       (Necessary IF you will manage the argument)// S -> sign             (Not Necessary)// N -> base | precision (Not Necessary)// C -> letter case      (Not Necessary)// } -> end of section   (Necessary)/* ------------ Exceptions ------------ */// std::invalid_argument("bad syntax")// [-] you must write one or more specifier at least after the controller `:`// [-] you must write the begin '{' and the end '}' of the section //     without any-unknown character between it//     the known characters is "I:SNC"// std::out_of_range("invalid argument id")// [-] 'I' can not be larger than the template parameter 'N'
      • padding

        // prototypefpattern<1>("{.AFV.}");// {. -> begin of padding section       (Necessary)// A  -> padding align  ['<', '>', '^'] (Not Necessary) (default is left '<')// F  -> padding fill   [any char]      (Necessary)// V  -> padding value  [any numbers]   (Necessary)// .} -> end   of padding section       (Necessary)// dynamic padding (with argument's and text inside it)fpattern<4>("{.^ 15IP:{}.},{.^ 15PORT:{}.}");// IF IP is "127.0.0.1" && PORT is 443, so the result will be like it:// --> "IP:127.0.0.1   ,PORT:443       "// normal padding (without anything inside it)fpattern<2>("{.*5.} IP:{}");// --> "***** IP:127.0.0.1"
      • Examples

        xeerx::format<N> returns to xeerx::basic_string<char>

        xeerx::format<C, N> returns to xeerx::basic_string<C>

        // sequence arguments    "Hello World"format<2>("{} {}", "Hello", "World");// numbered arguments    "World Hello, Hello World"format<4>("{1} {0}, {0} {1}", "Hello", "World");// character             "C, C"format<2>("{}, {}", 'C', 'c'); // bool                  "true, false"format<2>("{}, {}", true, false);                   // integer               "123"format<1>("{}", 123);// integer base          "d:123, x:7b, o:173, b:1111011, 36:3f"format<5>("d:{0:10}, x:{0:16}, o:{0:8}, b:{0:2}, 36:{0:36}", 123);  // letter case           "Capital:3F, Small:3f"format<2>("Capital:{0:36C}, Small:{0:36c}", 123);// float                 "3.14"format<1>("{}", 3.14);// float precision       "3.01, 3.014, 3.0143"format<3>("{0:2}, {0:3}, {0:4}", 3.014321);// sign                  "+:[+1, 1,  1], -:[-1, -1, -1]"format<6>("+:[{0:+10}, {0:-10}, {0: 10}], -:[{1:+10}, {1:-10}, {1: 10}]",  1, -1); // multi types           "string, C, true, -123, 3.14"format<5>("{}, {}, {}, {}, {}", "string", 'C', true, -123, 3.14);

        padding examples

        // empty padding         "**********, true"format<2>("{.*10.}, {}", true);// left   aligned        "******true"format<2>("{.<*10{}.}", true);// right  aligned        "true******"format<2>("{.>*10{}.}", true);// center aligned        "***true***"format<2>("{.^*10{}.}", true);// another example       "[IP:127.0.0.1    ] [PORT:443        ]"format<4>("[{.> 15IP:{}.}] [{.> 15PORT:{}.}]", "127.0.0.1", 443);

    Benchmark

    BenchmarkTimeIterationsSpeedType
    xeerx::format3.70 ns186586391 52.9left padding
    fmt::format196 ns3545286
    xeerx::format3.70 ns189126228 54.3right padding
    fmt::format201 ns3464272
    xeerx::format3.70 ns188942568 57.0center padding
    fmt::format211 ns3304297
    xeerx::format2.69 ns258969920 9.9one string
    fmt::format26.7 ns26305344
    xeerx::format16.5 ns42150231 4.0two strings
    fmt::format66.7 ns10376705
    xeerx::format77.8 ns8581737 2.2a lot strings
    fmt::format174 ns4061439
    xeerx::format2.69 ns259762850 14.3signle character
    fmt::format38.6 ns18119202
    xeerx::format10.8 ns64446743 5.3bool
    fmt::format57.6 ns11925818
    xeerx::format2.02 ns346543561 10.0short int
    fmt::format20.1 ns34644407
    xeerx::format3.02 ns231357308 17.4long int
    fmt::format52.4 ns13166775
    xeerx::format2.69 ns252905827 29.4float
    fmt::format78.6 ns9923260
    • Optimization with constexpr fpattern

      it will be faster by near 30% in long and complicated patterns

      constexpr fpattern<N> pat("...");// then you can pass it to format function like:format<N>(pat, ...);
  • Exceptions

    0. void test()1. {2.      x_throw(exceptions::out_of_range);3. }// output:// xeerx::exception::out_of_range// [FILE] /path/to/file.ext [LINE] 2 [FUNC] test 
```cpp0. void test()1. {    int pos = 21, size = 20;2.      x_throws(exceptions::out_of_range, format<2>("pos:{} >= size:{}", pos, size));3. }// output:// xeerx::exception::out_of_range// [FILE] /path/to/file.ext [LINE] 2 [FUNC] test : pos:21 >= size:20```

Benchmark Info

  • compiler: GCC 12
  • c++ version: 20
  • operator system: Ubuntu 22.04.1 LTS
  • processor: Intel Core i7-6500U CPU @ 2.50GHz 4
  • flags: -Ofast

Source Code

you can find the source code on Github

because the source code is big and has a lot script's

so i can't put it here.

This Post Was Published In Version 0.0.1

Updates

..

Hope I made something useful

This version is still a beta version and I have not finished fully developing the library

So I would like to know your opinion about this

  • Are there problems ?

  • Is there anything that can be developed or added?

  • Did I do anything wrong?

Thanks.


Original Link: https://dev.to/xeerx/much-faster-than-stdstring-fmtformat-stdtochars-stdtime-and-more-4j5n

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To