Code Snippet

lib/utils.fs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
namespace SpiseMisu

[<RequireQualifiedAccess>]
module Performance =
  
  open System.Diagnostics
  
  module FSharpCore = Microsoft.FSharp.Core.LanguagePrimitives
  
  type [<Measure>] ns
  
  type stopwatch = private | SW of Stopwatch
  
  [<RequireQualifiedAccess>]
  module Nanosecond =
    
    let fromDouble (x:double) =
      FSharpCore.FloatWithMeasure<ns> x
    
    let toDouble (x:double<ns>) =
      double x
  
  [<RequireQualifiedAccess>]
  module Stopwatch =
    
    let init () =
      Stopwatch ()
      |> SW 
    
    let restart (SW w) = w.Restart ()
    let stop    (SW w) = w.Stop    ()
    let elapsed (SW w) =
      w.Elapsed.TotalNanoseconds
      |> Nanosecond.fromDouble

[<RequireQualifiedAccess>]
module Date =
  
  open System
    
  let inline stamp
    ( )
    : DateOnly =
      DateTime.UtcNow
      |> DateOnly.FromDateTime
    
  let inline timestamp
    ( )
    : DateTime =
      DateTime.UtcNow
  
  [<RequireQualifiedAccess>]
  module Unix =
    
    let epoch
      : int64 =
        0L
    
    let inline timestamp
      ( )
      : int64 =
        DateTimeOffset.UtcNow.ToUnixTimeSeconds ()
    
    let inline fromDateTime
      ( dateTime : DateTime )
      : int64 =
        DateTimeOffset(dateTime = dateTime).ToUnixTimeSeconds ()
    
    let inline toDateTime
      ( seconds : int64 )
      : DateTime =
        ( DateTimeOffset.FromUnixTimeSeconds seconds
        ).UtcDateTime
    
    [<RequireQualifiedAccess>]
    module Milliseconds =
    
      let inline timestamp
        ( )
        : int64 =
          DateTimeOffset.UtcNow.ToUnixTimeMilliseconds ()
    
      let inline fromDateTime
        ( dateTime : DateTime  )
        : int64 =
          DateTimeOffset(dateTime = dateTime).ToUnixTimeMilliseconds ()
    
      let inline toDateTime
        ( milliseconds : int64 )
        : DateTime =
          ( DateTimeOffset.FromUnixTimeMilliseconds milliseconds
          ).UtcDateTime
    
    [<RequireQualifiedAccess>]
    module Microseconds =
    
      let inline timestamp
        ( )
        : int64 =
          let uts = toDateTime 0L
          ( DateTimeOffset.UtcNow - DateTimeOffset(dateTime = uts)
          ).Ticks / 10L
    
      let inline fromDateTime
        ( dateTime : DateTime  )
        : int64 =
          let uts = toDateTime 0L
          ( DateTimeOffset(dateTime = dateTime) - DateTimeOffset(dateTime = uts)
          ).Ticks / 10L
    
      let inline toDateTime
        ( microseconds : int64 )
        : DateTime =
          let uts = toDateTime 0L
          microseconds * 10L
          |> uts.AddTicks
    
    [<RequireQualifiedAccess>]
    module Nanoseconds =
    
      let inline timestamp
        ( )
        : int64 =
          let uts = toDateTime 0L
          ( DateTimeOffset.UtcNow - DateTimeOffset(dateTime = uts)
          ).Ticks * 100L
    
      let inline fromDateTime
        ( dateTime : DateTime  )
        : int64 =
          let uts = toDateTime 0L
          ( DateTimeOffset(dateTime = dateTime) - DateTimeOffset(dateTime = uts)
          ).Ticks * 100L
    
      let inline toDateTime
        ( nanoseconds : int64 )
        : DateTime =
          let uts = toDateTime 0L
          nanoseconds / 100L
          |> uts.AddTicks
  
  [<RequireQualifiedAccess>]
  module ISO8601 =
    
    open System.Globalization

    type ISO8601 = string
    
    let inline stamp
      ( )
      : string =
        DateOnly.FromDateTime(DateTime.UtcNow).ToString("o")
    
    let inline timestamp
      ( )
      : string =
        DateTime.UtcNow.ToString("o")
    
    let inline fromDate
      ( date : DateOnly)
      : string =
        date.ToString("o")
    
    let inline fromDateTime
      ( datetime : DateTime)
      : string =
        datetime.ToString("o")
    
    let inline toDate
      ( date : string)
      : DateOnly =
        DateOnly.ParseExact
          ( date
          , "yyyy-MM-dd"
          )
    
    let inline toDateTime
      ( datetime : string)
      : DateTime =
        DateTime.ParseExact
          ( datetime
          , "yyyy-MM-ddTHH:mm:ss.fffffffZ"
          , CultureInfo.InvariantCulture
          )

[<RequireQualifiedAccess>]
module Input =
  
  open System
  
  let inline wait (key : ConsoleKey) =
    let rec aux _ =
      match System.Console.ReadKey(true).Key with
        | k when k = key ->     ()
        | ______________ -> aux ()
    aux ()

[<RequireQualifiedAccess>]
module Async =
  
  open System
  
  [<RequireQualifiedAccess>]
  module Control =
    
    let exit a =
      async {
        return
          ConsoleKey.Enter
          |> Input.wait
          |> Some
      }

[<RequireQualifiedAccess>]
module Output =
  
  open System
  
  let inline stdout
    ( x : 'a )
    : unit =
      Console.WriteLine x
  
  let inline stderr
    ( x : 'a )
    : unit =
      Console.Error.WriteLine x
  
  let inline debug
    ( x : 'a )
    : unit =
      Diagnostics.Debug.WriteLine x
  
  let inline trace
    ( x : 'a )
    : unit =
      Diagnostics.Trace.WriteLine x

[<RequireQualifiedAccess>]
module Bits =
  
  open System
  open System.Numerics (* #INumberBase<'a> *)
  
  let inline show pad (n:#INumberBase<'a>) =
    Convert.ToString(int64 n, 2).PadLeft(pad,'0')

[<RequireQualifiedAccess>]
module Hex =
  
  open System
  open System.Numerics (* #INumberBase<'a> *)
  
  let inline show pad (n:#INumberBase<'a>) =
    (int64 n).ToString("X2").PadLeft(pad, '0')

[<RequireQualifiedAccess>]
module HTTP =
  
  open System
  open System.Collections.Generic
  open System.IO
  open System.Net
  open System.Net.Http
  open System.Net.Http.Headers
  open System.Text
  
  type headers = (string * string list) list
  
  type DebugHandler (baseHandler) =
    
    inherit DelegatingHandler (baseHandler)
    
    override __.SendAsync (req, cancelToken) =
      let reqBody =
        if null = req.Content
        then
          String.Empty
        else
          req.Content.ReadAsStringAsync()
          |> Async.AwaitTask
          |> Async.RunSynchronously
      let com = 
        baseHandler.SendAsync
          ( request = req
          , cancellationToken = cancelToken
          )
        |> Async.AwaitTask
      let res =
        com
        |> Async.RunSynchronously
      let resBody =
        res
        |> fun x ->
          if null = x.Content
          then 
            String.Empty
          else
            x.Content.ReadAsStringAsync()
            |> Async.AwaitTask
            |> Async.RunSynchronously
      sprintf
        "%s | VERBOSE | DEBUG Request  \n%A\n%s\n\n\
         %s | VERBOSE | DEBUG Response \n%A\n%s\n"
          (Date.ISO8601.timestamp ()) req reqBody
          (Date.ISO8601.timestamp ()) res resBody
      |> Output.stderr
      
      Async.StartAsTask
        ( computation = com
        , cancellationToken = cancelToken
        )
  
  let inline client
    ( debug : bool )
    ( hds : (string * string) list )
    : HttpClient =
      try
        let affinity = new HttpClientHandler()
        affinity.UseCookies <- false
        (* System.Net > DecompressionMethods > DecompressionMethods Enum:
           - https://docs.microsoft.com
                    /en-us/dotnet/api/system.net.decompressionmethods
        *)
        if affinity.SupportsAutomaticDecompression then
          affinity.AutomaticDecompression <- DecompressionMethods.All
        let http =
          if debug then
            new HttpClient
              ( handler        = new DebugHandler(affinity)
              , disposeHandler = true
              )
          else
            new HttpClient
              ( handler        = affinity
              , disposeHandler = true
              )
        let accept =
          new MediaTypeWithQualityHeaderValue
            ( "application/json"
            )
        accept.Parameters.Add (
          new NameValueHeaderValue
            ( "charset"
            , "utf-8"
            )
        )
        hds
        |> List.iter(
          fun (x,y) ->
            http.DefaultRequestHeaders.TryAddWithoutValidation(x,y) |> ignore
        )
        http
      with ex ->
        raise ex
      
  let inline private headers
    ( response : HttpResponseMessage )
    : headers =
      let hs =
        response.Headers
        |> Seq.map(
          fun kv ->
            ( kv.Key
            , kv.Value
              |> Seq.toList
            )
        )
      hs
      |> Seq.toList
  
  let inline private body
    ( response : HttpResponseMessage )
    : string Async =
      async {
        let! content =
          response.Content.ReadAsStringAsync()
          |> Async.AwaitTask
        return content
      }
  
  (* HttpClient Class > Remarks > The following methods are thread safe:
     - https://docs.microsoft.com
              /en-us/dotnet/api/system.net.http.httpclient#remarks
   *)
  let inline private send
    ( cli : HttpClient )
    ( url : string )
    ( met : string )
    ( hds : (string * string) list )
    ( con : HttpContent option )
    : (HttpStatusCode * headers * string) Async =
      async {
        let req =
          new HttpRequestMessage
            ( new HttpMethod(met)
            , url
            )
        hds
        |> List.iter(
          fun (x,y) ->
            req.Headers.TryAddWithoutValidation(x,y)
            |> ignore
        )
        match con with
          | None   -> ()
          | Some x -> req.Content <- x
        let! res =
          cli.SendAsync req
          |> Async.AwaitTask
        let! txt = body res
        return
          ( res.StatusCode
          , headers res
          , txt
          )
      }
  
  [<RequireQualifiedAccess>]
  module Form =
    
    let inline private helper
      ( cli : HttpClient )
      ( hds : (string * string) list )
      ( mds : (string * string) list )
      ( url : string )
      ( mtd : string )
      : (HttpStatusCode * headers * string) Async =
        let kvs =
          mds
          |> List.map(
            fun (x,y) ->
              new KeyValuePair<string,string>(x, y)
          )
        let fue = new FormUrlEncodedContent(kvs) :> HttpContent
        send cli url mtd hds (Some fue)
    
    let inline patch
      ( cli : HttpClient )
      ( hds : (string * string) list )
      ( mds : (string * string) list )
      ( url : string )
      : (HttpStatusCode * headers * string) Async =
        helper cli hds mds url "PATCH"
    
    let inline post
      ( cli : HttpClient )
      ( hds : (string * string) list )
      ( mds : (string * string) list )
      ( url : string )
      : (HttpStatusCode * headers * string) Async =
        helper cli hds mds url "POST"
    
    let inline put
      ( cli : HttpClient )
      ( hds : (string * string) list )
      ( mds : (string * string) list )
      ( url : string )
      : (HttpStatusCode * headers * string) Async =
        helper cli hds mds url "PUT"
  
  [<RequireQualifiedAccess>]
  module Stream =
    
    let inline private helper
      ( cli : HttpClient )
      ( hds : (string * string) list )
      ( mem : Stream )
      ( url : string )
      ( mtd : string )
      : (HttpStatusCode * headers * string) Async =
        let con =
          new StreamContent
            ( mem
            ) :> HttpContent
        send cli url mtd hds (Some con)
    
    let inline patch
      ( cli : HttpClient )
      ( hds : (string * string) list )
      ( mem : Stream )
      ( url : string )
      : (HttpStatusCode * headers * string) Async =
        helper cli hds mem url "PATCH"
    
    let inline post
      ( cli : HttpClient )
      ( hds : (string * string) list )
      ( mem : Stream )
      ( url : string )
      : (HttpStatusCode * headers * string) Async =
        helper cli hds mem url "POST"
    
    let inline put
      ( cli : HttpClient )
      ( hds : (string * string) list )
      ( mem : Stream )
      ( url : string )
      : (HttpStatusCode * headers * string) Async =
        helper cli hds mem url "PUT"
  
  [<RequireQualifiedAccess>]
  module JSON =
    
    let inline private helper
      ( cli : HttpClient )
      ( hds : (string * string) list )
      ( json : string )
      ( url : string )
      ( mtd : string )
      : (HttpStatusCode * headers * string) Async =
        let con =
          new StringContent
            ( json
            , Encoding.UTF8
            , "application/json"
            ) :> HttpContent
        send cli url mtd hds (Some con)
    
    let inline patch
      ( cli : HttpClient )
      ( hds : (string * string) list )
      ( json : string )
      ( url : string )
      : (HttpStatusCode * headers * string) Async =
        helper cli hds json url "PATCH"
    
    let inline post
      ( cli : HttpClient )
      ( hds : (string * string) list )
      ( json : string )
      ( url : string )
      : (HttpStatusCode * headers * string) Async =
        helper cli hds json url "POST"
    
    let inline put
      ( cli : HttpClient )
      ( hds : (string * string) list )
      ( json : string )
      ( url : string )
      : (HttpStatusCode * headers * string) Async =
        helper cli hds json url "PUT"
  
  let inline get
    ( cli : HttpClient )
    ( hds : (string * string) list )
    ( url : string )
    : (HttpStatusCode * headers * string) Async =
      send cli url "GET" hds None
  
  let inline delete
    ( cli : HttpClient )
    ( hds : (string * string) list )
    ( url : string )
    : (HttpStatusCode * headers * string) Async =
      send cli url "DELETE" hds None
  
  let inline head
    ( cli : HttpClient )
    ( hds : (string * string) list )
    ( url : string )
    : (HttpStatusCode * headers * string) Async =
      send cli url "HEAD" hds None
  
  let inline put
    ( cli : HttpClient )
    ( hds : (string * string) list )
    ( url : string )
    : (HttpStatusCode * headers * string) Async =
      send cli url "PUT" hds None

[<RequireQualifiedAccess>]
module JSON =
  
  open System.Text.Json
  open System.Text.Json.Serialization
  
  let options (converters : JsonConverter seq) indent =
    let os = JsonSerializerOptions ()
    os.Converters
      .Add
        ( JsonStringEnumConverter JsonNamingPolicy.CamelCase
        )
    for converter in converters do
      os.Converters
        .Add
          ( converter
          )
    os.DefaultIgnoreCondition <- JsonIgnoreCondition.WhenWritingDefault
    os.WriteIndented <- indent
    os
  
  let inline serialize
    ( converters : JsonConverter seq )
    ( indent : bool )
    ( value : 'a )
    : string =
      JsonSerializer.Serialize<'a>
        ( value   = value
        , options = options converters indent
        )
  
  let inline deserialize<'a>
    ( converters : JsonConverter seq )
    ( json : string )
    : 'a =
      try
        JsonSerializer.Deserialize<'a>
          ( json    = json
          , options = options converters false
          )
      with ex ->
        failwith ex.Message
      
  [<RequireQualifiedAccess>]
  module Value =
    
    let inline serialize
      ( indent : bool )
      ( value : JsonElement )
      : string =
        JsonSerializer.Serialize<JsonElement>
          ( value   = value
          , options = options Seq.empty indent
          )
    
    let inline deserialize
      ( json:string ) =
        ( try
            JsonSerializer.Deserialize<JsonDocument>
              ( json = json
              )
            |> Some
          with _ ->
            None
        )
        |> Option.map (fun jdoc -> jdoc.RootElement)

module Hash =
  
  [<RequireQualifiedAccess>]
  module SHA256 =
    
    open System.Security.Cryptography
    open System.Text
    
    (* Terminal vs .NET implementation
    
    [T480:~]$ echo -n 'foobar' | sha256sum
    c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2
    
    > Hash.SHA256.sum "foobar";;
    val it: string =
      "c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2"
    *)
  
    [<RequireQualifiedAccess>]
    module Bytes =
      
      let inline bytes
        ( bs : byte [] )
        : byte [] =
        use sha = SHA256.Create()
        bs
        |> sha.ComputeHash
      
      let inline sum
        ( bs : byte [] )
        : string =
        bytes bs
        |> Array.map    (sprintf "%02x")
        |> Array.reduce (sprintf "%s%s")
  
    [<RequireQualifiedAccess>]
    module String =
      
      let inline bytes
        ( str : string )
        : byte [] =
        use sha = SHA256.Create()
        str
        |> Encoding.UTF8.GetBytes
        |> sha.ComputeHash
      
      let inline sum
        ( str : string )
        : string =
        bytes str
        |> Array.map    (sprintf "%02x")
        |> Array.reduce (sprintf "%s%s")
  
    (* #time "on";; open Hash;; SHA256.String.sum "foobar";; *)

[<RequireQualifiedAccess>]
module UTF8 =
  
  open System.Text
  
  let noBOM = UTF8Encoding false

base32.fsx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
#!/usr/bin/env -S dotnet fsi --langversion:8.0 --optimize --warnaserror+:25,26

#nowarn "60"
(* Override implementations in augmentations are now deprecated. Override
   implementations should be given as part of the initial declaration of a type.
*)

#time "on"

#load "lib/utils.fs"

open System

module Date   = SpiseMisu.Date
module Output = SpiseMisu.Output

(*
  # Base32:
  - https://en.wikipedia.org/wiki/Base32     
  - https://www.rfc-editor.org/rfc/rfc4648#page-8
*)

[<RequireQualifiedAccess>]
module Base32 =
  
  open System.Collections.Generic
  open System.Text
  
  type Dict = private | Dict of Dictionary<char, byte>
  
  [<RequireQualifiedAccess>]
  module Dict =
    
    let init (cs : #seq<char>) =
      cs
      |> Seq.mapi (
        fun i c ->
          KeyValuePair<char, byte>(c, byte i)
      )
      |> Dictionary
      |> Dict
    
    let exists key (Dict dict) =
      dict.ContainsKey key
    
    let get key (Dict dict) =
      dict[key]
    
  let enc = 5
  let dec = 8
  
  let pad = 0b00111101uy (* byte '=' *)
  
  let alphabet =
    seq {
      [| 'A' .. 'Z' |]
      [| '2' .. '7' |]
    }
    |> Array.concat
  
  let alpha2idx =
    alphabet
    |> Dict.init
  
  let private indexHelper b00 b01 b02 b03 b04 =
    let t00 = b00
    let t01 = Option.defaultValue 0b00000000uy b01
    let t02 = Option.defaultValue 0b00000000uy b02
    let t03 = Option.defaultValue 0b00000000uy b03
    let t04 = Option.defaultValue 0b00000000uy b04
    
    let c00 =
      ((0b11111000uy &&& t00) >>> 3)
    let c01 =
      ((0b00000111uy &&& t00) <<< 2) |||
      ((0b11000000uy &&& t01) >>> 6)
    let c02 =
      ((0b00111110uy &&& t01) >>> 1)
    let c03 =
      ((0b00000001uy &&& t01) <<< 4) |||
      ((0b11110000uy &&& t02) >>> 4)
    let c04 =
      ((0b00001111uy &&& t02) <<< 1) |||
      ((0b10000000uy &&& t03) >>> 7)
    let c05 =
      ((0b01111100uy &&& t03) >>> 2)
    let c06 =
      ((0b00000011uy &&& t03) <<< 3) |||
      ((0b11100000uy &&& t04) >>> 5)
    let c07 =
      ((0b00011111uy &&& t04))
    
    seq {
      yield c00
      yield c01
      yield match b01 with | None -> pad | _ -> c02
      yield match b01 with | None -> pad | _ -> c03
      yield match b02 with | None -> pad | _ -> c04
      yield match b03 with | None -> pad | _ -> c05
      yield match b03 with | None -> pad | _ -> c06
      yield match b04 with | None -> pad | _ -> c07
    }
  
  let private encodeHelper (alpha:char []) (cs:string) =
    cs
    |> Seq.map byte
    |> Seq.chunkBySize enc
    |> Seq.map(
      fun xs ->
        seq {
          match Array.toList xs with
            | b0 :: b1 :: b2 :: b3 :: b4 :: [] ->
              yield! indexHelper b0 (Some b1) (Some b2) (Some b3) (Some b4)
            | b0 :: b1 :: b2 :: b3 ::       [] ->
              yield! indexHelper b0 (Some b1) (Some b2) (Some b3)  None
            | b0 :: b1 :: b2 ::             [] ->
              yield! indexHelper b0 (Some b1) (Some b2)  None      None
            | b0 :: b1 ::                   [] ->
              yield! indexHelper b0 (Some b1) None       None      None
            | b0 ::                         [] ->
              yield! indexHelper b0  None     None       None      None
            | ________________________________ ->
              ()
        }
    )
    |> Seq.concat
    |> Seq.map (
      fun b ->
        if pad <> b then
          string alpha[int b]
        else
          pad |> char |> string
    )
    |> Seq.fold (+) String.Empty
  
  let private charHelper b00 b01 b02 b03 b04 b05 b06 b07 =
    let t00 = b00
    let t01 = b01
    let t02 = Option.defaultValue 0b00000000uy b02
    let t03 = Option.defaultValue 0b00000000uy b03
    let t04 = Option.defaultValue 0b00000000uy b04
    let t05 = Option.defaultValue 0b00000000uy b05
    let t06 = Option.defaultValue 0b00000000uy b06
    let t07 = Option.defaultValue 0b00000000uy b07
    
    let c00 =
      ((0b00011111uy &&& t00) <<< 3) |||
      ((0b00011100uy &&& t01) >>> 2)
    let c01 =
      ((0b00000011uy &&& t01) <<< 6) |||
      ((0b00011111uy &&& t02) <<< 1) |||
      ((0b00010000uy &&& t03) >>> 4)
    let c02 =
      ((0b00001111uy &&& t03) <<< 4) |||
      ((0b00011110uy &&& t04) >>> 1)
    let c03 =
      ((0b00000001uy &&& t04) <<< 7) |||
      ((0b00011111uy &&& t05) <<< 2) |||
      ((0b00011000uy &&& t06) >>> 3)
    let c04 =
      ((0b00000111uy &&& t06) <<< 5) |||
      ((0b00011111uy &&& t07))
    
    seq {
      yield Some c00
      if None <> b02 && None <> b03 then
        yield Some c01
      if None <> b03 && None <> b04 then
        yield Some c02
      if None <> b04 && None <> b05 && None <> b06 then
        yield Some c03
      if None <> b06 && None <> b07 then
        yield Some c04
    }
  
  let private decodeHelper (dict:Dict) (cs:string) =
    cs
    |> Seq.map (
      fun c ->
        if pad = byte c || not (Dict.exists c dict) then
          None
        else
          Dict.get c dict
          |> Some
    )
    |> Seq.chunkBySize dec
    |> Seq.map(
      fun xs ->
        seq {
          match Array.toList xs with
            | Some b0 :: Some b1 :: b2 :: b3 :: b4 :: b5 :: b6 :: b7 :: [] ->
              yield! charHelper b0 b1 b2 b3 b4 b5 b6 b7
            | [] ->
              ()
            | _ ->
              yield None
        }
    )
    |> Seq.concat
    |> Seq.fold (
      fun (oa:StringBuilder option) ox ->
        match oa, ox with
          | None  ,      _
          |      _, None   -> None
          | Some a, Some x -> Some (a.Append(value = char x))
    ) (Some (StringBuilder()))
    |> Option.map (fun sb -> sb.ToString())
  
  let encode =
    encodeHelper alphabet
  
  let decode =
    decodeHelper alpha2idx
  
  [<RequireQualifiedAccess>]
  module Hex =
    
    let alphabet =
      seq {
        [| '0' .. '9' |]
        [| 'A' .. 'V' |]
      }
      |> Array.concat
  
    let alpha2idx =
      alphabet
      |> Dict.init
    
    let encode =
      encodeHelper alphabet
    
    let decode =
      decodeHelper alpha2idx

[<RequireQualifiedAccess>]
module Test =
  
  [<RequireQualifiedAccess>]
  module Vectors =
    
    (*
       # 10. Test Vectors
    *)
    
    let encode =
      [
        ( """Base32.encode "" """
        , Base32.encode ""
        , ""
        )
  
        ( """Base32.encode "f" """
        , Base32.encode "f"
        , "MY======"
        )
  
        ( """Base32.encode "fo" """
        , Base32.encode "fo"
        , "MZXQ===="
        )
  
        ( """Base32.encode "foo" """
        , Base32.encode "foo"
        , "MZXW6==="
        )
  
        ( """Base32.encode "foob" """
        , Base32.encode "foob"
        , "MZXW6YQ="
        )
  
        ( """Base32.encode "fooba" """
        , Base32.encode "fooba"
        , "MZXW6YTB"
        )
  
        ( """Base32.encode "foobar" """
        , Base32.encode "foobar"
        , "MZXW6YTBOI======"
        )
  
        ( """Base32.Hex.encode "" """
        , Base32.Hex.encode ""
        , ""
        )
  
        ( """Base32.Hex.encode "f" """
        , Base32.Hex.encode "f"
        , "CO======"
        )
  
        ( """Base32.Hex.encode "fo" """
        , Base32.Hex.encode "fo"
        , "CPNG===="
        )
  
        ( """Base32.Hex.encode "foo" """
        , Base32.Hex.encode "foo"
        , "CPNMU==="
        )
  
        ( """Base32.Hex.encode "foob" """
        , Base32.Hex.encode "foob"
        , "CPNMUOG="
        )
  
        ( """Base32.Hex.encode "fooba" """
        , Base32.Hex.encode "fooba"
        , "CPNMUOJ1"
        )
  
        ( """Base32.Hex.encode "foobar" """
        , Base32.Hex.encode "foobar"
        , "CPNMUOJ1E8======"
        )
      ]
    
    let decode =
      [
        ( """Base32.decode "" """
        , Base32.decode ""
        , Some ""
        )
  
        ( """Base32.decode "MY======" """
        , Base32.decode "MY======"
        , Some "f"
        )
  
        ( """Base32.decode "MZXQ====" """
        , Base32.decode "MZXQ===="
        , Some "fo"
        )
  
        ( """Base32.decode "MZXW6===" """
        , Base32.decode "MZXW6==="
        , Some "foo"
        )
  
        ( """Base32.decode "MZXW6YQ=" """
        , Base32.decode "MZXW6YQ="
        , Some "foob"
        )
  
        ( """Base32.decode "MZXW6YTB" """
        , Base32.decode "MZXW6YTB"
        , Some "fooba"
        )
  
        ( """Base32.decode "MZXW6YTBOI======" """
        , Base32.decode "MZXW6YTBOI======"
        , Some "foobar"
        )
  
        ( """Base32.Hex.decode "" """
        , Base32.Hex.decode ""
        , Some ""
        )
  
        ( """Base32.Hex.decode "CO======" """
        , Base32.Hex.decode "CO======"
        , Some "f"
        )
  
        ( """Base32.Hex.decode "CPNG====" """
        , Base32.Hex.decode "CPNG===="
        , Some "fo"
        )
  
        ( """Base32.Hex.decode "CPNMU===" """
        , Base32.Hex.decode "CPNMU==="
        , Some "foo"
        )
  
        ( """Base32.Hex.decode "CPNMUOG=" """
        , Base32.Hex.decode "CPNMUOG="
        , Some "foob"
        )
  
        ( """Base32.Hex.decode "CPNMUOJ1" """
        , Base32.Hex.decode "CPNMUOJ1"
        , Some "fooba"
        )
  
        ( """Base32.Hex.decode "CPNMUOJ1E8======" """
        , Base32.Hex.decode "CPNMUOJ1E8======"
        , Some "foobar"
        )
      ]
      
    let cases verbose =
      let es =
        encode
        |> Seq.map(
          fun (s, o, r) ->
            ( s
            , o
            , r
            , o = r
            )
        )
      
      if verbose then
        let ts = Date.ISO8601.timestamp ()
        sprintf "%s | Base32 | VERBOSE | # Test Vectors encode (verbose):" ts
        |> Output.stdout
        es
        |> Seq.iteri (
          fun i (s, o, r, t) ->
            sprintf "%s | Base32 | VERBOSE | %03i - %b: %s = %A" ts i t s r
            |> Output.stdout
        )
      
      let ds =
        decode
        |> Seq.map(
          fun (s, o, r) ->
            ( s
            , o
            , r
            , o = r
            )
        )
      
      if verbose then
        let ts = Date.ISO8601.timestamp ()
        sprintf "%s | Base32 | VERBOSE | # Test Vectors decode (verbose):" ts
        |> Output.stdout
        ds
        |> Seq.iteri (
          fun i (s, o, r, t) ->
            sprintf "%s | Base32 | VERBOSE | %03i - %b: %s = %A" ts i t s r
            |> Output.stdout
        )
      Seq.forall (fun (_, _, _, t) -> t) es &&
      Seq.forall (fun (_, _, _, t) -> t) ds

let _ =

  Date.ISO8601.timestamp ()
  |> sprintf "%s | Base32 | STARTED |"
  |> Output.stdout
  
  try
    
    let verbose = true
    
    let ts = Date.ISO8601.timestamp ()
    
    Test.Vectors.cases verbose
    |> sprintf "%s | Base32 | COMPUTE | Test.Vectors.cases: %b" ts
    |> Output.stdout
    
    Date.ISO8601.timestamp ()
    |> sprintf "%s | Base32 | STOPPED |"
    |> Output.stdout
    
    00
  with ex ->
    ( Date.ISO8601.timestamp ()
    , ex
    )
    ||> sprintf "%s | Base32 | FAILURE | Unexpected error:\n%A"
    |> Output.stdout
    -1

Code Output:

Real: 00:00:00.000, CPU: 00:00:00.000, GC gen0: 0, gen1: 0, gen2: 0
2025-05-26T07:07:07.7150397Z | … |
2025-05-26T07:07:07.7162282Z | … | # Test Vectors encode (verbose):
2025-05-26T07:07:07.7162282Z | … | 000 - true: Base32.encode ""  = ""
2025-05-26T07:07:07.7162282Z | … | 001 - true: Base32.encode "f"  = "MY======"
2025-05-26T07:07:07.7162282Z | … | 002 - true: Base32.encode "fo"  = "MZXQ===="
2025-05-26T07:07:07.7162282Z | … | 003 - true: Base32.encode "foo"  = "MZXW6==="
2025-05-26T07:07:07.7162282Z | … | 004 - true: Base32.encode "foob"  = "MZXW6YQ="
2025-05-26T07:07:07.7162282Z | … | 005 - true: Base32.encode "fooba"  = "MZXW6YTB"
2025-05-26T07:07:07.7162282Z | … | 006 - true: Base32.encode "foobar"  = "MZXW6YTBOI======"
2025-05-26T07:07:07.7162282Z | … | 007 - true: Base32.Hex.encode ""  = ""
2025-05-26T07:07:07.7162282Z | … | 008 - true: Base32.Hex.encode "f"  = "CO======"
2025-05-26T07:07:07.7162282Z | … | 009 - true: Base32.Hex.encode "fo"  = "CPNG===="
2025-05-26T07:07:07.7162282Z | … | 010 - true: Base32.Hex.encode "foo"  = "CPNMU==="
2025-05-26T07:07:07.7162282Z | … | 011 - true: Base32.Hex.encode "foob"  = "CPNMUOG="
2025-05-26T07:07:07.7162282Z | … | 012 - true: Base32.Hex.encode "fooba"  = "CPNMUOJ1"
2025-05-26T07:07:07.7162282Z | … | 013 - true: Base32.Hex.encode "foobar"  = "CPNMUOJ1E8======"
2025-05-26T07:07:07.7194703Z | … | # Test Vectors decode (verbose):
2025-05-26T07:07:07.7194703Z | … | 000 - true: Base32.decode ""  = Some ""
2025-05-26T07:07:07.7194703Z | … | 001 - true: Base32.decode "MY======"  = Some "f"
2025-05-26T07:07:07.7194703Z | … | 002 - true: Base32.decode "MZXQ===="  = Some "fo"
2025-05-26T07:07:07.7194703Z | … | 003 - true: Base32.decode "MZXW6==="  = Some "foo"
2025-05-26T07:07:07.7194703Z | … | 004 - true: Base32.decode "MZXW6YQ="  = Some "foob"
2025-05-26T07:07:07.7194703Z | … | 005 - true: Base32.decode "MZXW6YTB"  = Some "fooba"
2025-05-26T07:07:07.7194703Z | … | 006 - true: Base32.decode "MZXW6YTBOI======"  = Some "foobar"
2025-05-26T07:07:07.7194703Z | … | 007 - true: Base32.Hex.decode ""  = Some ""
2025-05-26T07:07:07.7194703Z | … | 008 - true: Base32.Hex.decode "CO======"  = Some "f"
2025-05-26T07:07:07.7194703Z | … | 009 - true: Base32.Hex.decode "CPNG===="  = Some "fo"
2025-05-26T07:07:07.7194703Z | … | 010 - true: Base32.Hex.decode "CPNMU==="  = Some "foo"
2025-05-26T07:07:07.7194703Z | … | 011 - true: Base32.Hex.decode "CPNMUOG="  = Some "foob"
2025-05-26T07:07:07.7194703Z | … | 012 - true: Base32.Hex.decode "CPNMUOJ1"  = Some "fooba"
2025-05-26T07:07:07.7194703Z | … | 013 - true: Base32.Hex.decode "CPNMUOJ1E8======"  = Some "foobar"
2025-05-26T07:07:07.7154636Z | … | Test.Vectors.cases: true
2025-05-26T07:07:07.7220438Z | … |
Real: 00:00:00.015, CPU: 00:00:00.010, GC gen0: 0, gen1: 0, gen2: 0

References: