/****************************************************************************/
/*	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 <chips/ARM/func.h>

	afunc	strnlen_fast
	mov		r2,r0					// We use R2 as the pointer
	add		r3,r0,#1				// Use R3 as the original pointer
	movs	r0,r1					// R0 is the ret.val. if we don't find NUL
	bxeq	lr						// If 0 length was specified, we're done.
	cmp		r1,#7					// For less than 7 bytes we don't bother
	ble		7f
0:
	tst		r2,#3					// Is the pointer word aligned?
	beq		1f						// If yes, start doing words
	ldrb	ip,[r2],#1				// Otherwise get a byte
	tst		ip,ip					// Check if it is 0
	beq		5f						// Finish if it is
	sub		r1,r1,#1				// Otherwise decrement the counter
	b		0b						// and try it again
1:
	subs	r1,r1,#4				// Do we have at least 4 bytes to go?
	bmi		6f						// No, revert to byte scan
	ldr		ip,[r2],#4				// Get the next word
	tst		ip,#0xff				// Test the bytes
	tstne	ip,#0xff00
	tstne	ip,#0xff0000
	tstne	ip,#0xff000000
	bne		1b
	tst		ip,#0xff
	addeq	r3,r3,#1
	tstne	ip,#0xff00
	addeq	r3,r3,#1
	tstne	ip,#0xff0000
	addeq	r3,r3,#1
5:
	sub		r0,r2,r3
	bx		lr
6:
	adds	r1,r1,#4
	bxeq	lr
7:
	ldrb	ip,[r2],#1
	tst		ip,ip
	beq		5b
	subs	r1,r1,#1
	bpl		7b
	bx		lr

