Created
March 6, 2020 16:20
-
-
Save Szer/bf29a02214c26cb7c87b2a87327d650c to your computer and use it in GitHub Desktop.
Combine Strings using ArrayPool
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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