I think there could be a problem here. What if length(HistoryValue) == $ValueLength? Then there will be no more space for the OldValue, but it will still be added. 

It could also be that the HistoryValue is very short (minimum ''), and the OldValue is very long, or the other way round. In that case some unneccessary cutting might happen. Please improve this and add test cases for both scenarios. Thanks!