wooksong / contributon2019-nns

7 stars 6 forks source link

Apply regular expression if possible #14

Closed wooksong closed 5 years ago

wooksong commented 5 years ago

In order to check matching patterns in a variable, we have used combined if-statements a lot. This is obviously very simple way, but also inefficient way IMO.

For example, Talse could be handled as True in the following code.

 71 static gboolean                                                                 
 72 _parse_bool_string (const gchar * strval, gboolean def)                         
 73 {                                                                               
 74   gboolean res = def;                                                           
 75                                                                                 
 76   if (strval) {                                                                 
 77     /* 1/0, true/false, t/f, yes/no, on/off. case incensitive. */               
 78     if (strval[0] == '1' || strval[0] == 't' || strval[0] == 'T' ||             
 79         strval[0] == 'y' || strval[0] == 'Y' ||                                 
 80         !g_ascii_strncasecmp ("on", strval, 2)) {                               
 81       res = TRUE;                                                               
 82     } else if (strval[0] == '0' || strval[0] == 'f' || strval[0] == 'F' ||      
 83         strval[0] == 'n' || strval[0] == 'N' ||                                 
 84         !g_ascii_strncasecmp ("of", strval, 2)) {                               
 85       res = FALSE;                                                              
 86     }                                                                           
 87   }                                                                             
 88                                                                                 
 89   return res;                                                                   
 90 }                   

How about applying regular expressions to such logics in our project?

abcinje commented 5 years ago

다음과 같이 정규 표현식을 적용해 보았습니다.

#include <regex.h>

// . . .

static gboolean
_parse_bool_string (const gchar * strval, gboolean def)
{
  gboolean res = def;

  regex_t reg_true, reg_false;
  regcomp (&reg_true, "^([1ty]|on).*", REG_EXTENDED | REG_ICASE | REG_NOSUB);
  regcomp (&reg_false, "^([0fn]|of).*", REG_EXTENDED | REG_ICASE | REG_NOSUB);

  if (strval) {
    /* 1/0, true/false, t/f, yes/no, on/off. case incensitive. */
    if (!regexec (&reg_true, strval, 0, 0, 0)) {
      res = TRUE;
    } else if (!regexec (&reg_false, strval, 0, 0, 0)) {
      res = FALSE;
    }
  }

  regfree (&reg_true);
  regfree (&reg_false);
  return res;
}
wooksong commented 5 years ago

Merged!