Skip to content

Instantly share code, notes, and snippets.

@rahulmutt
Created March 1, 2018 02:34
Show Gist options
  • Save rahulmutt/0efcf0fddd02bc58f2854014aa68f11e to your computer and use it in GitHub Desktop.
Save rahulmutt/0efcf0fddd02bc58f2854014aa68f11e to your computer and use it in GitHub Desktop.
Convert CharSequence to StringBuffer
charSeqToStringBuffer :: CharSequence -> StringBuffer
charSeqToStringBuffer cs = unsafePerformJava $ do
bytes <- charSequenceBytes cs
len <- bytes <.> alength
buf <- mallocForeignPtrArray len
io $ withForeignPtr buf $ putBytesIntoPtr bytes
return $ StringBuffer { cur = 0, .. }
foreign import java unsafe "@static Utils.charSequenceBytes" charSequenceBytes
:: CharSequence -> Java a JByteArray
foreign import java unsafe "@static Utils.putBytesIntoPtr" putBytesIntoPtr
:: Ptr Word8 -> IO ()
import eta.runtime.io.MemoryManager;
import java.io.UnsupportedEncodingException;
public class Utils {
public static byte[] charSequenceBytes(CharSequence cs)
throws UnsupportedEncodingException {
return cs.toString().getBytes("UTF-8");
}
public static void putBytesIntoPtr(long address, byte[] bytes) {
MemoryManager.getBoundedBuffer(address).put(bytes);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment