Extract logic to constrain a line segment within bounds to a function.
Add unit tests for constrain function and fix the bug they revealed.