Skip to content
This repository was archived by the owner on Aug 31, 2021. It is now read-only.

Commit 86aa7dc

Browse files
committed
[[ Foundation ]] Add MCStringIsInteger
This patch adds the MCStringIsInteger method which checks that the given string is a strict integer - i.e. one matching the regex -?(0|[1-9][0-9]*).
1 parent 9d05f00 commit 86aa7dc

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

libfoundation/include/foundation.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2284,6 +2284,9 @@ MC_DLLEXPORT bool MCStringIsMutable(const MCStringRef string);
22842284

22852285
// Returns true if the string is the empty string.
22862286
MC_DLLEXPORT bool MCStringIsEmpty(MCStringRef string);
2287+
2288+
// Returns true if the string is a (strict) integer string <-?(0|[1-9][0-9]*)>*/
2289+
MC_DLLEXPORT bool MCStringIsInteger(MCStringRef string);
22872290

22882291
// Returns true if the the string only requires native characters to represent.
22892292
MC_DLLEXPORT bool MCStringCanBeNative(MCStringRef string);

libfoundation/src/foundation-string.cpp

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2947,6 +2947,47 @@ bool MCStringIsEmpty(MCStringRef string)
29472947
return string == nil || MCStringGetLength(string) == 0;
29482948
}
29492949

2950+
template<typename T>
2951+
static inline bool __MCStringIsInteger(const T *p_chars, uindex_t p_length)
2952+
{
2953+
uindex_t i = 0;
2954+
2955+
if (p_chars[i] == '-')
2956+
i++;
2957+
2958+
if (i == p_length)
2959+
return false;
2960+
2961+
if (p_chars[i] == '0')
2962+
{
2963+
return i + 1 == p_length;
2964+
}
2965+
2966+
for(; i < p_length; i++)
2967+
{
2968+
if (!isdigit(p_chars[i]))
2969+
{
2970+
return false;
2971+
}
2972+
}
2973+
2974+
return true;
2975+
}
2976+
2977+
MC_DLLEXPORT_DEF
2978+
bool MCStringIsInteger(MCStringRef self)
2979+
{
2980+
__MCAssertIsString(self);
2981+
2982+
if (__MCStringIsIndirect(self))
2983+
self = self -> string;
2984+
2985+
if (__MCStringIsNative(self))
2986+
return __MCStringIsInteger(self->native_chars, self->char_count);
2987+
2988+
return __MCStringIsInteger(self->chars, self->char_count);
2989+
}
2990+
29502991
MC_DLLEXPORT_DEF
29512992
bool MCStringSubstringIsEqualTo(MCStringRef self, MCRange p_sub, MCStringRef p_other, MCStringOptions p_options)
29522993
{

0 commit comments

Comments
 (0)