changeset 13894:4fa77c58ad8f

added utility methods for writing a Java string to a native memory buffer as a C string
author Doug Simon <doug.simon@oracle.com>
date Thu, 06 Feb 2014 18:42:45 +0100
parents 1398243a0efa
children 4731c1a0b1f3
files graal/com.oracle.graal.graph/src/com/oracle/graal/graph/UnsafeAccess.java
diffstat 1 files changed, 29 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/graal/com.oracle.graal.graph/src/com/oracle/graal/graph/UnsafeAccess.java	Thu Feb 06 18:41:16 2014 +0100
+++ b/graal/com.oracle.graal.graph/src/com/oracle/graal/graph/UnsafeAccess.java	Thu Feb 06 18:42:45 2014 +0100
@@ -49,4 +49,33 @@
             throw new RuntimeException("exception while trying to get Unsafe.theUnsafe via reflection:", e);
         }
     }
+
+    /**
+     * Copies the contents of a {@link String} to a native memory buffer as a {@code '\0'}
+     * terminated C string. The native memory buffer is allocated via
+     * {@link Unsafe#allocateMemory(long)}. The caller is responsible for releasing the buffer when
+     * it is no longer needed via {@link Unsafe#freeMemory(long)}.
+     * 
+     * @return the native memory pointer of the C string created from {@code s}
+     */
+    public static long createCString(String s) {
+        return writeCString(s, unsafe.allocateMemory(s.length() + 1));
+    }
+
+    /**
+     * Writes the contents of a {@link String} to a native memory buffer as a {@code '\0'}
+     * terminated C string. The caller is responsible for ensuring the buffer is at least
+     * {@code s.length() + 1} bytes long. The caller is also responsible for releasing the buffer
+     * when it is no longer.
+     * 
+     * @return the value of {@code buf}
+     */
+    public static long writeCString(String s, long buf) {
+        int size = s.length();
+        for (int i = 0; i < size; i++) {
+            unsafe.putByte(buf + i, (byte) s.charAt(i));
+        }
+        unsafe.putByte(buf + size, (byte) '\0');
+        return buf;
+    }
 }