Skip to content

Commit b7cb26e

Browse files
committed
getNativeStringCapacity() should - 4, the native string terminator length
1 parent 9369382 commit b7cb26e

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

src/main/java/org/truffleruby/cext/CExtNodes.java

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -157,23 +157,25 @@ public abstract class CExtNodes {
157157
public static final int RUBY_TAG_THROW = 0x7;
158158
public static final int RUBY_TAG_FATAL = 0x8;
159159

160+
/** We need up to 4 \0 bytes for UTF-32. Always use 4 for speed rather than checking the encoding min length.
161+
* Corresponds to TERM_LEN() in MRI. */
162+
public static final int NATIVE_STRING_TERMINATOR_LENGTH = 4;
163+
160164
public static Pointer newNativeStringPointer(RubyLanguage language, RubyContext context, int capacity) {
161-
// We need up to 4 \0 bytes for UTF-32. Always use 4 for speed rather than checking the encoding min length.
162-
Pointer pointer = Pointer.mallocAutoRelease(language, context, capacity + 4);
165+
Pointer pointer = Pointer.mallocAutoRelease(language, context, capacity + NATIVE_STRING_TERMINATOR_LENGTH);
163166
pointer.writeInt(capacity, 0);
164167
return pointer;
165168
}
166169

167170
public static Pointer newZeroedNativeStringPointer(RubyLanguage language, RubyContext context, int capacity) {
168-
// We need up to 4 \0 bytes for UTF-32. Always use 4 for speed rather than checking the encoding min length.
169-
return Pointer.callocAutoRelease(language, context, capacity + 4);
171+
return Pointer.callocAutoRelease(language, context, capacity + NATIVE_STRING_TERMINATOR_LENGTH);
170172
}
171173

172174
private static long getNativeStringCapacity(Pointer pointer) {
173175
final long nativeBufferSize = pointer.getSize();
174176
assert nativeBufferSize > 0;
175-
// Do not count the extra byte for \0, like MRI.
176-
return nativeBufferSize - 1;
177+
// Do not count the extra terminator bytes, like MRI.
178+
return nativeBufferSize - NATIVE_STRING_TERMINATOR_LENGTH;
177179
}
178180

179181
@Primitive(name = "call_with_c_mutex_and_frame")

0 commit comments

Comments
 (0)