Sorry I couldn't write the sample in C#, seems Python was too different
IMHO, the errors in rendering are because:
1. It seems whitespace is not the only thing that should be processed differently: symbols should too (0x00 - 0x2f, 0x3a - 0x3f, 0x5b - 0x5f, 0x7b - 0x7f)
2. The "<space>2" is a problem because you don't take into account that the locale is RTL. The spaces around reversed direction script section should be rendered as part of original script direction. Only the spaces within reversed script section should render as part of that section direction. Darn, this sounds complicated but it's not.
IMHO, the errors in rendering are because:
1. It seems whitespace is not the only thing that should be processed differently: symbols should too (0x00 - 0x2f, 0x3a - 0x3f, 0x5b - 0x5f, 0x7b - 0x7f)
2. The "<space>2" is a problem because you don't take into account that the locale is RTL. The spaces around reversed direction script section should be rendered as part of original script direction. Only the spaces within reversed script section should render as part of that section direction. Darn, this sounds complicated but it's not.