From 4684e19828380f295ea1fd93da35ca67a2151aa1 Mon Sep 17 00:00:00 2001 From: Hawstein Date: Thu, 20 Jul 2017 23:34:33 +0800 Subject: [PATCH] add zero-copy constructor to create ByteString from external array --- .../src/main/scala/akka/util/ByteString.scala | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/akka-actor/src/main/scala/akka/util/ByteString.scala b/akka-actor/src/main/scala/akka/util/ByteString.scala index dfcfb549af..837fec437e 100644 --- a/akka-actor/src/main/scala/akka/util/ByteString.scala +++ b/akka-actor/src/main/scala/akka/util/ByteString.scala @@ -60,6 +60,16 @@ object ByteString { */ def fromArray(array: Array[Byte]): ByteString = apply(array) + /** + * Creates a ByteString without allocation. + * + * Use with caution: + * Since the ByteString is created without copying the byte array, + * this makes it unsafe if an array is passed in and mutated afterwards. + * DO NOT USE if you are not sure whether the passed-in array will be changed outside this method. + */ + def fromArrayUnsafe(array: Array[Byte]): ByteString = ByteString1C(array) + /** * Creates a new ByteString by copying length bytes starting at offset from * an Array. @@ -67,6 +77,16 @@ object ByteString { def fromArray(array: Array[Byte], offset: Int, length: Int): ByteString = CompactByteString.fromArray(array, offset, length) + /** + * Creates a ByteString without allocation, using length bytes starting at offset from an Array. + * + * Use with caution: + * Since the ByteString is created without copying the byte array, + * this makes it unsafe if an array is passed in and mutated afterwards. + * DO NOT USE if you are not sure whether the passed-in array will be changed outside this method. + */ + def fromArrayUnsafe(array: Array[Byte], offset: Int, length: Int): ByteString = ByteString1(array, offset, length) + /** * JAVA API * Creates a new ByteString by copying an int array by converting from integral numbers to bytes.