summary refs log tree commit diff stats
path: root/lib/system/jssys.nim
blob: 3bf506e1e861f764fd5372484966c45a4d3088a4 (plain) (blame)
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
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
#
#
#            Nim's Runtime Library
#        (c) Copyright 2015 Andreas Rumpf
#
#    See the file "copying.txt", included in this
#    distribution, for details about the copyright.
#

include system/indexerrors
import std/private/miscdollars

proc log*(s: cstring) {.importc: "console.log", varargs, nodecl.}

type
  PSafePoint = ptr SafePoint
  SafePoint {.compilerproc, final.} = object
    prev: PSafePoint # points to next safe point
    exc: ref Exception

  PCallFrame = ptr CallFrame
  CallFrame {.importc, nodecl, final.} = object
    prev: PCallFrame
    procname: cstring
    line: int # current line number
    filename: cstring

  PJSError = ref object
    columnNumber {.importc.}: int
    fileName {.importc.}: cstring
    lineNumber {.importc.}: int
    message {.importc.}: cstring
    stack {.importc.}: cstring

  JSRef = ref RootObj # Fake type.

var
  framePtr {.importc, nodecl, volatile.}: PCallFrame
  excHandler {.importc, nodecl, volatile.}: int = 0
  lastJSError {.importc, nodecl, volatile.}: PJSError = nil

{.push stacktrace: off, profiler:off.}
proc nimBoolToStr(x: bool): string {.compilerproc.} =
  if x: result = "true"
  else: result = "false"

proc nimCharToStr(x: char): string {.compilerproc.} =
  result = newString(1)
  result[0] = x

proc isNimException(): bool {.asmNoStackFrame.} =
  asm "return `lastJSError` && `lastJSError`.m_type;"

proc getCurrentException*(): ref Exception {.compilerRtl, benign.} =
  if isNimException(): result = cast[ref Exception](lastJSError)

proc getCurrentExceptionMsg*(): string =
  if lastJSError != nil:
    if isNimException():
      return cast[Exception](lastJSError).msg
    else:
      var msg: cstring
      {.emit: """
      if (`lastJSError`.message !== undefined) {
        `msg` = `lastJSError`.message;
      }
      """.}
      if not msg.isNil:
        return $msg
  return ""

proc setCurrentException*(exc: ref Exception) =
  lastJSError = cast[PJSError](exc)

proc auxWriteStackTrace(f: PCallFrame): string =
  type
    TempFrame = tuple[procname: cstring, line: int, filename: cstring]
  var
    it = f
    i = 0
    total = 0
    tempFrames: array[0..63, TempFrame]
  while it != nil and i <= high(tempFrames):
    tempFrames[i].procname = it.procname
    tempFrames[i].line = it.line
    tempFrames[i].filename = it.filename
    inc(i)
    inc(total)
    it = it.prev
  while it != nil:
    inc(total)
    it = it.prev
  result = ""
  # if the buffer overflowed print '...':
  if total != i:
    add(result, "(")
    add(result, $(total-i))
    add(result, " calls omitted) ...\n")
  for j in countdown(i-1, 0):
    result.toLocation($tempFrames[j].filename, tempFrames[j].line, 0)
    add(result, " at ")
    add(result, tempFrames[j].procname)
    add(result, "\n")

proc rawWriteStackTrace(): string =
  if framePtr != nil:
    result = "Traceback (most recent call last)\n" & auxWriteStackTrace(framePtr)
  else:
    result = "No stack traceback available\n"

proc writeStackTrace() =
  var trace = rawWriteStackTrace()
  trace.setLen(trace.len - 1)
  echo trace

proc getStackTrace*(): string = rawWriteStackTrace()
proc getStackTrace*(e: ref Exception): string = e.trace

proc unhandledException(e: ref Exception) {.
    compilerproc, asmNoStackFrame.} =
  var buf = ""
  if e.msg.len != 0:
    add(buf, "Error: unhandled exception: ")
    add(buf, e.msg)
  else:
    add(buf, "Error: unhandled exception")
  add(buf, " [")
  add(buf, e.name)
  add(buf, "]\n")
  when NimStackTrace:
    add(buf, rawWriteStackTrace())
  let cbuf = cstring(buf)
  when NimStackTrace:
    framePtr = nil
  {.emit: """
  if (typeof(Error) !== "undefined") {
    throw new Error(`cbuf`);
  }
  else {
    throw `cbuf`;
  }
  """.}

proc raiseException(e: ref Exception, ename: cstring) {.
    compilerproc, asmNoStackFrame.} =
  e.name = ename
  if excHandler == 0:
    unhandledException(e)
  when NimStackTrace:
    e.trace = rawWriteStackTrace()
  asm "throw `e`;"

proc reraiseException() {.compilerproc, asmNoStackFrame.} =
  if lastJSError == nil:
    raise newException(ReraiseDefect, "no exception to reraise")
  else:
    if excHandler == 0:
      if isNimException():
        unhandledException(cast[ref Exception](lastJSError))

    asm "throw lastJSError;"

proc raiseOverflow {.exportc: "raiseOverflow", noreturn, compilerproc.} =
  raise newException(OverflowDefect, "over- or underflow")

proc raiseDivByZero {.exportc: "raiseDivByZero", noreturn, compilerproc.} =
  raise newException(DivByZeroDefect, "division by zero")

proc raiseRangeError() {.compilerproc, noreturn.} =
  raise newException(RangeDefect, "value out of range")

proc raiseIndexError(i, a, b: int) {.compilerproc, noreturn.} =
  raise newException(IndexDefect, formatErrorIndexBound(int(i), int(a), int(b)))

proc raiseFieldError2(f: string, discVal: string) {.compilerproc, noreturn.} =
  raise newException(FieldDefect, formatFieldDefect(f, discVal))

proc setConstr() {.varargs, asmNoStackFrame, compilerproc.} =
  asm """
    var result = {};
    for (var i = 0; i < arguments.length; ++i) {
      var x = arguments[i];
      if (typeof(x) == "object") {
        for (var j = x[0]; j <= x[1]; ++j) {
          result[j] = true;
        }
      } else {
        result[x] = true;
      }
    }
    return result;
  """

proc makeNimstrLit(c: cstring): string {.asmNoStackFrame, compilerproc.} =
  {.emit: """
  var result = [];
  for (var i = 0; i < `c`.length; ++i) {
    result[i] = `c`.charCodeAt(i);
  }
  return result;
  """.}

proc cstrToNimstr(c: cstring): string {.asmNoStackFrame, compilerproc.} =
  {.emit: """
  var ln = `c`.length;
  var result = new Array(ln);
  var r = 0;
  for (var i = 0; i < ln; ++i) {
    var ch = `c`.charCodeAt(i);

    if (ch < 128) {
      result[r] = ch;
    }
    else {
      if (ch < 2048) {
        result[r] = (ch >> 6) | 192;
      }
      else {
        if (ch < 55296 || ch >= 57344) {
          result[r] = (ch >> 12) | 224;
        }
        else {
            ++i;
            ch = 65536 + (((ch & 1023) << 10) | (`c`.charCodeAt(i) & 1023));
            result[r] = (ch >> 18) | 240;
            ++r;
            result[r] = ((ch >> 12) & 63) | 128;
        }
        ++r;
        result[r] = ((ch >> 6) & 63) | 128;
      }
      ++r;
      result[r] = (ch & 63) | 128;
    }
    ++r;
  }
  return result;
  """.}

proc toJSStr(s: string): cstring {.compilerproc.} =
  proc fromCharCode(c: char): cstring {.importc: "String.fromCharCode".}
  proc join(x: openArray[cstring]; d = cstring""): cstring {.
    importcpp: "#.join(@)".}
  proc decodeURIComponent(x: cstring): cstring {.
    importc: "decodeURIComponent".}

  proc toHexString(c: char; d = 16): cstring {.importcpp: "#.toString(@)".}

  proc log(x: cstring) {.importc: "console.log".}

  var res = newSeq[cstring](s.len)
  var i = 0
  var j = 0
  while i < s.len:
    var c = s[i]
    if c < '\128':
      res[j] = fromCharCode(c)
      inc i
    else:
      var helper = newSeq[cstring]()
      while true:
        let code = toHexString(c)
        if code.len == 1:
          helper.add cstring"%0"
        else:
          helper.add cstring"%"
        helper.add code
        inc i
        if i >= s.len or s[i] < '\128': break
        c = s[i]
      try:
        res[j] = decodeURIComponent join(helper)
      except:
        res[j] = join(helper)
    inc j
  setLen(res, j)
  result = join(res)

proc mnewString(len: int): string {.asmNoStackFrame, compilerproc.} =
  asm """
    return new Array(`len`);
  """

proc SetCard(a: int): int {.compilerproc, asmNoStackFrame.} =
  # argument type is a fake
  asm """
    var result = 0;
    for (var elem in `a`) { ++result; }
    return result;
  """

proc SetEq(a, b: int): bool {.compilerproc, asmNoStackFrame.} =
  asm """
    for (var elem in `a`) { if (!`b`[elem]) return false; }
    for (var elem in `b`) { if (!`a`[elem]) return false; }
    return true;
  """

proc SetLe(a, b: int): bool {.compilerproc, asmNoStackFrame.} =
  asm """
    for (var elem in `a`) { if (!`b`[elem]) return false; }
    return true;
  """

proc SetLt(a, b: int): bool {.compilerproc.} =
  result = SetLe(a, b) and not SetEq(a, b)

proc SetMul(a, b: int): int {.compilerproc, asmNoStackFrame.} =
  asm """
    var result = {};
    for (var elem in `a`) {
      if (`b`[elem]) { result[elem] = true; }
    }
    return result;
  """

proc SetPlus(a, b: int): int {.compilerproc, asmNoStackFrame.} =
  asm """
    var result = {};
    for (var elem in `a`) { result[elem] = true; }
    for (var elem in `b`) { result[elem] = true; }
    return result;
  """

proc SetMinus(a, b: int): int {.compilerproc, asmNoStackFrame.} =
  asm """
    var result = {};
    for (var elem in `a`) {
      if (!`b`[elem]) { result[elem] = true; }
    }
    return result;
  """

proc cmpStrings(a, b: string): int {.asmNoStackFrame, compilerproc.} =
  asm """
    if (`a` == `b`) return 0;
    if (!`a`) return -1;
    if (!`b`) return 1;
    for (var i = 0; i < `a`.length && i < `b`.length; i++) {
      var result = `a`[i] - `b`[i];
      if (result != 0) return result;
    }
    return `a`.length - `b`.length;
  """

proc cmp(x, y: string): int =
  when nimvm:
    if x == y: result = 0
    elif x < y: result = -1
    else: result = 1
  else:
    result = cmpStrings(x, y)

proc eqStrings(a, b: string): bool {.asmNoStackFrame, compilerproc.} =
  asm """
    if (`a` == `b`) return true;
    if (`a` === null && `b`.length == 0) return true;
    if (`b` === null && `a`.length == 0) return true;
    if ((!`a`) || (!`b`)) return false;
    var alen = `a`.length;
    if (alen != `b`.length) return false;
    for (var i = 0; i < alen; ++i)
      if (`a`[i] != `b`[i]) return false;
    return true;
  """

when defined(kwin):
  proc rawEcho {.compilerproc, asmNoStackFrame.} =
    asm """
      var buf = "";
      for (var i = 0; i < arguments.length; ++i) {
        buf += `toJSStr`(arguments[i]);
      }
      print(buf);
    """

elif not defined(nimOldEcho):
  proc ewriteln(x: cstring) = log(x)

  proc rawEcho {.compilerproc, asmNoStackFrame.} =
    asm """
      var buf = "";
      for (var i = 0; i < arguments.length; ++i) {
        buf += `toJSStr`(arguments[i]);
      }
      console.log(buf);
    """

else:
  proc ewriteln(x: cstring) =
    var node : JSRef
    {.emit: "`node` = document.getElementsByTagName('body')[0];".}
    if node.isNil:
      raise newException(ValueError, "<body> element does not exist yet!")
    {.emit: """
    `node`.appendChild(document.createTextNode(`x`));
    `node`.appendChild(document.createElement("br"));
    """.}

  proc rawEcho {.compilerproc.} =
    var node : JSRef
    {.emit: "`node` = document.getElementsByTagName('body')[0];".}
    if node.isNil:
      raise newException(IOError, "<body> element does not exist yet!")
    {.emit: """
    for (var i = 0; i < arguments.length; ++i) {
      var x = `toJSStr`(arguments[i]);
      `node`.appendChild(document.createTextNode(x));
    }
    `node`.appendChild(document.createElement("br"));
    """.}

# Arithmetic:
proc checkOverflowInt(a: int) {.asmNoStackFrame, compilerproc.} =
  asm """
    if (`a` > 2147483647 || `a` < -2147483648) `raiseOverflow`();
  """

proc addInt(a, b: int): int {.asmNoStackFrame, compilerproc.} =
  asm """
    var result = `a` + `b`;
    `checkOverflowInt`(result);
    return result;
  """

proc subInt(a, b: int): int {.asmNoStackFrame, compilerproc.} =
  asm """
    var result = `a` - `b`;
    `checkOverflowInt`(result);
    return result;
  """

proc mulInt(a, b: int): int {.asmNoStackFrame, compilerproc.} =
  asm """
    var result = `a` * `b`;
    `checkOverflowInt`(result);
    return result;
  """

proc divInt(a, b: int): int {.asmNoStackFrame, compilerproc.} =
  asm """
    if (`b` == 0) `raiseDivByZero`();
    if (`b` == -1 && `a` == 2147483647) `raiseOverflow`();
    return Math.trunc(`a` / `b`);
  """

proc modInt(a, b: int): int {.asmNoStackFrame, compilerproc.} =
  asm """
    if (`b` == 0) `raiseDivByZero`();
    if (`b` == -1 && `a` == 2147483647) `raiseOverflow`();
    return Math.trunc(`a` % `b`);
  """

proc checkOverflowInt64(a: int64) {.asmNoStackFrame, compilerproc.} =
  asm """
    if (`a` > 9223372036854775807n || `a` < -9223372036854775808n) `raiseOverflow`();
  """

proc addInt64(a, b: int64): int64 {.asmNoStackFrame, compilerproc.} =
  asm """
    var result = `a` + `b`;
    `checkOverflowInt64`(result);
    return result;
  """

proc subInt64(a, b: int64): int64 {.asmNoStackFrame, compilerproc.} =
  asm """
    var result = `a` - `b`;
    `checkOverflowInt64`(result);
    return result;
  """

proc mulInt64(a, b: int64): int64 {.asmNoStackFrame, compilerproc.} =
  asm """
    var result = `a` * `b`;
    `checkOverflowInt64`(result);
    return result;
  """

proc divInt64(a, b: int64): int64 {.asmNoStackFrame, compilerproc.} =
  asm """
    if (`b` == 0n) `raiseDivByZero`();
    if (`b` == -1n && `a` == 9223372036854775807n) `raiseOverflow`();
    return `a` / `b`;
  """

proc modInt64(a, b: int64): int64 {.asmNoStackFrame, compilerproc.} =
  asm """
    if (`b` == 0n) `raiseDivByZero`();
    if (`b` == -1n && `a` == 9223372036854775807n) `raiseOverflow`();
    return `a` % `b`;
  """

proc negInt(a: int): int {.compilerproc.} =
  result = a*(-1)

proc negInt64(a: int64): int64 {.compilerproc.} =
  result = a*(-1)

proc absInt(a: int): int {.compilerproc.} =
  result = if a < 0: a*(-1) else: a

proc absInt64(a: int64): int64 {.compilerproc.} =
  result = if a < 0: a*(-1) else: a

proc nimMin(a, b: int): int {.compilerproc.} = return if a <= b: a else: b
proc nimMax(a, b: int): int {.compilerproc.} = return if a >= b: a else: b

proc chckNilDisp(p: pointer) {.compilerproc.} =
  if p == nil:
    sysFatal(NilAccessDefect, "cannot dispatch; dispatcher is nil")

include "system/hti"

proc isFatPointer(ti: PNimType): bool =
  # This has to be consistent with the code generator!
  return ti.base.kind notin {tyObject,
    tyArray, tyArrayConstr, tyTuple,
    tyOpenArray, tySet, tyVar, tyRef, tyPtr}

proc nimCopy(dest, src: JSRef, ti: PNimType): JSRef {.compilerproc.}

proc nimCopyAux(dest, src: JSRef, n: ptr TNimNode) {.compilerproc.} =
  case n.kind
  of nkNone: sysAssert(false, "nimCopyAux")
  of nkSlot:
    asm """
      `dest`[`n`.offset] = nimCopy(`dest`[`n`.offset], `src`[`n`.offset], `n`.typ);
    """
  of nkList:
    asm """
    for (var i = 0; i < `n`.sons.length; i++) {
      nimCopyAux(`dest`, `src`, `n`.sons[i]);
    }
    """
  of nkCase:
    asm """
      `dest`[`n`.offset] = nimCopy(`dest`[`n`.offset], `src`[`n`.offset], `n`.typ);
      for (var i = 0; i < `n`.sons.length; ++i) {
        nimCopyAux(`dest`, `src`, `n`.sons[i][1]);
      }
    """

