Skip to content

Instantly share code, notes, and snippets.

@Szer
Created March 6, 2020 16:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Szer/bf29a02214c26cb7c87b2a87327d650c to your computer and use it in GitHub Desktop.
Save Szer/bf29a02214c26cb7c87b2a87327d650c to your computer and use it in GitHub Desktop.
Combine Strings using ArrayPool
open System
open System.Buffers
open System.Text
let toOneArrayToRuleThemAll(strs: string[]) =
let ascii = System.Text.Encoding.ASCII
let totalBytes = Seq.sumBy String.length strs
let result = Array.zeroCreate totalBytes
let mutable i = 0
let pool: ArrayPool<byte> = ArrayPool.Shared
for str in strs do
let byteArray = pool.Rent str.Length
let span = byteArray.AsSpan()
let bytes = ascii.GetBytes(str.AsSpan(), span)
for j = 0 to bytes-1 do
result.[j+i] <- byteArray.[j]
pool.Return byteArray
i <- i + bytes
result
let testArr = [|"123";"345";"bcdasdkjh";"ABASD234"|]
let byteResult = toOneArrayToRuleThemAll testArr
// [|49uy; 50uy; 51uy; 51uy; 52uy; 53uy; 98uy; 99uy; 100uy; 97uy; 115uy; 100uy;
// 107uy; 106uy; 104uy; 65uy; 66uy; 65uy; 83uy; 68uy; 50uy; 51uy; 52uy|]
let testString = Encoding.ASCII.GetString byteResult
// "123345bcdasdkjhABASD234"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment