| 
16 | 16 | 
 
  | 
17 | 17 | package com.mongodb.internal.connection;  | 
18 | 18 | 
 
  | 
 | 19 | +import org.bson.BsonSerializationException;  | 
19 | 20 | import org.bson.ByteBuf;  | 
20 | 21 | import org.bson.io.OutputBuffer;  | 
21 | 22 | 
 
  | 
 | 
27 | 28 | 
 
  | 
28 | 29 | import static com.mongodb.assertions.Assertions.assertTrue;  | 
29 | 30 | import static com.mongodb.assertions.Assertions.notNull;  | 
 | 31 | +import static java.lang.String.format;  | 
30 | 32 | 
 
  | 
31 | 33 | /**  | 
32 | 34 |  * <p>This class is not part of the public API and may be removed or changed at any time</p>  | 
@@ -273,6 +275,42 @@ public void close() {  | 
273 | 275 |         }  | 
274 | 276 |     }  | 
275 | 277 | 
 
  | 
 | 278 | +    @Override  | 
 | 279 | +    protected int writeCharacters(final String str, final boolean checkForNullCharacters) {  | 
 | 280 | +        ensureOpen();  | 
 | 281 | +        ByteBuf buf = getCurrentByteBuffer();  | 
 | 282 | +        byte[] array = buf.array();  | 
 | 283 | +        int i = 0;  | 
 | 284 | +        if (array != null && (buf.remaining() >= str.length() + 1)) {  | 
 | 285 | +            int pos = buf.position();  | 
 | 286 | +            int len = str.length();  | 
 | 287 | +            for (;i < len; i++) {  | 
 | 288 | +                char c = str.charAt(i);  | 
 | 289 | +                if (checkForNullCharacters && c == 0x0) {  | 
 | 290 | +                    throw new BsonSerializationException(format("BSON cstring '%s' is not valid because it contains a null character "  | 
 | 291 | +                            + "at index %d", str, i));  | 
 | 292 | +                }  | 
 | 293 | +                if (c > 0x80) {  | 
 | 294 | +                    break;  | 
 | 295 | +                }  | 
 | 296 | +                array[pos + i] = (byte) c;  | 
 | 297 | +            }  | 
 | 298 | +            if (i == len) {  | 
 | 299 | +                int total = len + 1;  | 
 | 300 | +                array[pos + len] = 0;  | 
 | 301 | +                position += total;  | 
 | 302 | +                buf.position(pos + total);  | 
 | 303 | +                return len + 1;  | 
 | 304 | +            }  | 
 | 305 | +            // ith character is not ASCII  | 
 | 306 | +            if (i > 0) {  | 
 | 307 | +                position += i;  | 
 | 308 | +                buf.position(pos + i);  | 
 | 309 | +            }  | 
 | 310 | +        }  | 
 | 311 | +        return i + super.writeCharacters(str, i, checkForNullCharacters);  | 
 | 312 | +    }  | 
 | 313 | + | 
276 | 314 |     private static final class BufferPositionPair {  | 
277 | 315 |         private final int bufferIndex;  | 
278 | 316 |         private int position;  | 
 | 
0 commit comments