proc nimCopy(dest, src: JSRef, ti: PNimType): JSRef =
  case ti.kind
  of tyPtr, tyRef, tyVar, tyNil:
    if not isFatPointer(ti):
      result = src
    else:
      asm "`result` = [`src`[0], `src`[1]];"
  of tySet:
    asm """
      if (`dest` === null || `dest` === undefined) {
        `dest` = {};
      }
      else {
        for (var key in `dest`) { delete `dest`[key]; }
      }
      for (var key in `src`) { `dest`[key] = `src`[key]; }
      `result` = `dest`;
    """
  of tyTuple, tyObject:
    if ti.base != nil: result = nimCopy(dest, src, ti.base)
    elif ti.kind == tyObject:
      asm "`result` = (`dest` === null || `dest` === undefined) ? {m_type: `ti`} : `dest`;"
    else:
      asm "`result` = (`dest` === null || `dest` === undefined) ? {} : `dest`;"
    nimCopyAux(result, src, ti.node)
  of tyArrayConstr, tyArray:
    # In order to prevent a type change (TypedArray -> Array) and to have better copying performance,
    # arrays constructors are considered separately
    asm """
      if(ArrayBuffer.isView(`src`)) { 
        if(`dest` === null || `dest` === undefined || `dest`.length != `src`.length) {
          `dest` = new `src`.constructor(`src`);
        } else {
          `dest`.set(`src`, 0);
        }
        `result` = `dest`;
      } else {
        if (`src` === null) {
          `result` = null;
        }
        else {
          if (`dest` === null || `dest` === undefined || `dest`.length != `src`.length) {
            `dest` = new Array(`src`.length);
          }
          `result` = `dest`;
          for (var i = 0; i < `src`.length; ++i) {
            `result`[i] = nimCopy(`result`[i], `src`[i], `ti`.base);
          }
        }
      }
    """
  of tySequence, tyOpenArray:
    asm """
      if (`src` === null) {
        `result` = null;
      }
      else {
        if (`dest` === null || `dest` === undefined || `dest`.length != `src`.length) {
          `dest` = new Array(`src`.length);
        }
        `result` = `dest`;
        for (var i = 0; i < `src`.length; ++i) {
          `result`[i] = nimCopy(`result`[i], `src`[i], `ti`.base);
        }
      }
    """
  of tyString:
    asm """
      if (`src` !== null) {
        `result` = `src`.slice(0);
      }
    """
  else:
    result = src

proc genericReset(x: JSRef, ti: PNimType): JSRef {.compilerproc.} =
  asm "`result` = null;"
  case ti.kind
  of tyPtr, tyRef, tyVar, tyNil:
    if isFatPointer(ti):
      asm """
        `result` = [null, 0];
      """
  of tySet:
    asm """
      `result` = {};
    """
  of tyTuple, tyObject:
    if ti.kind == tyObject:
      asm "`result` = {m_type: `ti`};"
    else:
      asm "`result` = {};"
  of tySequence, tyOpenArray, tyString:
    asm """
      `result` = [];
    """
  of tyArrayConstr, tyArray:
    asm """
      `result` = new Array(`x`.length);
      for (var i = 0; i < `x`.length; ++i) {
        `result`[i] = genericReset(`x`[i], `ti`.base);
      }
    """
  else:
    discard

proc arrayConstr(len: int, value: JSRef, typ: PNimType): JSRef {.
                asmNoStackFrame, compilerproc.} =
  # types are fake
  asm """
    var result = new Array(`len`);
    for (var i = 0; i < `len`; ++i) result[i] = nimCopy(null, `value`, `typ`);
    return result;
  """

proc chckIndx(i, a, b: int): int {.compilerproc.} =
  if i >= a and i <= b: return i
  else: raiseIndexError(i, a, b)

proc chckRange(i, a, b: int): int {.compilerproc.} =
  if i >= a and i <= b: return i
  else: raiseRangeError()

proc chckObj(obj, subclass: PNimType) {.compilerproc.} =
  # checks if obj is of type subclass:
  var x = obj
  if x == subclass: return # optimized fast path
  while x != subclass:
    if x == nil:
      raise newException(ObjectConversionDefect, "invalid object conversion")
    x = x.base

proc isObj(obj, subclass: PNimType): bool {.compilerproc.} =
  # checks if obj is of type subclass:
  var x = obj
  if x == subclass: return true # optimized fast path
  while x != subclass:
    if x == nil: return false
    x = x.base
  return true

proc addChar(x: string, c: char) {.compilerproc, asmNoStackFrame.} =
  asm "`x`.push(`c`);"

{.pop.}

proc tenToThePowerOf(b: int): BiggestFloat =
  # xxx deadcode
  var b = b
  var a = 10.0
  result = 1.0
  while true:
    if (b and 1) == 1:
      result = result * a
    b = b shr 1
    if b == 0: break
    a = a * a

const
  IdentChars = {'a'..'z', 'A'..'Z', '0'..'9', '_'}


proc parseFloatNative(a: openarray[char]): float =
  var str = ""
  for x in a:
    str.add x

  let cstr = cstring str

  asm """
  `result` = Number(`cstr`);
  """

proc nimParseBiggestFloat(s: openarray[char], number: var BiggestFloat): int {.compilerproc.} =
  var sign: bool
  var i = 0
  if s[i] == '+': inc(i)
  elif s[i] == '-':
    sign = true
    inc(i)
  if s[i] == 'N' or s[i] == 'n':
    if s[i+1] == 'A' or s[i+1] == 'a':
      if s[i+2] == 'N' or s[i+2] == 'n':
        if s[i+3] notin IdentChars:
          number = NaN
          return i+3
    return 0
  if s[i] == 'I' or s[i] == 'i':
    if s[i+1] == 'N' or s[i+1] == 'n':
      if s[i+2] == 'F' or s[i+2] == 'f':
        if s[i+3] notin IdentChars:
          number = if sign: -Inf else: Inf
          return i+3
    return 0

  var buf: string
    # we could also use an `array[char, N]` buffer to avoid reallocs, or
    # use a 2-pass algorithm that first computes the length.
  if sign: buf.add '-'
  template addInc =
    buf.add s[i]
    inc(i)
  template eatUnderscores =
    while s[i] == '_': inc(i)
  while s[i] in {'0'..'9'}: # Read integer part
    buf.add s[i]
    inc(i)
    eatUnderscores()
  if s[i] == '.': # Decimal?
    addInc()
    while s[i] in {'0'..'9'}: # Read fractional part
      addInc()
      eatUnderscores()
  # Again, read integer and fractional part
  if buf.len == ord(sign): return 0
  if s[i] in {'e', 'E'}: # Exponent?
    addInc()
    if s[i] == '+': inc(i)
    elif s[i] == '-': addInc()
    if s[i] notin {'0'..'9'}: return 0
    while s[i] in {'0'..'9'}:
      addInc()
      eatUnderscores()
  number = parseFloatNative(buf)
  result = i

