Move length check earlier to ensure we don't go beyond the end of the user's buffer...