Actually, even more simply, just truncate the buffer before the last leading byte you see if you walk backward from the end of the array. As shown below, leading bytes always start either with a 0 (for a 1-byte char) or 2 or more 1s, whereas continuation bytes start with 10. So just skip backwards over all bytes that start with 10, skip backwards over the next byte (which must be a leading byte), and then verify the rest.