# Workaround for IE, IE up to version 11 lacks 'Math.trunc'. We produce
# 'Math.trunc' for Nim's ``div`` and ``mod`` operators:
when defined(nimJsMathTruncPolyfill):
  {.emit: """
if (!Math.trunc) {
  Math.trunc = function(v) {
    v = +v;
    if (!isFinite(v)) return v;
    return (v - v % 1) || (v < 0 ? -0 : v === 0 ? v : 0);
  };
}
""".}
n>importc.} proc SSLv23_method*(): PSSL_METHOD{.cdecl, dynlib: DLLSSLName, importc.} proc SSLv2_method*(): PSSL_METHOD{.cdecl, dynlib: DLLSSLName, importc.} proc SSLv3_method*(): PSSL_METHOD{.cdecl, dynlib: DLLSSLName, importc.} proc TLSv1_method*(): PSSL_METHOD{.cdecl, dynlib: DLLSSLName, importc.} proc SSL_new*(context: SslCtx): SslPtr{.cdecl, dynlib: DLLSSLName, importc.} proc SSL_free*(ssl: SslPtr){.cdecl, dynlib: DLLSSLName, importc.} proc SSL_CTX_new*(meth: PSSL_METHOD): SslCtx{.cdecl, dynlib: DLLSSLName, importc.} proc SSL_CTX_load_verify_locations*(ctx: SslCtx, CAfile: cstring, CApath: cstring): cInt{.cdecl, dynlib: DLLSSLName, importc.} proc SSL_CTX_free*(arg0: SslCtx){.cdecl, dynlib: DLLSSLName, importc.} proc SSL_CTX_set_verify*(s: SslCtx, mode: int, cb: proc (a: int, b: pointer): int {.cdecl.}){.cdecl, dynlib: DLLSSLName, importc.} proc SSL_get_verify_result*(ssl: SslPtr): int{.cdecl, dynlib: DLLSSLName, importc.} proc SSL_CTX_set_cipher_list*(s: SslCtx, ciphers: cstring): cint{.cdecl, dynlib: DLLSSLName, importc.} proc SSL_CTX_use_certificate_file*(ctx: SslCtx, filename: cstring, typ: cInt): cInt{. stdcall, dynlib: DLLSSLName, importc.} proc SSL_CTX_use_certificate_chain_file*(ctx: SslCtx, filename: cstring): cInt{. stdcall, dynlib: DLLSSLName, importc.} proc SSL_CTX_use_PrivateKey_file*(ctx: SslCtx, filename: cstring, typ: cInt): cInt{.cdecl, dynlib: DLLSSLName, importc.} proc SSL_CTX_check_private_key*(ctx: SslCtx): cInt{.cdecl, dynlib: DLLSSLName, importc.} proc SSL_set_fd*(ssl: SslPtr, fd: SocketHandle): cint{.cdecl, dynlib: DLLSSLName, importc.} proc SSL_shutdown*(ssl: SslPtr): cInt{.cdecl, dynlib: DLLSSLName, importc.} proc SSL_set_shutdown*(ssl: SslPtr, mode: cint) {.cdecl, dynlib: DLLSSLName, importc: "SSL_set_shutdown".} proc SSL_get_shutdown*(ssl: SslPtr): cint {.cdecl, dynlib: DLLSSLName, importc: "SSL_get_shutdown".} proc SSL_connect*(ssl: SslPtr): cint{.cdecl, dynlib: DLLSSLName, importc.} proc SSL_read*(ssl: SslPtr, buf: pointer, num: int): cint{.cdecl, dynlib: DLLSSLName, importc.} proc SSL_write*(ssl: SslPtr, buf: cstring, num: int): cint{.cdecl, dynlib: DLLSSLName, importc.} proc SSL_get_error*(s: SslPtr, ret_code: cInt): cInt{.cdecl, dynlib: DLLSSLName, importc.} proc SSL_accept*(ssl: SslPtr): cInt{.cdecl, dynlib: DLLSSLName, importc.} proc SSL_pending*(ssl: SslPtr): cInt{.cdecl, dynlib: DLLSSLName, importc.} proc BIO_new_ssl_connect*(ctx: SslCtx): BIO{.cdecl, dynlib: DLLSSLName, importc.} proc BIO_ctrl*(bio: BIO, cmd: cint, larg: int, arg: cstring): int{.cdecl, dynlib: DLLSSLName, importc.} proc BIO_get_ssl*(bio: BIO, ssl: ptr SslPtr): int = return BIO_ctrl(bio, BIO_C_GET_SSL, 0, cast[cstring](ssl)) proc BIO_set_conn_hostname*(bio: BIO, name: cstring): int = return BIO_ctrl(bio, BIO_C_SET_CONNECT, 0, name) proc BIO_do_handshake*(bio: BIO): int = return BIO_ctrl(bio, BIO_C_DO_STATE_MACHINE, 0, nil) proc BIO_do_connect*(bio: BIO): int = return BIO_do_handshake(bio) when not defined(nimfix): proc BIO_read*(b: BIO, data: cstring, length: cInt): cInt{.cdecl, dynlib: DLLUtilName, importc.} proc BIO_write*(b: BIO, data: cstring, length: cInt): cInt{.cdecl, dynlib: DLLUtilName, importc.} proc BIO_free*(b: BIO): cInt{.cdecl, dynlib: DLLUtilName, importc.} proc ERR_print_errors_fp*(fp: File){.cdecl, dynlib: DLLSSLName, importc.} proc ERR_error_string*(e: cInt, buf: cstring): cstring{.cdecl, dynlib: DLLUtilName, importc.} proc ERR_get_error*(): cInt{.cdecl, dynlib: DLLUtilName, importc.} proc ERR_peek_last_error*(): cInt{.cdecl, dynlib: DLLUtilName, importc.} proc OpenSSL_add_all_algorithms*(){.cdecl, dynlib: DLLUtilName, importc: "OPENSSL_add_all_algorithms_conf".} proc OPENSSL_config*(configName: cstring){.cdecl, dynlib: DLLSSLName, importc.} when not useWinVersion: proc CRYPTO_set_mem_functions(a,b,c: pointer){.cdecl, dynlib: DLLUtilName, importc.} proc allocWrapper(size: int): pointer {.cdecl.} = alloc(size) proc reallocWrapper(p: pointer; newsize: int): pointer {.cdecl.} = if p == nil: if newSize > 0: result = alloc(newsize) elif newsize == 0: dealloc(p) else: result = realloc(p, newsize) proc deallocWrapper(p: pointer) {.cdecl.} = if p != nil: dealloc(p) proc CRYPTO_malloc_init*() = when not useWinVersion and not defined(macosx): CRYPTO_set_mem_functions(allocWrapper, reallocWrapper, deallocWrapper) proc SSL_CTX_ctrl*(ctx: SslCtx, cmd: cInt, larg: int, parg: pointer): int{. cdecl, dynlib: DLLSSLName, importc.} proc SSL_CTX_callback_ctrl(ctx: SslCtx, typ: cInt, fp: PFunction): int{. cdecl, dynlib: DLLSSLName, importc.} proc SSLCTXSetMode*(ctx: SslCtx, mode: int): int = result = SSL_CTX_ctrl(ctx, SSL_CTRL_MODE, mode, nil) proc SSL_ctrl*(ssl: SslPtr, cmd: cInt, larg: int, parg: pointer): int{. cdecl, dynlib: DLLSSLName, importc.} proc SSL_set_tlsext_host_name*(ssl: SslPtr, name: cstring): int = result = SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name, name) ## Set the SNI server name extension to be used in a client hello. ## Returns 1 if SNI was set, 0 if current SSL configuration doesn't support SNI. proc SSL_get_servername*(ssl: SslPtr, typ: cInt = TLSEXT_NAMETYPE_host_name): cstring {.cdecl, dynlib: DLLSSLName, importc.} ## Retrieve the server name requested in the client hello. This can be used ## in the callback set in `SSL_CTX_set_tlsext_servername_callback` to ## implement virtual hosting. May return `nil`. proc SSL_CTX_set_tlsext_servername_callback*(ctx: SslCtx, cb: proc(ssl: SslPtr, cb_id: int, arg: pointer): int {.cdecl.}): int = ## Set the callback to be used on listening SSL connections when the client hello is received. ## ## The callback should return one of: ## * SSL_TLSEXT_ERR_OK ## * SSL_TLSEXT_ERR_ALERT_WARNING ## * SSL_TLSEXT_ERR_ALERT_FATAL ## * SSL_TLSEXT_ERR_NOACK result = SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, cast[PFunction](cb)) proc SSL_CTX_set_tlsext_servername_arg*(ctx: SslCtx, arg: pointer): int = ## Set the pointer to be used in the callback registered to ``SSL_CTX_set_tlsext_servername_callback``. result = SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, arg) proc bioNew*(b: PBIO_METHOD): BIO{.cdecl, dynlib: DLLUtilName, importc: "BIO_new".} proc bioFreeAll*(b: BIO){.cdecl, dynlib: DLLUtilName, importc: "BIO_free_all".} proc bioSMem*(): PBIO_METHOD{.cdecl, dynlib: DLLUtilName, importc: "BIO_s_mem".} proc bioCtrlPending*(b: BIO): cInt{.cdecl, dynlib: DLLUtilName, importc: "BIO_ctrl_pending".} proc bioRead*(b: BIO, Buf: cstring, length: cInt): cInt{.cdecl, dynlib: DLLUtilName, importc: "BIO_read".} proc bioWrite*(b: BIO, Buf: cstring, length: cInt): cInt{.cdecl, dynlib: DLLUtilName, importc: "BIO_write".} proc sslSetConnectState*(s: SslPtr) {.cdecl, dynlib: DLLSSLName, importc: "SSL_set_connect_state".} proc sslSetAcceptState*(s: SslPtr) {.cdecl, dynlib: DLLSSLName, importc: "SSL_set_accept_state".} proc sslRead*(ssl: SslPtr, buf: cstring, num: cInt): cInt{.cdecl, dynlib: DLLSSLName, importc: "SSL_read".} proc sslPeek*(ssl: SslPtr, buf: cstring, num: cInt): cInt{.cdecl, dynlib: DLLSSLName, importc: "SSL_peek".} proc sslWrite*(ssl: SslPtr, buf: cstring, num: cInt): cInt{.cdecl, dynlib: DLLSSLName, importc: "SSL_write".} proc sslSetBio*(ssl: SslPtr, rbio, wbio: BIO) {.cdecl, dynlib: DLLSSLName, importc: "SSL_set_bio".} proc sslDoHandshake*(ssl: SslPtr): cint {.cdecl, dynlib: DLLSSLName, importc: "SSL_do_handshake".} proc ErrClearError*(){.cdecl, dynlib: DLLUtilName, importc: "ERR_clear_error".} proc ErrFreeStrings*(){.cdecl, dynlib: DLLUtilName, importc: "ERR_free_strings".} proc ErrRemoveState*(pid: cInt){.cdecl, dynlib: DLLUtilName, importc: "ERR_remove_state".} when true: discard else: proc SslCtxSetCipherList*(arg0: PSSL_CTX, str: cstring): cInt{.cdecl, dynlib: DLLSSLName, importc.} proc SslCtxNew*(meth: PSSL_METHOD): PSSL_CTX{.cdecl, dynlib: DLLSSLName, importc.} proc SslSetFd*(s: PSSL, fd: cInt): cInt{.cdecl, dynlib: DLLSSLName, importc.} proc SslCTXCtrl*(ctx: PSSL_CTX, cmd: cInt, larg: int, parg: Pointer): int{. cdecl, dynlib: DLLSSLName, importc.} proc SSLSetMode*(s: PSSL, mode: int): int proc SSLCTXGetMode*(ctx: PSSL_CTX): int proc SSLGetMode*(s: PSSL): int proc SslMethodV2*(): PSSL_METHOD{.cdecl, dynlib: DLLSSLName, importc.} proc SslMethodV3*(): PSSL_METHOD{.cdecl, dynlib: DLLSSLName, importc.} proc SslMethodTLSV1*(): PSSL_METHOD{.cdecl, dynlib: DLLSSLName, importc.} proc SslMethodV23*(): PSSL_METHOD{.cdecl, dynlib: DLLSSLName, importc.} proc SslCtxUsePrivateKey*(ctx: PSSL_CTX, pkey: SslPtr): cInt{.cdecl, dynlib: DLLSSLName, importc.} proc SslCtxUsePrivateKeyASN1*(pk: cInt, ctx: PSSL_CTX, d: cstring, length: int): cInt{.cdecl, dynlib: DLLSSLName, importc.} proc SslCtxUseCertificate*(ctx: PSSL_CTX, x: SslPtr): cInt{.cdecl, dynlib: DLLSSLName, importc.} proc SslCtxUseCertificateASN1*(ctx: PSSL_CTX, length: int, d: cstring): cInt{. cdecl, dynlib: DLLSSLName, importc.} # function SslCtxUseCertificateChainFile(ctx: PSSL_CTX; const filename: PChar):cInt; proc SslCtxUseCertificateChainFile*(ctx: PSSL_CTX, filename: cstring): cInt{. cdecl, dynlib: DLLSSLName, importc.} proc SslCtxSetDefaultPasswdCb*(ctx: PSSL_CTX, cb: PPasswdCb){.cdecl, dynlib: DLLSSLName, importc.} proc SslCtxSetDefaultPasswdCbUserdata*(ctx: PSSL_CTX, u: SslPtr){.cdecl, dynlib: DLLSSLName, importc.} # function SslCtxLoadVerifyLocations(ctx: PSSL_CTX; const CAfile: PChar; const CApath: PChar):cInt; proc SslCtxLoadVerifyLocations*(ctx: PSSL_CTX, CAfile: cstring, CApath: cstring): cInt{. cdecl, dynlib: DLLSSLName, importc.} proc SslNew*(ctx: PSSL_CTX): PSSL{.cdecl, dynlib: DLLSSLName, importc.} proc SslConnect*(ssl: PSSL): cInt{.cdecl, dynlib: DLLSSLName, importc.} proc SslGetVersion*(ssl: PSSL): cstring{.cdecl, dynlib: DLLSSLName, importc.} proc SslGetPeerCertificate*(ssl: PSSL): PX509{.cdecl, dynlib: DLLSSLName, importc.} proc SslCtxSetVerify*(ctx: PSSL_CTX, mode: cInt, arg2: PFunction){.cdecl, dynlib: DLLSSLName, importc.} proc SSLGetCurrentCipher*(s: PSSL): SslPtr{.cdecl, dynlib: DLLSSLName, importc.} proc SSLCipherGetName*(c: SslPtr): cstring{.cdecl, dynlib: DLLSSLName, importc.} proc SSLCipherGetBits*(c: SslPtr, alg_bits: var cInt): cInt{.cdecl, dynlib: DLLSSLName, importc.} proc SSLGetVerifyResult*(ssl: PSSL): int{.cdecl, dynlib: DLLSSLName, importc.} # libeay.dll proc X509New*(): PX509{.cdecl, dynlib: DLLUtilName, importc.} proc X509Free*(x: PX509){.cdecl, dynlib: DLLUtilName, importc.} proc X509NameOneline*(a: PX509_NAME, buf: cstring, size: cInt): cstring{. cdecl, dynlib: DLLUtilName, importc.} proc X509GetSubjectName*(a: PX509): PX509_NAME{.cdecl, dynlib: DLLUtilName, importc.} proc X509GetIssuerName*(a: PX509): PX509_NAME{.cdecl, dynlib: DLLUtilName, importc.} proc X509NameHash*(x: PX509_NAME): int{.cdecl, dynlib: DLLUtilName, importc.} # function SslX509Digest(data: PX509; typ: PEVP_MD; md: PChar; len: PcInt):cInt; proc X509Digest*(data: PX509, typ: PEVP_MD, md: cstring, length: var cInt): cInt{. cdecl, dynlib: DLLUtilName, importc.} proc X509print*(b: PBIO, a: PX509): cInt{.cdecl, dynlib: DLLUtilName, importc.} proc X509SetVersion*(x: PX509, version: cInt): cInt{.cdecl, dynlib: DLLUtilName, importc.} proc X509SetPubkey*(x: PX509, pkey: EVP_PKEY): cInt{.cdecl, dynlib: DLLUtilName, importc.} proc X509SetIssuerName*(x: PX509, name: PX509_NAME): cInt{.cdecl, dynlib: DLLUtilName, importc.} proc X509NameAddEntryByTxt*(name: PX509_NAME, field: cstring, typ: cInt, bytes: cstring, length, loc, theSet: cInt): cInt{. cdecl, dynlib: DLLUtilName, importc.} proc X509Sign*(x: PX509, pkey: EVP_PKEY, md: PEVP_MD): cInt{.cdecl, dynlib: DLLUtilName, importc.} proc X509GmtimeAdj*(s: PASN1_UTCTIME, adj: cInt): PASN1_UTCTIME{.cdecl, dynlib: DLLUtilName, importc.} proc X509SetNotBefore*(x: PX509, tm: PASN1_UTCTIME): cInt{.cdecl, dynlib: DLLUtilName, importc.} proc X509SetNotAfter*(x: PX509, tm: PASN1_UTCTIME): cInt{.cdecl, dynlib: DLLUtilName, importc.} proc X509GetSerialNumber*(x: PX509): PASN1_cInt{.cdecl, dynlib: DLLUtilName, importc.} proc EvpPkeyNew*(): EVP_PKEY{.cdecl, dynlib: DLLUtilName, importc.} proc EvpPkeyFree*(pk: EVP_PKEY){.cdecl, dynlib: DLLUtilName, importc.} proc EvpPkeyAssign*(pkey: EVP_PKEY, typ: cInt, key: Prsa): cInt{.cdecl, dynlib: DLLUtilName, importc.} proc EvpGetDigestByName*(Name: cstring): PEVP_MD{.cdecl, dynlib: DLLUtilName, importc.} proc EVPcleanup*(){.cdecl, dynlib: DLLUtilName, importc.} # function ErrErrorString(e: cInt; buf: PChar): PChar; proc SSLeayversion*(t: cInt): cstring{.cdecl, dynlib: DLLUtilName, importc.} proc OPENSSLaddallalgorithms*(){.cdecl, dynlib: DLLUtilName, importc.} proc CRYPTOcleanupAllExData*(){.cdecl, dynlib: DLLUtilName, importc.} proc RandScreen*(){.cdecl, dynlib: DLLUtilName, importc.} proc d2iPKCS12bio*(b: PBIO, Pkcs12: SslPtr): SslPtr{.cdecl, dynlib: DLLUtilName, importc.} proc PKCS12parse*(p12: SslPtr, pass: cstring, pkey, cert, ca: var SslPtr): cint{. dynlib: DLLUtilName, importc, cdecl.} proc PKCS12free*(p12: SslPtr){.cdecl, dynlib: DLLUtilName, importc.} proc RsaGenerateKey*(bits, e: cInt, callback: PFunction, cb_arg: SslPtr): PRSA{. cdecl, dynlib: DLLUtilName, importc.} proc Asn1UtctimeNew*(): PASN1_UTCTIME{.cdecl, dynlib: DLLUtilName, importc.} proc Asn1UtctimeFree*(a: PASN1_UTCTIME){.cdecl, dynlib: DLLUtilName, importc.} proc Asn1cIntSet*(a: PASN1_cInt, v: cInt): cInt{.cdecl, dynlib: DLLUtilName, importc.} proc i2dX509bio*(b: PBIO, x: PX509): cInt{.cdecl, dynlib: DLLUtilName, importc.} proc i2dPrivateKeyBio*(b: PBIO, pkey: EVP_PKEY): cInt{.cdecl, dynlib: DLLUtilName, importc.} # 3DES functions proc DESsetoddparity*(Key: des_cblock){.cdecl, dynlib: DLLUtilName, importc.} proc DESsetkeychecked*(key: des_cblock, schedule: des_key_schedule): cInt{. cdecl, dynlib: DLLUtilName, importc.} proc DESecbencrypt*(Input: des_cblock, output: des_cblock, ks: des_key_schedule, enc: cInt){.cdecl, dynlib: DLLUtilName, importc.} # implementation proc SSLSetMode(s: PSSL, mode: int): int = result = SSLctrl(s, SSL_CTRL_MODE, mode, nil) proc SSLCTXGetMode(ctx: PSSL_CTX): int = result = SSLCTXctrl(ctx, SSL_CTRL_MODE, 0, nil) proc SSLGetMode(s: PSSL): int = result = SSLctrl(s, SSL_CTRL_MODE, 0, nil) # <openssl/md5.h> type MD5_LONG* = cuint const MD5_CBLOCK* = 64 MD5_LBLOCK* = int(MD5_CBLOCK div 4) MD5_DIGEST_LENGTH* = 16 type MD5_CTX* = object A,B,C,D,Nl,Nh: MD5_LONG data: array[MD5_LBLOCK, MD5_LONG] num: cuint {.pragma: ic, importc: "$1".} {.push callconv:cdecl, dynlib:DLLUtilName.} proc md5_Init*(c: var MD5_CTX): cint{.ic.} proc md5_Update*(c: var MD5_CTX; data: pointer; len: csize): cint{.ic.} proc md5_Final*(md: cstring; c: var MD5_CTX): cint{.ic.} proc md5*(d: ptr cuchar; n: csize; md: ptr cuchar): ptr cuchar{.ic.} proc md5_Transform*(c: var MD5_CTX; b: ptr cuchar){.ic.} {.pop.} from strutils import toHex,toLower proc hexStr (buf:cstring): string = # turn md5s output into a nice hex str result = newStringOfCap(32) for i in 0 .. <16: result.add toHex(buf[i].ord, 2).toLower proc md5_File* (file: string): string {.raises: [IOError,Exception].} = ## Generate MD5 hash for a file. Result is a 32 character # hex string with lowercase characters (like the output # of `md5sum` const sz = 512 let f = open(file,fmRead) var buf: array[sz,char] ctx: MD5_CTX discard md5_init(ctx) while(let bytes = f.readChars(buf, 0, sz); bytes > 0): discard md5_update(ctx, buf[0].addr, bytes) discard md5_final( buf[0].addr, ctx ) f.close result = hexStr(buf) proc md5_Str* (str:string): string {.raises:[IOError].} = ##Generate MD5 hash for a string. Result is a 32 character #hex string with lowercase characters var ctx: MD5_CTX res: array[MD5_DIGEST_LENGTH,char] input = str.cstring discard md5_init(ctx) var i = 0 while i < str.len: let L = min(str.len - i, 512) discard md5_update(ctx, input[i].addr, L) i += L discard md5_final(res,ctx) result = hexStr(res)