1 #!/usr/bin/env dub
2 /+ dub.sdl:
3     name "bench_fastjwt"
4     // dependency "fastjwt" version="~>1.1.1"
5     dependency "fastjwt" path=".dub/packages/fastjwt-1.1.1/fastjwt" # wrong Base64 decoder workaround
6 +/
7 
8 module bench.fastjwt;
9 import core.memory;
10 import std.conv;
11 import std.datetime.stopwatch;
12 import std.json;
13 import std.stdio;
14 import fastjwt.jwt;
15 import stringbuffer;
16 
17 int main(string[] args)
18 {
19     // args: enc/dec/val, cycle count, alg, token/payload, signature
20     // output:
21     //   payload/token/true
22     //   msecs taken
23     //   GC used bytes
24 
25     if (args.length != 6) { writeln("Invalid args"); return 1; }
26     size_t cycles = args[2].to!size_t;
27 
28     JWTAlgorithm alg;
29     try alg = args[3].to!JWTAlgorithm;
30     catch (Exception ex)
31     {
32         writeln("Unsupported algorithm");
33         return 1;
34     }
35 
36     {
37         StopWatch sw;
38         sw.start();
39         immutable prevAllocated = GC.allocatedInCurrentThread;
40         scope (exit)
41         {
42             sw.stop();
43             writeln(sw.peek.total!"msecs");
44             writeln(GC.allocatedInCurrentThread - prevAllocated);
45         }
46 
47         if (args[1] == "val") return validate(cycles, alg, args[4], args[5]);
48         else if (args[1] == "dec") return decode(cycles, alg, args[4], args[5]);
49         else if (args[1] == "enc") return encode(cycles, alg, args[4], args[5]);
50     }
51 
52     writeln("Invalid command: ", args[1]);
53     return 1;
54 }
55 
56 int validate(size_t cycles, JWTAlgorithm alg, string token, string secret)
57 {
58     StringBuffer head, pay;
59     bool ret;
60     foreach (_; 0..cycles)
61     {
62         head.removeAll();
63         pay.removeAll();
64         ret = 0 == decodeJWTToken(token, secret, alg, head, pay);
65     }
66     writeln(ret);
67     return 0;
68 }
69 
70 int decode(size_t cycles, JWTAlgorithm alg, string token, string secret)
71 {
72     StringBuffer head, pay;
73     foreach (_; 0..cycles)
74     {
75         head.removeAll();
76         pay.removeAll();
77         decodeJWTToken(token, secret, alg, head, pay);
78     }
79     writeln(pay.getData());
80     return 0;
81 }
82 
83 int encode(size_t cycles, JWTAlgorithm alg, string payload, string secret)
84 {
85     import vibe.data.json;
86     StringBuffer token;
87     auto jpay = parseJson(payload);
88     foreach (_; 0..cycles)
89     {
90         token.removeAll();
91         token.encodeJWTToken(alg, secret, jpay);
92     }
93     writeln(token.getData());
94     return 0;
95 }