Factor out boundary checking.