Browse Source

str: faux_str_getline()

Serj Kalichev 2 years ago
parent
commit
c06b474b85
3 changed files with 42 additions and 20 deletions
  1. 1 0
      faux/faux.map
  2. 1 20
      faux/str.h
  3. 40 0
      faux/str/str.c

+ 1 - 0
faux/faux.map

@@ -302,6 +302,7 @@ FAUX_2.0 {
 		faux_str_ndecode;
 		faux_str_encode;
 		faux_str_equal_part;
+		faux_str_getline;
 
 		faux_sysdb_getpwnam;
 		faux_sysdb_getpwuid;

+ 1 - 20
faux/str.h

@@ -43,26 +43,7 @@ char *faux_str_c_bin(const char *src, size_t n);
 
 char *faux_str_nextword(const char *str, const char **saveptr,
 	const char *alt_quotes, bool_t *qclosed);
-
-
-//const char *faux_str_suffix(const char *string);
-/*
- * These are the escape characters which are used by default when 
- * expanding variables. These characters will be backslash escaped
- * to prevent them from being interpreted in a script.
- *
- * This is a security feature to prevent users from arbitarily setting
- * parameters to contain special sequences.
- */
-//extern const char *faux_str_esc_default;
-//extern const char *faux_str_esc_regex;
-//extern const char *faux_str_esc_quoted;
-
-//char *faux_str_decode(const char *string);
-//char *faux_str_ndecode(const char *string, unsigned int len);
-//char *faux_str_encode(const char *string, const char *escape_chars);
-//unsigned int faux_str_equal_part(const char *str1, const char *str2,
-//	bool_t utf8);
+char *faux_str_getline(const char *str, const char **saveptr);
 
 C_DECL_END
 

+ 40 - 0
faux/str/str.c

@@ -846,3 +846,43 @@ bool_t faux_str_is_empty(const char *str)
 
 	return BOOL_FALSE;
 }
+
+
+/** @brief Gets line from multiline string.
+ *
+ * @param [in] str String to analyze.
+ * @param [out] saveptr Pointer to the position after found EOL.
+ * @return Allocated line or NULL if string is empty.
+ */
+char *faux_str_getline(const char *str, const char **saveptr)
+{
+	const char *find_pos = NULL;
+	const char *eol = "\n\r";
+
+	assert(str);
+	if (!str)
+		return NULL;
+	if ('\0' == *str) {
+		if (saveptr)
+			*saveptr = str;
+		return NULL;
+	}
+
+	find_pos = faux_str_chars(str, eol);
+	if (find_pos) {
+		size_t len = find_pos - str;
+		char *res = NULL;
+		res = faux_zmalloc(len + 1);
+		if (len > 0)
+			memcpy(res, str, len);
+		if (saveptr)
+			*saveptr = find_pos + 1;
+		return res;
+	}
+
+	// Line without EOL
+	if (saveptr)
+		*saveptr = str + strlen(str);
+
+	return faux_str_dup(str);
+}