git/list[1] front-page[2] threads[3] people[4] search[5] about
 

Re: [PATCH] general style: replaces memcmp() with proper starts_with()

From
Jeff King <peff@peff.net>
Date
Mar 13, 2014, 17:55 UTC
Message-ID
<20140313175515.GA18897@sigill.intra.peff.net>
In-Reply-To
<xmqq4n32j8i7.fsf@gitster.dls.corp.google.com>
On Thu, Mar 13, 2014 at 10:47:28AM -0700, Junio C Hamano wrote:
Show 17 quoted lines
> >> --- a/builtin/cat-file.c
> >> +++ b/builtin/cat-file.c
> >> @@ -82,7 +82,7 @@ static int cat_one_file(int opt, const char *exp_type, const char *obj_name)
> >>  				enum object_type type;
> >>  				unsigned long size;
> >>  				char *buffer = read_sha1_file(sha1, &type, &size);
> >> -				if (memcmp(buffer, "object ", 7) ||
> >> +				if (!starts_with(buffer, "object ") ||
> >
> > [...]
> >
> >> The original hunks show that the code knows and relies on magic
> >> numbers 7 and 8 very clearly and there are rooms for improvement.
> >
> > Like: what if the file is empty?
> 
> Yes.

I think this one is actually OK. The result of read_sha1_file is NUL-terminated, and we know that starts_with reads byte-by-byte (the prior memcmp is wrong, but only if you care about accessing bytes past the end of the NUL).

That whole piece of code seems silly, though, IMHO. It should be using parse_tag or peel_to_type.

-Peff
Previous: Junio C Hamano
Message 22 of 22 in “general style: replaces memcmp() with proper starts_with()”
  1. general style: replaces memcmp() with proper starts_with()Quint Guvernator, Mar 12, 2014
  2. Jeff KingMar 12, 2014
  3. Junio C HamanoMar 12, 2014
  4. Jeff KingMar 12, 2014
  5. Junio C HamanoMar 12, 2014
  6. Jeff KingMar 12, 2014
  7. Jeff KingMar 12, 2014
  8. Jeff KingMar 12, 2014
  9. Junio C HamanoMar 12, 2014
  10. Quint GuvernatorMar 13, 2014
  11. Junio C HamanoMar 13, 2014
  12. Jeff KingMar 14, 2014
  13. Quint GuvernatorMar 14, 2014
  14. Junio C HamanoMar 14, 2014
  15. René ScharfeMar 12, 2014
  16. David KastrupMar 12, 2014
  17. René ScharfeMar 12, 2014
  18. David KastrupMar 12, 2014
  19. Junio C HamanoMar 12, 2014
  20. David KastrupMar 13, 2014
  21. Junio C HamanoMar 13, 2014
  22. Jeff KingMar 13, 2014

Read the whole thread, see it on lore, or plain text.

$ cat FOOTERMessages come from the public archive at lore.kernel.org/git, fetched every hour. The front page is chosen and written each morning by an AI editor and can be wrong; the threads themselves are the record. About and API. For agents: an MCP server at https://gitlist.dev/mcp, and any thread, story or person page as Markdown by adding .md to its URL (or sending Accept: text/markdown). Details in /llms.txt.