utils: custom strtof and strndup moved into utils

The custom implementations of 'strtof' and 'strndup'
present in the svg loader have been moved into a new
'utils' directory (strToFloat and strDuplicate, respectively).
This commit is contained in:
Mira Grudzinska 2023-08-01 23:43:33 +02:00 committed by Hermet Park
parent 07c05b52dc
commit 480917651a
10 changed files with 285 additions and 204 deletions

View file

@ -55,7 +55,7 @@
#include "tvgXmlParser.h"
#include "tvgSvgLoader.h"
#include "tvgSvgSceneBuilder.h"
#include "tvgSvgUtil.h"
#include "tvgStr.h"
#include "tvgSvgCssStyle.h"
#include "tvgMath.h"
@ -106,7 +106,7 @@ static bool _parseNumber(const char** content, float* number)
{
char* end = nullptr;
*number = svgUtilStrtof(*content, &end);
*number = strToFloat(*content, &end);
//If the start of string is not number
if ((*content) == end) return false;
//Skip comma if any
@ -162,7 +162,7 @@ static void _parseAspectRatio(const char** content, AspectRatioAlign* align, Asp
*/
static float _toFloat(const SvgParser* svgParse, const char* str, SvgParserLengthType type)
{
float parsedValue = svgUtilStrtof(str, nullptr);
float parsedValue = strToFloat(str, nullptr);
if (strstr(str, "cm")) parsedValue *= PX_PER_CM;
else if (strstr(str, "mm")) parsedValue *= PX_PER_MM;
@ -190,7 +190,7 @@ static float _gradientToFloat(const SvgParser* svgParse, const char* str, bool&
{
char* end = nullptr;
float parsedValue = svgUtilStrtof(str, &end);
float parsedValue = strToFloat(str, &end);
isPercentage = false;
if (strstr(str, "%")) {
@ -213,7 +213,7 @@ static float _toOffset(const char* str)
char* end = nullptr;
auto strEnd = str + strlen(str);
float parsedValue = svgUtilStrtof(str, &end);
float parsedValue = strToFloat(str, &end);
end = _skipSpace(end, nullptr);
auto ptr = strstr(str, "%");
@ -230,7 +230,7 @@ static float _toOffset(const char* str)
static int _toOpacity(const char* str)
{
char* end = nullptr;
float opacity = svgUtilStrtof(str, &end);
float opacity = strToFloat(str, &end);
if (end) {
if (end[0] == '%' && end[1] == '\0') return lrint(opacity * 2.55f);
@ -358,7 +358,7 @@ static void _parseDashArray(SvgLoaderData* loader, const char *str, SvgDash* das
while (*str) {
str = _skipComma(str);
float parsedValue = svgUtilStrtof(str, &end);
float parsedValue = strToFloat(str, &end);
if (str == end) break;
if (parsedValue <= 0.0f) break;
if (*end == '%') {
@ -389,7 +389,7 @@ static char* _idFromUrl(const char* url)
int i = 0;
while (url[i] > ' ' && url[i] != ')' && url[i] != '\'') ++i;
return svgUtilStrndup(url, i);
return strDuplicate(url, i);
}
@ -397,7 +397,7 @@ static unsigned char _parseColor(const char* value, char** end)
{
float r;
r = svgUtilStrtof(value, end);
r = strToFloat(value, end);
*end = _skipSpace(*end, nullptr);
if (**end == '%') {
r = 255 * r / 100;
@ -639,7 +639,7 @@ static char* _parseNumbersArray(char* str, float* points, int* ptCount, int len)
str = _skipSpace(str, nullptr);
while ((count < len) && (isdigit(*str) || *str == '-' || *str == '+' || *str == '.')) {
points[count++] = svgUtilStrtof(str, &end);
points[count++] = strToFloat(str, &end);
str = end;
str = _skipSpace(str, nullptr);
if (*str == ',') ++str;
@ -889,7 +889,7 @@ static bool _attrParseSvgNode(void* data, const char* key, const char* value)
} else if (!strcmp(key, "style")) {
return simpleXmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, loader);
#ifdef THORVG_LOG_ENABLED
} else if ((!strcmp(key, "x") || !strcmp(key, "y")) && fabsf(svgUtilStrtof(value, nullptr)) > FLT_EPSILON) {
} else if ((!strcmp(key, "x") || !strcmp(key, "y")) && fabsf(strToFloat(value, nullptr)) > FLT_EPSILON) {
TVGLOG("SVG", "Unsupported attributes used [Elements type: Svg][Attribute: %s][Value: %s]", key, value);
#endif
} else {
@ -975,7 +975,7 @@ static void _handleStrokeLineJoinAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode*
static void _handleStrokeMiterlimitAttr(SvgLoaderData* loader, SvgNode* node, const char* value)
{
char* end = nullptr;
const float miterlimit = svgUtilStrtof(value, &end);
const float miterlimit = strToFloat(value, &end);
// https://www.w3.org/TR/SVG2/painting.html#LineJoin
// - A negative value for stroke-miterlimit must be treated as an illegal value.
@ -1137,7 +1137,7 @@ static bool _parseStyleAttr(void* data, const char* key, const char* value, bool
while (size > 0 && isspace(value[size - 1])) {
size--;
}
value = svgUtilStrndup(value, size);
value = strDuplicate(value, size);
importance = true;
}
if (style) {

View file

@ -55,7 +55,7 @@
#include <ctype.h>
#include "tvgSvgLoaderCommon.h"
#include "tvgSvgPath.h"
#include "tvgSvgUtil.h"
#include "tvgStr.h"
/************************************************************************/
/* Internal Class Implementation */
@ -74,7 +74,7 @@ static char* _skipComma(const char* content)
static bool _parseNumber(char** content, float* number)
{
char* end = NULL;
*number = svgUtilStrtof(*content, &end);
*number = strToFloat(*content, &end);
//If the start of string is not number
if ((*content) == end) return false;
//Skip comma if any

View file

@ -56,6 +56,7 @@
#include "tvgSvgSceneBuilder.h"
#include "tvgSvgPath.h"
#include "tvgSvgUtil.h"
#include "tvgStr.h"
/************************************************************************/
/* Internal Class Implementation */

View file

@ -21,19 +21,12 @@
*/
#include <cstring>
#include <math.h>
#include <memory.h>
#include "tvgSvgUtil.h"
/************************************************************************/
/* Internal Class Implementation */
/************************************************************************/
static inline bool _floatExact(float a, float b)
{
return memcmp(&a, &b, sizeof(float)) == 0;
}
static uint8_t _hexCharToDec(const char c)
{
if (c >= 'a') return c - 'a' + 10;
@ -55,167 +48,6 @@ static uint8_t _base64Value(const char chr)
/* External Class Implementation */
/************************************************************************/
/*
* https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/strtof-strtof-l-wcstof-wcstof-l?view=msvc-160
*
* src should be one of the following form :
*
* [whitespace] [sign] {digits [radix digits] | radix digits} [{e | E} [sign] digits]
* [whitespace] [sign] {INF | INFINITY}
* [whitespace] [sign] NAN [sequence]
*
* No hexadecimal form supported
* no sequence supported after NAN
*/
float svgUtilStrtof(const char *nPtr, char **endPtr)
{
if (endPtr) *endPtr = (char*)(nPtr);
if (!nPtr) return 0.0f;
auto a = nPtr;
auto iter = nPtr;
auto val = 0.0f;
unsigned long long integerPart = 0;
int minus = 1;
//ignore leading whitespaces
while (isspace(*iter)) iter++;
//signed or not
if (*iter == '-') {
minus = -1;
iter++;
} else if (*iter == '+') {
iter++;
}
if (tolower(*iter) == 'i') {
if ((tolower(*(iter + 1)) == 'n') && (tolower(*(iter + 2)) == 'f')) iter += 3;
else goto error;
if (tolower(*(iter)) == 'i') {
if ((tolower(*(iter + 1)) == 'n') && (tolower(*(iter + 2)) == 'i') && (tolower(*(iter + 3)) == 't') && (tolower(*(iter + 4)) == 'y')) iter += 5;
else goto error;
}
if (endPtr) *endPtr = (char *)(iter);
return (minus == -1) ? -INFINITY : INFINITY;
}
if (tolower(*iter) == 'n') {
if ((tolower(*(iter + 1)) == 'a') && (tolower(*(iter + 2)) == 'n')) iter += 3;
else goto error;
if (endPtr) *endPtr = (char *)(iter);
return (minus == -1) ? -NAN : NAN;
}
//Optional: integer part before dot
if (isdigit(*iter)) {
for (; isdigit(*iter); iter++) {
integerPart = integerPart * 10ULL + (unsigned long long)(*iter - '0');
}
a = iter;
} else if (*iter != '.') {
goto success;
}
val = static_cast<float>(integerPart);
//Optional: decimal part after dot
if (*iter == '.') {
unsigned long long decimalPart = 0;
unsigned long long pow10 = 1;
int count = 0;
iter++;
if (isdigit(*iter)) {
for (; isdigit(*iter); iter++, count++) {
if (count < 19) {
decimalPart = decimalPart * 10ULL + + static_cast<unsigned long long>(*iter - '0');
pow10 *= 10ULL;
}
}
} else if (isspace(*iter)) { //skip if there is a space after the dot.
a = iter;
goto success;
}
val += static_cast<float>(decimalPart) / static_cast<float>(pow10);
a = iter;
}
//Optional: exponent
if (*iter == 'e' || *iter == 'E') {
++iter;
//Exception: svg may have 'em' unit for fonts. ex) 5em, 10.5em
if ((*iter == 'm') || (*iter == 'M')) {
//TODO: We don't support font em unit now, but has to multiply val * font size later...
a = iter + 1;
goto success;
}
//signed or not
int minus_e = 1;
if (*iter == '-') {
minus_e = -1;
++iter;
} else if (*iter == '+') {
iter++;
}
unsigned int exponentPart = 0;
if (isdigit(*iter)) {
while (*iter == '0') iter++;
for (; isdigit(*iter); iter++) {
exponentPart = exponentPart * 10U + static_cast<unsigned int>(*iter - '0');
}
} else if (!isdigit(*(a - 1))) {
a = nPtr;
goto success;
} else if (*iter == 0) {
goto success;
}
//if ((_floatExact(val, 2.2250738585072011f)) && ((minus_e * static_cast<int>(exponentPart)) <= -308)) {
if ((_floatExact(val, 1.175494351f)) && ((minus_e * static_cast<int>(exponentPart)) <= -38)) {
//val *= 1.0e-308f;
val *= 1.0e-38f;
a = iter;
goto success;
}
a = iter;
auto scale = 1.0f;
while (exponentPart >= 8U) {
scale *= 1E8;
exponentPart -= 8U;
}
while (exponentPart > 0U) {
scale *= 10.0f;
exponentPart--;
}
val = (minus_e == -1) ? (val / scale) : (val * scale);
} else if ((iter > nPtr) && !isdigit(*(iter - 1))) {
a = nPtr;
goto success;
}
success:
if (endPtr) *endPtr = (char*)(a);
return minus * val;
error:
if (endPtr) *endPtr = (char*)(nPtr);
return 0.0f;
}
string svgUtilURLDecode(const char *src)
{
if (!src) return nullptr;
@ -274,17 +106,4 @@ string svgUtilBase64Decode(const char *src)
src += 4;
}
return decoded;
}
char* svgUtilStrndup(const char* str, size_t n)
{
auto len = strlen(str);
if (len < n) n = len;
auto ret = (char*)malloc(n + 1);
if (!ret) return nullptr;
ret[n] = '\0';
return (char*)memcpy(ret, str, n);
}

View file

@ -25,11 +25,7 @@
#include "tvgCommon.h"
float svgUtilStrtof(const char *nPtr, char **endPtr);
string svgUtilURLDecode(const char *src);
string svgUtilBase64Decode(const char *src);
char* svgUtilStrndup(const char* str, size_t n);
#endif //_TVG_SVG_UTIL_H_

View file

@ -33,7 +33,7 @@
#endif
#include "tvgXmlParser.h"
#include "tvgSvgUtil.h"
#include "tvgStr.h"
/************************************************************************/
/* Internal Class Implementation */
@ -557,10 +557,10 @@ const char* simpleXmlParseCSSAttribute(const char* buf, unsigned bufLength, char
}
if (p == itr) *tag = strdup("all");
else *tag = svgUtilStrndup(itr, p - itr);
else *tag = strDuplicate(itr, p - itr);
if (p == itrEnd) *name = nullptr;
else *name = svgUtilStrndup(p + 1, itrEnd - p - 1);
else *name = strDuplicate(p + 1, itrEnd - p - 1);
return (nextElement ? nextElement + 1 : nullptr);
}

View file

@ -38,10 +38,11 @@ endif
subdir('lib')
subdir('utils')
subdir('loaders')
subdir('savers')
thorvg_lib_dep = [common_dep, loader_dep, saver_dep]
thorvg_lib_dep = [common_dep, utils_dep, loader_dep, saver_dep]
if host_machine.system() != 'windows'
thread_dep = meson.get_compiler('cpp').find_library('pthread')
thorvg_lib_dep += [thread_dep]

8
src/utils/meson.build Normal file
View file

@ -0,0 +1,8 @@
source_file = [
'tvgStr.h',
'tvgStr.cpp'
]
utils_dep = declare_dependency(
include_directories : include_directories('.'),
sources : source_file)

223
src/utils/tvgStr.cpp Normal file
View file

@ -0,0 +1,223 @@
/*
* Copyright (c) 2020 - 2023 the ThorVG project. All rights reserved.
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "config.h"
#include <cstring>
#include <memory.h>
#include "tvgMath.h"
#include "tvgStr.h"
#if defined(THORVG_SVG_LOADER_SUPPORT) || defined(THORVG_LOTTIE_LOADER_SUPPORT)
/************************************************************************/
/* Internal Class Implementation */
/************************************************************************/
static inline bool _floatExact(float a, float b)
{
return memcmp(&a, &b, sizeof(float)) == 0;
}
/************************************************************************/
/* External Class Implementation */
/************************************************************************/
namespace tvg {
/*
* https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/strtof-strtof-l-wcstof-wcstof-l?view=msvc-160
*
* src should be one of the following form :
*
* [whitespace] [sign] {digits [radix digits] | radix digits} [{e | E} [sign] digits]
* [whitespace] [sign] {INF | INFINITY}
* [whitespace] [sign] NAN [sequence]
*
* No hexadecimal form supported
* no sequence supported after NAN
*/
float strToFloat(const char *nPtr, char **endPtr)
{
if (endPtr) *endPtr = (char *) (nPtr);
if (!nPtr) return 0.0f;
auto a = nPtr;
auto iter = nPtr;
auto val = 0.0f;
unsigned long long integerPart = 0;
int minus = 1;
//ignore leading whitespaces
while (isspace(*iter)) iter++;
//signed or not
if (*iter == '-') {
minus = -1;
iter++;
} else if (*iter == '+') {
iter++;
}
if (tolower(*iter) == 'i') {
if ((tolower(*(iter + 1)) == 'n') && (tolower(*(iter + 2)) == 'f')) iter += 3;
else goto error;
if (tolower(*(iter)) == 'i') {
if ((tolower(*(iter + 1)) == 'n') && (tolower(*(iter + 2)) == 'i') && (tolower(*(iter + 3)) == 't') &&
(tolower(*(iter + 4)) == 'y'))
iter += 5;
else goto error;
}
if (endPtr) *endPtr = (char *) (iter);
return (minus == -1) ? -INFINITY : INFINITY;
}
if (tolower(*iter) == 'n') {
if ((tolower(*(iter + 1)) == 'a') && (tolower(*(iter + 2)) == 'n')) iter += 3;
else goto error;
if (endPtr) *endPtr = (char *) (iter);
return (minus == -1) ? -NAN : NAN;
}
//Optional: integer part before dot
if (isdigit(*iter)) {
for (; isdigit(*iter); iter++) {
integerPart = integerPart * 10ULL + (unsigned long long) (*iter - '0');
}
a = iter;
} else if (*iter != '.') {
goto success;
}
val = static_cast<float>(integerPart);
//Optional: decimal part after dot
if (*iter == '.') {
unsigned long long decimalPart = 0;
unsigned long long pow10 = 1;
int count = 0;
iter++;
if (isdigit(*iter)) {
for (; isdigit(*iter); iter++, count++) {
if (count < 19) {
decimalPart = decimalPart * 10ULL + +static_cast<unsigned long long>(*iter - '0');
pow10 *= 10ULL;
}
}
} else if (isspace(*iter)) { //skip if there is a space after the dot.
a = iter;
goto success;
}
val += static_cast<float>(decimalPart) / static_cast<float>(pow10);
a = iter;
}
//Optional: exponent
if (*iter == 'e' || *iter == 'E') {
++iter;
//Exception: svg may have 'em' unit for fonts. ex) 5em, 10.5em
if ((*iter == 'm') || (*iter == 'M')) {
//TODO: We don't support font em unit now, but has to multiply val * font size later...
a = iter + 1;
goto success;
}
//signed or not
int minus_e = 1;
if (*iter == '-') {
minus_e = -1;
++iter;
} else if (*iter == '+') {
iter++;
}
unsigned int exponentPart = 0;
if (isdigit(*iter)) {
while (*iter == '0') iter++;
for (; isdigit(*iter); iter++) {
exponentPart = exponentPart * 10U + static_cast<unsigned int>(*iter - '0');
}
} else if (!isdigit(*(a - 1))) {
a = nPtr;
goto success;
} else if (*iter == 0) {
goto success;
}
//if ((_floatExact(val, 2.2250738585072011f)) && ((minus_e * static_cast<int>(exponentPart)) <= -308)) {
if ((_floatExact(val, 1.175494351f)) && ((minus_e * static_cast<int>(exponentPart)) <= -38)) {
//val *= 1.0e-308f;
val *= 1.0e-38f;
a = iter;
goto success;
}
a = iter;
auto scale = 1.0f;
while (exponentPart >= 8U) {
scale *= 1E8;
exponentPart -= 8U;
}
while (exponentPart > 0U) {
scale *= 10.0f;
exponentPart--;
}
val = (minus_e == -1) ? (val / scale) : (val * scale);
} else if ((iter > nPtr) && !isdigit(*(iter - 1))) {
a = nPtr;
goto success;
}
success:
if (endPtr) *endPtr = (char *)(a);
return minus * val;
error:
if (endPtr) *endPtr = (char *)(nPtr);
return 0.0f;
}
char* strDuplicate(const char *str, size_t n)
{
auto len = strlen(str);
if (len < n) n = len;
auto ret = (char *) malloc(n + 1);
if (!ret) return nullptr;
ret[n] = '\0';
return (char *) memcpy(ret, str, n);
}
}
#endif

33
src/utils/tvgStr.h Normal file
View file

@ -0,0 +1,33 @@
/*
* Copyright (c) 2020 - 2023 the ThorVG project. All rights reserved.
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef _TVG_STR_H_
#define _TVG_STR_H_
namespace tvg
{
float strToFloat(const char *nPtr, char **endPtr);
char* strDuplicate(const char *str, size_t n);
}
#endif //_TVG_STR_H_