Add bounds checks to prevent slice out of range panics.