1 // ANNA - Anna is Not Nothingness Anymore //
3 // (c) Copyright 2005-2015 Eduardo Ramos Testillano & Francisco Ruiz Rayo //
5 // See project site at http://redmine.teslayout.com/projects/anna-suite //
6 // See accompanying file LICENSE or copy at http://www.teslayout.com/projects/public/anna.LICENSE //
9 #ifndef anna_core_functions_hpp
10 #define anna_core_functions_hpp
14 #include <anna/core/util/ComponentManager.hpp>
15 #include <anna/core/util/defines.hpp>
16 #include <anna/core/RuntimeException.hpp>
18 #include <anna/core/util/ExclusiveHash.hpp>
19 #include <anna/core/util/Second.hpp>
20 #include <anna/core/util/Millisecond.hpp>
21 #include <anna/core/util/Microsecond.hpp>
23 #include <anna/core/DataBlock.hpp>
32 //------------------------------------------------------------------------------
33 //---------------------------------------------------------------------- #define
34 //------------------------------------------------------------------------------
35 #define s_REGEXP_IPv4_ADDRESSES "\\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b"
36 //#define s_REGEXP_IPv6_ADDRESSES "s*((([0-9A-Fa-f]{1,4}:){7}(([0-9A-Fa-f]{1,4})|:))|(([0-9A-Fa-f]{1,4}:){6}(:|((25[0-5]|2[0-4]\\d|[01]?\\d{1,2})(\\.(25[0-5]|2[0-4]\\d|[01]?\\d{1,2})){3})|(:[0-9A-Fa-f]{1,4})))|(([0-9A-Fa-f]{1,4}:){5}((:((25[0-5]|2[0-4]\\d|[01]?\\d{1,2})(\\.(25[0-5]|2[0-4]\\d|[01]?\\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){4}(:[0-9A-Fa-f]{1,4}){0,1}((:((25[0-5]|2[0-4]\\d|[01]?\\d{1,2})(\\.(25[0-5]|2[0-4]\\d|[01]?\\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){3}(:[0-9A-Fa-f]{1,4}){0,2}((:((25[0-5]|2[0-4]\\d|[01]?\\d{1,2})(\\.(25[0-5]|2[0-4]\\d|[01]?\\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){2}(:[0-9A-Fa-f]{1,4}){0,3}((:((25[0-5]|2[0-4]\\d|[01]?\\d{1,2})(\\.(25[0-5]|2[0-4]\\d|[01]?\\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:)(:[0-9A-Fa-f]{1,4}){0,4}((:((25[0-5]|2[0-4]\\d|[01]?\\d{1,2})(\\.(25[0-5]|2[0-4]\\d|[01]?\\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(:(:[0-9A-Fa-f]{1,4}){0,5}((:((25[0-5]|2[0-4]\\d|[01]?\\d{1,2})(\\.(25[0-5]|2[0-4]\\d|[01]?\\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(((25[0-5]|2[0-4]\\d|[01]?\\d{1,2})(\\.(25[0-5]|2[0-4]\\d|[01]?\\d{1,2})){3})))(%.+)?\\s*"
37 #define s_REGEXP_IPv6_ADDRESSES "s*((([0-9A-Fa-f]{1,4}:){7}(([0-9A-Fa-f]{1,4})|:))|(([0-9A-Fa-f]{1,4}:){6}(:|((25[0-5]|2[0-4]\\d|[01]?\\d{1,2})\
38 (\\.(25[0-5]|2[0-4]\\d|[01]?\\d{1,2})){3})|(:[0-9A-Fa-f]{1,4})))|(([0-9A-Fa-f]{1,4}:){5}((:((25[0-5]|2[0-4]\\d|[01]?\\d{1,2})(\\.(25[0-5]|2[0-4]\
39 \\d|[01]?\\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){4}(:[0-9A-Fa-f]{1,4}){0,1}((:((25[0-5]|2[0-4]\\d|[01]?\\d{1,2})(\\.(\
40 25[0-5]|2[0-4]\\d|[01]?\\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){3}(:[0-9A-Fa-f]{1,4}){0,2}((:((25[0-5]|2[0-4]\\d|[01]?\
41 \\d{1,2})(\\.(25[0-5]|2[0-4]\\d|[01]?\\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){2}(:[0-9A-Fa-f]{1,4}){0,3}((:((25[0-5]|2\
42 [0-4]\\d|[01]?\\d{1,2})(\\.(25[0-5]|2[0-4]\\d|[01]?\\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:)(:[0-9A-Fa-f]{1,4}){0,4}((:\
43 ((25[0-5]|2[0-4]\\d|[01]?\\d{1,2})(\\.(25[0-5]|2[0-4]\\d|[01]?\\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(:(:[0-9A-Fa-f]{1,4}){0,5}((:((25[0-\
44 5]|2[0-4]\\d|[01]?\\d{1,2})(\\.(25[0-5]|2[0-4]\\d|[01]?\\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(((25[0-5]|2[0-4]\\d|[01]?\\d{1,2})(\\.(25[\
45 0-5]|2[0-4]\\d|[01]?\\d{1,2})){3})))(%.+)?\\s*"
47 // Helpers for alarm parsing parameters:
48 #define STRING_WITH_QUOTATION_MARKS__C_STR(x) ((anna::functions::addQuotationMarks(x)).c_str())
49 #define ANNA_AS_STRING__C_STR(x) ((anna::functions::asString(x)).c_str())
58 #define CLOCK_PROCESS_CPUTIME_ID CLOCK_PROCESS_CPUTIME
63 functions - Métodos y variables
67 Tamao de la memoria reservada que debe tener la variable usada para guardar
68 el resultado de convertir el 'time' en texto.
72 static const int DateTimeSizeString = 21;
75 @return La versin de functions con la que hemos linkado nuestra aplicacion.
77 static std::string getVersion() throw();
80 @return Un literal con la arquitectura sobre la que hemos compilado nuestra aplicacion.
82 static std::string getArchitecture() throw();
85 Indica el número de bits de un entero.
87 static const int intBitSize = sizeof(int) * 8;
90 * Indica el número de bits de un entero largo.
92 static const int int64BitSize = sizeof(S64) * 8;
95 \param number Numero a convertir.
96 @return Un literal con el numero convertido a cadena decimal.
98 static std::string asString(const int number) throw();
101 \param number Numero a convertir.
102 @return Un literal con el numero sin signo convertido a cadena decimal.
104 static std::string asString(const unsigned int number) throw();
107 \param number Numero a convertir.
108 @return Un literal con el numero sin signo convertido a cadena decimal.
110 static std::string asString(const unsigned long long int number) throw() {
111 return asString((U64)number);
115 \param number Numero a convertir.
116 @return Un literal con el numero sin signo convertido a cadena decimal.
118 static std::string asString(const long long int number) throw() {
119 return asString((S64)number);
123 Devuelve un literal con tel numero convertido a cadena decimal
124 @return Un literal con el numero signo convertido a cadena decimal.
126 static std::string asString(const S64 number) throw();
129 Devuelve un literal con tel numero convertido a cadena decimal
130 @return Un literal con el numero signo convertido a cadena decimal.
132 static std::string asString(const U64 number) throw();
135 \param _bool Booleano a convertir.
136 \return Un literal con el boolean convertido a cadena.
138 static const char* asString(const bool _bool) throw() { return (_bool == true) ? "true" : "false"; }
141 Devuelve una cadena con el bloque de datos decodificado en grupos de 16 bytes.
142 @param dataBlock Bloque de datos a interpretar.
143 \param characterByLine Número de caracteres en cada línea.
144 @return Devuelve una cadena con el bloque de datos decodificado en grupos de 16 bytes.
146 static std::string asString(const DataBlock& dataBlock, const int characterByLine = 16) throw();
149 Devuelve una cadena con el numero en coma flotante.
150 \param v Numero a tratar.
151 \param format Formato aplicado para convertir el numero a cadena. Ver \em man printf.
152 \return una cadena con el numero en coma flotante.
154 static std::string asString(const double v, const char* format = "%e") throw();
157 Devuelve una cadena con el numero en coma flotante.
158 \param v Numero a tratar.
159 \param format Formato aplicado para convertir el numero a cadena. Ver \em man printf.
160 \return una cadena con el numero en coma flotante.
162 static std::string asString(const float v, const char* format = "%f") throw();
165 \param comment Comentario que precede al valor.
166 \param number Numero a convertir.
167 @return Un literal con el numero convertido a cadena decimal.
169 static std::string asText(const char* comment, const int number)
171 std::string result(comment);
172 return result += asString(number);
176 \param comment Comentario que precede al valor.
177 \param number Numero a convertir.
178 @return Un literal con el numero convertido a cadena decimal.
180 static std::string asText(const char* comment, const S64 number)
182 std::string result(comment);
183 return result += asString(number);
187 \param comment Comentario que precede al valor.
188 \param _bool Booleano a convertir.
189 @return Un literal con el numero convertido a cadena decimal.
191 static std::string asText(const char* comment, const bool _bool)
193 std::string result(comment);
194 return result += asString(_bool);
198 \param comment Comentario que precede al valor.
199 \param dataBlock Bloque de datos a interpretar.
200 \param characterByLine Número de caracteres en cada línea.
201 @return Un literal con el numero convertido a cadena decimal.
203 static std::string asText(const char* comment, const DataBlock& dataBlock, const int characterByLine = 16)
205 std::string result(comment);
206 return result += asString(dataBlock, characterByLine);
210 \param comment Comentario que precede al valor.
211 \param value Numero a tratar.
212 \param format Formato aplicado para convertir el numero a cadena. Ver \em man printf.
213 \return Un literal con el numero convertido a cadena.
215 static std::string asText(const char* comment, const float value, const char* format = "%f")
217 std::string result(comment);
218 return result += asString(value, format);
222 \param comment Comentario que precede al valor.
223 \param value Numero a tratar.
224 \param format Formato aplicado para convertir el numero a cadena. Ver \em man printf.
225 \return Un literal con el numero convertido a cadena.
227 static std::string asText(const char* comment, const double value, const char* format = "%e")
229 std::string result(comment);
230 return result += asString(value, format);
234 \param number Numero a convertir.
235 @return Un literal con el numero convertido a cadena hexadecimal.
237 static std::string asHexString(const int number) throw();
240 \param number Numero a convertir.
241 @return Un literal con el numero convertido a cadena hexadecimal.
243 static std::string asHexString(const S64 number) throw();
246 \param number Numero a convertir.
247 @return Un literal con el numero convertido a cadena hexadecimal.
249 static std::string asHexString(const U64 number) throw() { return asHexString((S64) number); }
252 \param comment Comentario que precede al valor.
253 \param number Numero a convertir.
254 @return Un literal con el numero convertido a cadena decimal.
256 static std::string asHexText(const char* comment, const int number)
258 std::string result(comment);
259 return result += asHexString(number);
263 \param comment Comentario que precede al valor.
264 \param number Numero a convertir.
265 @return Un literal con el numero convertido a cadena decimal.
267 static std::string asHexText(const char* comment, const S64 number)
269 std::string result(comment);
270 return result += asHexString(number);
274 * Devuelve un cadena con el contenido del bloque de datos interpretado como BCD, pero pasa
275 * cada valor binario a su correspondiente carácter. Por ejemplo, el buffer aa210c quedará como una cadena "AA210C".
277 * \param dataBlock Bloque a codificar.
278 * \return La cadena que contiene el valor literal del buffer de datos.
280 static std::string asHexString(const DataBlock& dataBlock) throw();
283 * Obtiene el valor original de una cadena obtenido con #asHexString (const DataBlock&).
284 * \param hexString Cadena que contiene el búfer.
285 * \param target Bloque de datos sobre el que decodificar la cadena.
286 * \return El bloque de datos original correspondiente a la cadena recibida.
288 static DataBlock& fromHexString(const std::string& hexString, DataBlock& target) throw(RuntimeException);
291 Devuelve una cadena con la hora en formato 'dd/mm/yyyy hh:mm:ss'.
293 @param second Hora que deseamos traducir.
295 @return Un literal con la hora en el formato 'dd/mm/yyyy hh:mm:ss'.
297 static std::string asDateTime(const Second &second) throw();
300 Devuelve una cadena con la hora en formato 'dd/mm/yyyy hh:mm:ss'.
302 @param second Hora que deseamos traducir.
303 @param result Puntero donde vamos a guardar el resultado de la conversin.
304 Debe tener espacio reservado para contener #TimeSizeAsString caracteres.
306 @return El puntero recibido como parametro conteniendo el literal con la hora
307 en el formato 'dd/mm/yyyy hh:mm:ss'.
309 static const char* asDateTime(const Second &second, char* result) throw();
312 Calcula la funcion hash de la cadena recibida como parametro.
313 \param str Cadena a la que aplicar la funcion hash.
315 static S64 hash(const char* str) throw();
318 Calcula la funcion hash de la cadena recibida como parametro.
319 \param str Cadena a la que aplicar la funcion hash.
321 static S64 hash(const std::string& str) throw() { return hash(str.c_str()); }
324 Devuelve la cadena que contiene el resultado de aplicar la especificacion \em format
325 sobre el resto de los parametros.
327 \param format especificacion de formato similiar al empleado en las funciones \em printf,
330 \return la cadena que contiene el resultado de aplicar la especificacion \em format
331 sobre el resto de los parametros.
333 static std::string asString(const char* format, ...) throw();
336 Devuelve el resultado de invocar a metodo asString de la clase recibida como parametro.
337 Si t es NULL devolvera el texto indicando la sitacion.
338 \param t Instancia de la clase a usar. Puede ser NULL.
339 \return el resultado de invoca a T::asString () si t es distinto de NULL.
340 \warning La clase T debe tener un metodo estatico con la signatura:
342 static const char* className () throw ();
345 template <typename T> static std::string asString(const T* t)
348 std::string result(T::className());
349 result += " { <null> }";
353 return t->asString();
357 Metodo identididad. Facilita la implementacion de patrones donde no se conoce el tipo de dato recibido.
359 \param str Instancia de la cadena.
360 \return La misma instancia recibida como parametro.
362 static const std::string& asString(const std::string& str) throw() { return str; }
365 Detiene la ejecucion del thread durante el numero de milisegundos indicados.
367 \param millisecond Numero de milisegundos que vamos a detener la ejecucion de este thread.
369 static void sleep(const Millisecond &millisecond) throw();
372 Obtiene el numero de segundos transcurridos desde el 1 del 1 de 1970.
373 \return El numero de segundos transcurridos desde el 1 del 1 de 1970.
375 static Second second() throw() {
376 Second result(::time(NULL));
381 Obtiene el numero de microsegundos transcurridos desde el 1 del 1 de 1970.
382 \return El numero de microsegundos transcurridos desde el 1 del 1 de 1970.
384 static Microsecond microsecond() throw() {
386 gettimeofday(&tv, NULL);
387 Microsecond result((Microsecond::type_t)1000000 * tv.tv_sec + tv.tv_usec);
392 Obtiene el numero de milisegundos transcurridos desde el 1 del 1 de 1970.
393 \return El numero de milisegundos transcurridos desde el 1 del 1 de 1970.
395 static Millisecond millisecond() throw() {
397 gettimeofday(&tv, NULL);
398 Millisecond result((Millisecond::type_t)1000 * tv.tv_sec + tv.tv_usec / 1000);
403 Devuelve la referencia interna de los microsegundos transcurrido en el procesador.
404 \return la referencia interna de los microsegundos transcurrido en el procesador.
406 static Microsecond hardwareClock() throw() {
408 //clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts); // DONT works (original)
409 //clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts); // DONT works
410 //clock_gettime(CLOCK_MONOTONIC, &ts); // works
411 // Note that CLOCK_MONOTONIC is subject to discontinuities from system time
412 // adjustment in Linux. CLOCK_MONOTONIC_RAW was defined to get around this
413 // (gets hardware time not adjusted by NTP).
414 clock_gettime(CLOCK_MONOTONIC_RAW, &ts); // works
416 Microsecond result((Microsecond::type_t)1000000 * ts.tv_sec + ts.tv_nsec / 1000);
421 Interpreta la cadena recibida como parametro como un dato de tipo boolean.
423 Si la cadena vale NULL, o contiene los literales "false" o "0" devolvera \em false,
424 si contiene los literales "true" o "1" devolvera \em true, en otro caso devolvera un excepcion.
426 \param str Cadena a interpretar.
428 \return El valor booleano correspondiente a la cadena recibida.
430 static bool asBool(const char* str) throw(RuntimeException);
433 Interpreta la cadena recibida como parametro como un entero de 32 bits.
436 static int asInteger(const char* str) throw() { return atoi(str); }
439 Interpreta la cadena recibida como parametro como un entero de 32 bits.
442 static S64 asInteger64(const char* str) throw();
445 Devuelve el identificador de thread desde el que es invocado este metodo.
446 Si el programa no tuviera soporta para MT siempre devolvera 0.
447 \return el identificador de thread desde el que es invocado este metodo.
449 static pthread_t getCurrentThread() throw();
452 Devuelve \em true si la version de nucleo que estamos ejecutado soporta multithread o \em false en otro
454 \return \em true si la version de nucleo que estamos ejecutado soporta multithread o \em false en otro
456 static bool supportMultithread() throw() {
457 WHEN_SINGLETHREAD(return false);
458 WHEN_MULTITHREAD(return true);
462 Devuelve \em true si el valor recibido cumple el patron establecido o \em false en otro caso.
463 \param pattern Expresion regular que describe el patron a cumplir.
464 \param value Cadena a comparar con el patron.
465 \return \em true si el valor recibido cumple el patron establecido o \em false en otro caso.
467 \see regexec para mas informacion sobre las expresiones regulares.
469 static bool isLike(const char* pattern, const std::string& value) throw(RuntimeException);
472 * Devuelve el número de bits necesarios para representar el valor recibido como parámetro.
473 * \param n Valor a estudiar.
474 * \return el número de bits necesarios para representar el valor recibido como parámetro.
476 static int bitsize(const int n) throw() { return (n == 0) ? 1 : functions::log2(n) + 1; }
479 * Devuelve el número de bits necesarios para representar el valor recibido como parámetro.
480 * \param n Valor a estudiar.
481 * \return el número de bits necesarios para representar el valor recibido como parámetro.
483 static int bitsize(const S64 n) throw() {
484 int aux = n >> intBitSize;
485 return (aux != 0) ? (bitsize(aux) + intBitSize) : bitsize((int) n);
489 * Calcula la operación (n1 << bitShit) | n2. Establece las comprobaciones necesarias para verificar
490 * que la operación se realiza correctamente, teniendo especial cuidado de que no se puedan solapar
491 * ninguno de los valores.
493 * \param whatis Literal que debería identificar el punto de invocación en caso de que haya algún error.
494 * \param n1 Número a desplazar el nº de bits indicado por \em bitShift.
495 * \param bitShift Número de bits a desplazar.
496 * \param n2 Número a combinar con el resultado de la operación (n1 << bitShift).
498 static S64 merge(const char* whatis, const int n1, const int n2, const int bitShift) throw(RuntimeException);
501 * Calcula el logaritmo en base 2 del número recibo como parámetro.
502 * \param v Valor a calcular.
503 * \return El algoritmo en base 2 del número recibido como parámetro o -1 si el parámetro recibido es 0.
505 static int log2(const unsigned int v) throw();
510 //////////////////////////////////////////////////////////////////////////////////////////////////
511 // Text format resources /////////////////////////////////////////////////////////////////////////
512 //////////////////////////////////////////////////////////////////////////////////////////////////
513 struct TextHighlightMode {
515 None = -1, // Initialized
525 struct TextJustifyMode {
527 None = -1, // Initialized
535 Solve singular/plural literal expression for any number.
537 Provide (0): returns "no entries"
538 Provide (1): returns "1 entry"
539 Provide (2): returns "2 entries"
541 Provide (0, 'table'): returns "no tables"
542 Provide (1, 'table'): returns "1 table"
543 Provide (2, 'table'): returns "2 tables"
545 Provide (0, 'query', 'queries'): returns "no queries"
546 Provide (1, 'query', 'queries'): returns "1 query"
547 Provide (2, 'query', 'queries'): returns "2 queries"
550 @param number Amount processed
551 @param wordForSingular Word used as singular, 'entry' by default.
552 @param wordForPlural Word used as plural, 'entries' by default.
554 @return Coherent literal as '%d <singular word/plural word>'
556 static std::string entriesAsString(int number, const char * wordForSingular = NULL, const char * wordForPlural = NULL) throw();
559 Justify text (traces and output improvement)
561 @param title Title processed
562 @param mode Justify mode: Left (default), Center, Right
563 @param filler Filler character used (space by default)
565 @return Processed text
567 static std::string justify(const std::string & title, TextJustifyMode::_v mode = TextJustifyMode::Left, char filler = ' ') throw();
570 Highligth text (traces and output improvement)
572 @param title Title processed
573 @param mode Highlight mode: Overline, Underline(default), OverAndUnderline, Leftline, Rightline, LeftAndRightline
574 @param filler Filler character used (dash by default)
575 @param appendCR Carriage return inclusion (true by default)
577 @return Processed text
579 static std::string highlight(const std::string & title, TextHighlightMode::_v mode = TextHighlightMode::Underline, char filler = '-', bool appendCR = true) throw();
582 Highligth and justify text (traces and output improvement)
584 @param title Title processed
585 @param hMode Highlight mode: Overline, Underline(default), OverAndUnderline, Leftline, Rightline, LeftAndRightline
586 @param jMode Justify mode: Left (default), Center, Right
587 @param highlightFiller Filler character used (double dash ('=') by default)
588 @param justifyFiller Filler character used when justify (space by default)
589 @param appendCR Carriage return inclusion (true by default)
591 @return Processed text
593 static std::string highlightJustify(const std::string & title, TextHighlightMode::_v hMode = TextHighlightMode::OverAndUnderline, TextJustifyMode::_v jMode = TextJustifyMode::Center, char highlightFiller = '=', char justifyFiller = ' ', bool appendCR = true) throw() {
594 return(highlight(justify(title, jMode, justifyFiller), hMode, highlightFiller, appendCR));
598 Tabulate text (traces and output improvement)
600 @param text Text processed
601 @param tabSpaces Tab spaces (three by default)
603 static std::string tab(const std::string & text, int tabSpaces = 3) throw();
606 //////////////////////////////////////////////////////////////////////////////////////////////////
607 // Conversions and helpers ///////////////////////////////////////////////////////////////////////
608 //////////////////////////////////////////////////////////////////////////////////////////////////
611 Pattern to obtain a multi named component instance easily.
612 Parameters are usually replaced by the macro C <b>FILE_LOCATION</b>.
614 \param className Component class name
615 \param fromFile File which called the method
616 \param fromLine Line number within the file from where the method is called.
618 \return Component instance for the class provided at the pattern
621 template <typename T> static T* componentByName(const char *className, const char* fromFile, const int fromLine)
622 throw(RuntimeException) {
623 ComponentManager &cm = ComponentManager::instantiate();
624 T* result = static_cast <T*>(cm.find(className));
627 std::string msg(className);
628 msg += " | Unregistered component";
629 throw RuntimeException(msg, fromFile, fromLine);
636 Pattern to obtain a single named component instance easily.
637 Parameters are usually replaced by the macro C <b>FILE_LOCATION</b>.
639 \param fromFile File which called the method
640 \param fromLine Line number within the file from where the method is called.
642 \return Component instance for the class provided at the pattern
643 \warning T class must implement a method in the form:
645 static const char* getClassName () throw ();
649 template <typename T> static T* component(const char* fromFile, const int fromLine)
650 throw(RuntimeException) {
651 return functions::componentByName<T> (T::getClassName(), fromFile, fromLine);
655 Finds string at the end of another
657 @param pattern String where we find
658 @param suffix Searched string
660 @return Boolean about ocurrency
662 static bool endsWith(const std::string & pattern, const std::string & suffix) throw() {
664 return endsWith(pattern, suffix, dummy);
668 Similar to #endsWith but returning additional preffix string by reference (pattern without suffix)
670 static bool endsWith(const std::string & pattern, const std::string & suffix, std::string & preffix) throw();
673 Finds string at the begining of another
675 @param pattern String where we find
676 @param preffix Searched string
678 @return Boolean about ocurrency
680 static bool startsWith(const std::string & pattern, const std::string & preffix) throw() {
682 return startsWith(pattern, preffix, dummy);
686 Similar to #startsWith but returning additional suffix string by reference (pattern without preffix)
688 static bool startsWith(const std::string & pattern, const std::string & preffix, std::string & suffix) throw();
691 Finds 'item' and replaces it with 'target' within the string provided ('text').
692 The result is returned.
694 @param text Original string
695 @param item Searched string
696 @param target String which replaces the item
697 @param all Boolean about replace all items or only the first found. True by default.
699 @return Modified string
701 static std::string replace(const std::string & text, const char *item, const char *target, bool all = true) throw();
704 * Coverts original string without quotation into quoted one: '\%s'
706 static std::string addQuotationMarks(const std::string & str) throw();
707 static std::string addQuotationMarks(const char * str) throw();
708 static std::string addQuotationMarks(const int & integer) throw();
711 * Generates space-separated string lists based on integer elements
712 * Also, another separator could be used.
714 static std::string vectorToStringRepresentation(const std::vector<int> & v, const char separator = ' ') throw();
717 * Generates space-separated string lists based on string elements.
718 * Also, another separator could be used.
720 static std::string vectorToStringRepresentation(const std::vector<std::string> & v, const char separator = ' ') throw();
723 Returns socket notation 'Address:Port'
725 static std::string socketLiteralAsString(const std::string & address, int port) throw();
728 Ascii string for buffer/size data block
730 @param buffer Octet string buffer
731 @param size Buffer size
732 @param isFullyPrintable Returned by reference
734 @return Ascii string representation, and dots for non-printable cheracters
736 static std::string asAsciiString(const char * buffer, int size, bool & isFullyPrintable) throw();
739 Same as #asAsciiString but without interest about if is printable or not
741 static std::string asAsciiString(const char * buffer, int size) throw() {
742 bool isFullyPrintable;
743 return asAsciiString(buffer, size, isFullyPrintable);
747 Same as #asAsciiString providing anna::DataBlock
749 static std::string asAsciiString(const DataBlock & db, bool & isFullyPrintable) throw() {
750 return asAsciiString(db.getData(), db.getSize(), isFullyPrintable);
754 Same as #asAsciiString providing DataBlock and without interest about if is printable or not
756 static std::string asAsciiString(const DataBlock & db) throw() {
757 bool isFullyPrintable;
758 return asAsciiString(db.getData(), db.getSize(), isFullyPrintable);
763 * IP Address enconding based on common database 'human-readable raw presentation':
765 * Example for IPv4: 'AABBCCDD' will be DataBlock for '170.187.204.221'
766 * Example for IPv6: '20010DB885A3000000008A2E03707334' will be DataBlock for '2001:0db8:85a3:0000:0000:8a2e:0370:7334'
768 * '000000000000000000000000AABBCCDD' will be encoded as 16-sized Datablock, not IPv4 (4 bytes). Is not recommended to
769 * put IPv4 on this way because of ambiguity regarding IPv4-compatible format. It is application responsability to trim
770 * leading zeros in order to use this method for IPv4 source.
773 * @param rawPresentation Input IP address as raw presentation. Must be 8 or 32 sized for IPv4 and IPv6 respectively.
775 * @return Encoded DataBlock
777 static DataBlock rawIpPresentationAsRaw(const std::string & rawPresentation) throw(RuntimeException);
781 * IP Address decoding from raw presentation:
783 * Example for IPv4: 'AABBCCDD' will be '170.187.204.221'
784 * Example for IPv6: '20010DB885A3000000008A2E03707334' will be '2001:0db8:85a3:0000:0000:8a2e:0370:7334'
786 * '000000000000000000000000AABBCCDD' will be internally encoded as 16-sized Datablock, not IPv4 (4 bytes).
787 * Is not recommended to put IPv4 on this way because of ambiguity regarding IPv4-compatible format. It is
788 * application responsability to trim leading zeros in order to use this method for IPv4 source.
791 * @param rawPresentation Input IP address as raw presentation. Must be 8 or 32 sized for IPv4 and IPv6 respectively.
792 * @param normalize Normalize returned address representation, 'false' by default (to avoid IPv4 to IPv6 conversion)
794 * @return Decoded IP address
796 static std::string rawIpPresentationToIpAsString(const std::string & rawPresentation, bool normalize = false) throw(RuntimeException) {
797 return rawIpAsString(rawIpPresentationAsRaw(rawPresentation), normalize);
802 * IP Address decoding to 'human-readable raw presentation':
804 * Example for IPv4: DataBlock for '170.187.204.221' will be 'AABBCCDD' (a pure IPv4 will never contain leading zeros outside of its scope (i.e., 24 zeros on a 32-character presentation)
805 * Example for IPv6: DataBlock for '2001:0db8:85a3:0000:0000:8a2e:0370:7334' will be '20010DB885A3000000008A2E03707334'
807 * DataBlock for '::170.187.204.221' will be represented as IPv4 compatible: '000000000000000000000000AABBCCDD'
810 * @param db Encoded DataBlock with 4 or 16 bytes to represent Ipv4 or Ipv6.
812 * @return Human-readable raw IP presentation
814 static std::string rawIpAsRawIpPresentation(const DataBlock & db) throw(RuntimeException);
818 * Gets the host name (system name)
822 static std::string getHostname() throw();
825 * Gets the domain name
829 static std::string getDomainname() throw();
832 * Gets the FQDN (Fully Qualified Domain Name)
834 * @param hostname Specific provided hostname. Automatically solved if missing. Empty string implies exclusion from FQDN.
835 * @param domainname Specific provided domainname. Automatically solved if missing. Empty string implies exclusion from FQDN.
837 * @return FQDN (<hostname>.<domainname>)
839 static std::string getFQDN(const char *hostname = NULL, const char *domainname = NULL) throw();
842 * Gets the IP based on hostname (#getHostname)
844 * @return Hostname-based IP
846 static std::string getHostnameIP() throw();
850 //////////////////////////////////////////////////////////////////////////////////////////////////
851 // IP Address resources //////////////////////////////////////////////////////////////////////////
852 //////////////////////////////////////////////////////////////////////////////////////////////////
855 * IPv4 subtype (Estrict/Compatible)
859 Estrict = -1, // Initialized,
866 * IPv4 address family detection
868 * @param ip IP address
869 * @param ipv4Type Check for IPv4-compatible (i.e. '::192.168.0.1'), IPv4-mapped (i.e. '2001:0db8:85a3:0000:0000:8a2e:192.168.0.1') or estrict IPv4 format.
871 * @return Boolean for IPv4 nature
873 static bool isIPv4(const std::string & ip, IPv4Type::_v ipv4Type = IPv4Type::Estrict) throw();
876 * IPv6 address family detection
878 * @param ip IP address
880 * @return Boolean for IPv6 nature
882 static bool isIPv6(const std::string & ip) throw();
885 * Convert an IPv4 address to IPv6. Also removes dots from IPv4-mapped format.
887 * @param ipv4 IP Address in dot notation (192.168.1.100)
889 * @return string IPv6 formatted address or launch exception if invalid input
891 static std::string IPv4To6(const std::string & ipv4) throw(RuntimeException);
894 * Normalizes an IP address to long notation. Specially used for IPv6, but valid for IPv4 (via IPv4To6 conversion).
897 * ::1 -> 0000:0000:0000:0000:0000:0000:0000:0001
898 * 2001:db8:85a3::8a2e:370:7334 -> 2001:0db8:85a3:0000:0000:8a2e:0370:7334
900 * @param ip Input IP address
902 * @return Normalized IP address
904 static std::string normalizeIP(const std::string & ip) throw(RuntimeException);
907 * Compare two IP addresses by mean normalization
909 * @param ip1 First IP address compared
910 * @param ip2 Second IP address compared
912 * @return Boolean about IP's comparison
914 static bool sameIP(const std::string & ip1, const std::string & ip2) throw(RuntimeException);
917 * Compare two IP addresses by mean internal comparison after ipv6 preffix restriction
919 * @param ipv6 IPv6 address matched
920 * @param preffixedIpv6 Preffixed IPv6 address (<ipv6>/<preffix length>: only values from 0 (always match) to 128 (maximum restriction) are allowed).
922 * @return Boolean about subnet matching
924 static bool matchIPv6(const std::string & ipv6, const std::string & preffixedIpv6) throw(RuntimeException);
927 * IP Address serialization
929 * @param ip Input IP address
931 * @return Encoded DataBlock
933 static DataBlock ipAsRaw(const std::string & ip) throw(RuntimeException);
936 * IP Address decoding
938 * @param db Encoded DataBlock with 4 or 16 bytes to represent Ipv4 or Ipv6.
939 * @param normalize Normalize returned address representation, 'false' by default (to avoid IPv4 to IPv6 conversion)
941 * @return Decoded IP address
943 static std::string rawIpAsString(const DataBlock & db, bool normalize = false) throw(RuntimeException) {
944 return (rawIpAsString(db.getData(), db.getSize(), normalize));
948 * IP Address decoding
950 * @param buffer Encoded buffer with 4 or 16 bytes to represent Ipv4 or Ipv6.
951 * @param bufferLength Encoded buffer length with 4 or 16 bytes to represent Ipv4 or Ipv6.
952 * @param normalize Normalize returned address representation, 'false' by default (to avoid IPv4 to IPv6 conversion)
954 * @return Decoded IP address
956 static std::string rawIpAsString(const char *buffer, int bufferLength, bool normalize = false) throw(RuntimeException);
959 * Abbreviates an IP address. Specially used for IPv6, but valid for IPv4.
962 * 0000:0000:0000:0000:0000:0000:0000:0001 -> ::1
963 * 2001:0db8:85a3:0000:0000:8a2e:0370:7334 -> 2001:db8:85a3::8a2e:370:7334
965 * @param ip Input IP address
967 * @return Abbreviated IP address
969 static std::string abbreviateIP(const std::string & ip) throw(RuntimeException) {
970 return (rawIpAsString(ipAsRaw(ip)));
976 // socket literal description typedef, vectors and conversion tools
979 * Extract ADDRESS (ip or hostname ro resolve) and PORT from socket literal description ('<ip|hostname>:<port>').
981 * @param literal Socket literal in format '<ip|hostname>:<port>'
982 * @param address Address extracted by reference
983 * @param port Port extracted by reference
985 static void getAddressAndPortFromSocketLiteral(const std::string &literal, std::string &address, int &port) throw();
988 * Translate pipe-separated socket literal list into Address/Port vector.
990 * @param list Comma-separated Address/Port list. I.e.: '10.95.10.25:4000,10.95.10.25:4001', or 'fed1:4000,fed2:4001'
991 * @return Address/Port socket items vector
993 static socket_v getSocketVectorFromString(const std::string & list) throw();
996 * Translate Address/Port vector into comma-separated Address/Port list.
998 * @param socketVector Address/Port vector
1000 * @return Comma-separated Address/Port list. I.e.: '10.95.10.25:4000,10.95.10.25:4001', or 'fed1:4000,fed2:4001'
1002 static std::string socketVectorAsString(const socket_v & socketVector) throw();
1006 Endianess of the system
1008 @result Returns true when the system is little endian, false if big endian
1010 static bool littleEndian() throw();
1013 Encodes an integer number with 32 bits over a buffer with at least 4 bytes of length.
1014 @param result Buffer where the number is encoded.
1015 @param n Number to encode.
1016 \return Buffer with the encoded number.
1018 static const char* codeInteger(char* result, const int n) throw();
1021 Encodes an integer number with 16 bits over a buffer with at least 2 bytes of length.
1022 @param result Buffer where the number is encoded.
1023 @param n Number to encode.
1024 \return Buffer with the encoded number.
1026 static const char* codeShort(char* result, const short int n) throw();
1029 Encodes an integer number with 64 bits over a buffer with at least 8 bytes of length.
1030 @param result Buffer where the number is encoded.
1031 @param n Number to encode.
1032 \return Buffer with the encoded number.
1034 static const char* codeInteger64(char* result, const S64 n) throw();
1037 Encodes a floating number with 32 bits (according to the standard IEEE-754) over a buffer with at least 4 bytes of length.
1038 @param result Buffer where the number is encoded.
1039 @param n Number to encode.
1040 \return Buffer with the encoded number.
1042 static const char* codeFloat(char* result, const float n) throw();
1045 Encodes a floating number with 64 bits (according to the standard IEEE-754) over a buffer with at least 8 bytes of length.
1046 @param result Buffer where the number is encoded.
1047 @param n Number to encode.
1048 \return Buffer with the encoded number.
1050 static const char* codeDouble(char* result, const double n) throw();
1053 Decodes an 32 bits integer number contained in a 4-bytes buffer.
1054 @param data Buffer with the encoded number.
1055 @return Value for the number contained in the buffer.
1057 static int decodeInteger(const char* data) throw();
1060 Decodes an 16 bits integer number contained in a 2-bytes buffer.
1061 @param data Buffer with the encoded number.
1062 @return Value for the number contained in the buffer.
1064 static short int decodeShort(const char* data) throw();
1067 Decodes an 64 bits integer number contained in a 8-bytes buffer.
1068 @param data Buffer with the encoded number.
1069 @return Value for the number contained in the buffer.
1071 static S64 decodeInteger64(const char* data) throw();
1074 Decodes an 32 bits floating number (according to the standard IEEE-754) contained in a 4-bytes buffer.
1075 @param data Buffer with the encoded number.
1076 @return Value for the number contained in the buffer.
1078 static float decodeFloat(const char* data) throw();
1081 Decodes an 64 bits floating number (according to the standard IEEE-754) contained in a 8-bytes buffer.
1082 @param data Buffer with the encoded number.
1083 @return Value for the number contained in the buffer.
1085 static double decodeDouble(const char* data) throw();
1089 * Decodes an ISUP Number (called or calling party number).
1091 * @param buffer Isup number content buffer.
1092 * @param length Isup number content length.
1093 * @param isupNumber Isup number decoded by reference.
1094 * @param calledOrCalling True for called party number, false for calling
1096 static void decodeIsupNumber(const char *buffer, int length, isup_number_t & isupNumber, bool calledOrCalling) throw(RuntimeException);
1099 * Encodes an ISUP Number (called or calling party number).
1101 * @param isupNumber Isup number.
1102 * @param calledOrCalling True for called party number, false for calling
1103 * @param buffer Isup number content encoded buffer.
1104 * @param length Isup number content encoded length.
1106 static void codeIsupNumber(const isup_number_t & isupNumber, bool calledOrCalling, char * buffer, int & length) throw(RuntimeException);
1109 * Encodes an ISUP Number (called or calling party number).
1111 * @param isupNumber Isup number.
1112 * @param calledOrCalling True for called party number, false for calling
1113 * @param target Isup number octet string.
1115 static void codeIsupNumber(const isup_number_t & isupNumber, bool calledOrCalling, std::string & target) throw(RuntimeException);