/****************************************************************************/
/*	Copyright (c) 2009, Bendor Research Pty. Ltd. All rights reserved.		*/
/*	This software is released under the GNU General Public License, version	*/
/*	3, with the exemptions that 1) the header files installed by this 	 	*/
/*	package can be included in closed-source code and 2) the libraries		*/
/*	built by this package can be statically linked into a closed-source 	*/
/*	binary. See the file LICENSE for the details.							*/
/*	This software is provided "AS IS", without any warranty or guarantee.	*/
/*	By using this software you acknowledge that neither Bendor Research nor	*/
/*	any of its personnel or affiliates can be held liable for any damages,	*/
/*	including, but not limited to, loss of business, loss of money, loss of */
/*	life, loss of reputation, arising out of this software being faulty or	*/
/*	not performing as advertised, even if Bendor Research was aware of such	*/
/*	faults in the software. You use this software at your own risk, any and */
/*	all liabilities that arise out of your using this software are strictly	*/
/*	yours.																	*/
/****************************************************************************/

#include <string.h>

/** @addtogroup string */
/** @{ */

/**
*	Copies at most len-1 bytes from a string to an other.
*
*	Works like strncpy() with the following differences:
*	- The result string is guaranteed to be NUL terminated
*	- The remaining buffer space after the terminating NUL will not be zeroed.
*	The zeroing of the remaining space is a performance hit, especially if
*	you have a reasonably sized buffer and short source strings. In addition,
*	strncpy() does not guarantee that the result is actually terminated.
*	This function avoids the performance penalty and guarantees the termination.
*	If you want to know if the copy truncated the string, then you just have to
*	see if the return value was greater than l-1.
*
*	@param	dst		Pointer to the destiantion area
*	@param	src		Pointer to the source string
*	@param	len		Maximum number of non-zero characters to copy
*	@return			Length of the source string, but no more than len.
*
*	@attention
*		This is not a standard C library function. This function was suggested
*		first by Todd C. Miller and Theo de Raadt and it is included in OpenBSD.
*/

size_t	strlcpy( char *dst, const char *src, size_t len )
{
size_t	n;

	if ( ! len ) return( 0 );

	// Get the length of the source string. The source may or may not
	// be terminated, so we use strnlen().

	n = strnlen( src, len );

	if ( n < len ) {

		// The source is shorter than the limit, just do a
		// normal stringcopy.

		strcpy( dst, src );
	}
	else {

		// The source is longer, we do a memcpy() (which is faster
		// than strncpy(), as we *know* that there's no NUL in the src).
		// Then we terminate the result.

		memcpy( dst, src, len - 1 );
		dst[ len - 1 ] = 0;
	}

	return( n );
}

/** @} */

