Re: Some string parsing functions



Owen Taylor wrote:

> Pavel Císler <pavel@eazel.com> writes:
>
> > > > gint g_str_find_substr_index_start_from (const gchar *str, guint startpos, const gchar *str_to_find);
> > >
> > > strstr (str + starpos, str_to_find)
> > >
> >
> > Not quite. You would probably want the following semantics (probably implemented more efficiently):
> >
> > const char *match;
> >
> > if (strlen(str) <= startpos)
> >     return -1;
> >
> > match = strstr(str + startpos, str_to_find);
> >
> > if (!match)
> >     return -1;
> >
> > return match-str;
> >
> > which would indeed justify wrapping it in a call.
>
> I don't see any reason to invent new semantics here. The strstr()
> semantics seem convenient enough to me.
>
> > > > gint g_str_find_substr_index_right (const gchar *str, const gchar *str_to_find);
> > >
> > > > gchar *g_str_copy_substr (const gchar *str, guint index, guint count);
> > >
> > > g_strndup (str + index, count);
> > >
> > > > gchar *g_str_copy_substr_index (const gchar *str, guint startpos, guint endpos);
> > >
> > > g_strndup (str + starpos, endpos - startpos);
> > >
> >
> > These would also be more convenient if they checked that the string you are trying to copy is long enough, again justifying the respective
> > call.
>
> g_strndup already does that, pretty much. The only harm if you
> ask for more characters than there are is that you'll allocate
> enough memory for the number of characters you asked for, instead
> of the number of bytes there are total.
>

Hi Owen,

I think you missed my point on both counts, I must have not made myself clear enough. Suppose you get passed a string "foo" in char *bar and
call

strstr(bar + 5, "match this");

- strstr will end up being passed a garbage pointer, past the original string. Except for the cases where you know that bar is at least as long
as the startpos index, you will need to call strlen on bar to make sure you don't run off it's end.

Same goes for the copy calls - using simple g_strndup will only work if you know that the source string is at least as long as the startpos. If
startpos is longer than strlen(str) + 1, you will attempt to copy garbage.

I'm not saying I'd use any of the proposed calls very often, I just don't agree with your dismissal because they are not simply replaceable by
strstr or g_strndup respectively and they would have utility in a full featured string library.

Pavel







[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]