Backport a bugfix for collapse adjacent encodings

Backport a bugfix from master