Created
February 19, 2022 22:17
-
-
Save ijrussell/d0a151419ccf2650f720edbb6263b1d3 to your computer and use it in GitHub Desktop.
This file contains hidden or 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.IO | |
open System.IO.Compression | |
open System.Text | |
type CompressionValue = { | |
Value: string | |
Size: int | |
} | |
type CompressionResult = { | |
Original: CompressionValue | |
Result: CompressionValue | |
Level: CompressionLevel | |
Kind: string | |
} | |
with | |
member this.Difference = | |
this.Original.Size - this.Result.Size | |
member this.Percent = | |
Math.Abs(decimal this.Difference / decimal this.Original.Size) | |
let ToGzipAsync (level:CompressionLevel) (value:string) = | |
task { | |
let bytes = Encoding.Unicode.GetBytes(value) | |
use input = new MemoryStream(bytes) | |
use output = new MemoryStream() | |
use stream = new GZipStream(output, level) | |
do! input.CopyToAsync(stream) | |
let result = output.ToArray() | |
return { | |
Original = { Value = value; Size = bytes.Length } | |
Result = { Value = Convert.ToBase64String(result); Size = result.Length } | |
Level = CompressionLevel.Fastest | |
Kind = "GZip" | |
} | |
} | |
let FromGzipAsync (value:string) = | |
task { | |
let bytes = Convert.FromBase64String(value) | |
use input = new MemoryStream(bytes) | |
use output = new MemoryStream() | |
use stream = new GZipStream(input, CompressionMode.Decompress) | |
do! stream.CopyToAsync(output) | |
do! stream.FlushAsync() | |
return Encoding.Unicode.GetString(output.ToArray()) | |
} | |
let compress fileName level = | |
task { | |
let! text = | |
Path.Combine(__SOURCE_DIRECTORY__, "resources", fileName) | |
|> File.ReadAllTextAsync | |
return! ToGzipAsync level text | |
} | |
let run () = | |
let output = | |
compress "comedy-of-errors.txt" CompressionLevel.Fastest | |
|> Async.AwaitTask | |
|> Async.RunSynchronously | |
printfn "Original size: %A" (output.Original.Size.ToString("N0")) | |
printfn "Compressed size: %A" (output.Result.Size.ToString("N0")) | |
printfn "Difference: %A" (output.Difference.ToString("N0")) | |
printfn "%% Reduction: %s" (output.Percent.ToString("P")) | |
run () |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment