Refactored buffer manipulation logic in separate utils.