/*-
 * Copyright (c) 2007 Sean Farley <sean-freebsd@farley.org>
 * All rights reserved.
 *
 * 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,
 *    without modification, immediately at the beginning of the file.
 * 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <sys/limits.h>
#include <sys/param.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


#if LONG_BIT == 64
typedef uint64_t word_t;
static const word_t LowBitMask = 0x0101010101010101ULL;
static const word_t HighBitMask = 0x8080808080808080ULL;
#elif LONG_BIT == 32
typedef uint32_t word_t;
static const word_t LowBitMask = 0x01010101UL;
static const word_t HighBitMask = 0x80808080UL;
#else
#error word size not supported
#endif


/*
 * String length calculated by first searching for a word containing a NUL byte
 * then searching the word for the specific byte.
 *
 * Word check obtained from Sean Eron Anderson's Bit Twiddling Hacks:
 * http://graphics.stanford.edu/~seander/bithacks.html
 */
size_t
xstrlen(const char *str)
{
	const char *start;
	word_t v;

	/* Search through the first characters until the pointer is aligned. */
	start = str;
	while (str != (const char *)ALIGN(str))
		if (*str == '\0')
			return (str - start);
		else
			str++;

	/* Search for a word containing a NUL byte then search for the byte. */
	for (;; str += sizeof (v)) {
		v = *(word_t *)str;
		if ((v - LowBitMask) & ~(v) & HighBitMask) {
			for (;; str++)
				if (*str == '\0')
					break;
			break;
		}
	}

	return (str - start);
}
