/*- * Copyright (c) 2014 Pietro Cerutti * All rights reserved. * * This code is derived from software contributed to Berkeley by * Chris Torek. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD: head/lib/libc/string/memcmp.c 251069 2013-05-28 20:57:40Z emaste $"); #include /* * Compare memory regions. */ int memcmp(const void *s1, const void *s2, size_t n) { const size_t *p1, *p2; /* Array traversal sizeof(size_t) bytes at a time */ const char *c1, *c2; /* Array traversal 1 byte at a time */ if (n == 0) return (0); /* If the two args are aligned, compare them one word at a time. */ p1 = s1; p2 = s2; if (((size_t)s1 & (sizeof(size_t) - 1)) == 0 && ((size_t)s2 & (sizeof(size_t) - 1)) == 0) { while (n >= sizeof(size_t) && *p1 == *p2) { ++p1; ++p2; n -= sizeof(size_t); } if (n == 0) return (0); } /* Usual byte-by-byte comparison. */ c1 = (const char *)p1; c2 = (const char *)p2; while (--n && *c1 == *c2) { ++c1; ++c2; } return (*c1 - *c2); }