summary refs log tree commit diff stats
path: root/lib/pure/lenientops.nim
blob: c70e12e5ff2ae411f552f9d1c0eaff0a7230ee3e (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
#
#
#            Nim's Runtime Library
#        (c) Copyright 2017 Nim contributors
#
#    See the file "copying.txt", included in this
#    distribution, for details about the copyright.
#

## This module offers implementations of common binary operations
## like ``+``, ``-``, ``*``, ``/`` and comparison operations,
## which work for mixed float/int operands.
## All operations convert the integer operand into the
## type of the float operand. For numerical expressions, the return
## type is always the type of the float involved in the expresssion,
## i.e., there is no auto conversion from float32 to float64.
##
## Note: In general, auto-converting from int to float loses
## information, which is why these operators live in a separate
## module. Use with care.
##
## Regarding binary comparison, this module only provides unequal operators.
## The equality operator ``==`` is omitted, because depending on the use case
## either casting to float or rounding to int might be preferred, and users
## should make an explicit choice.

import typetraits

proc `+`*[I: SomeInteger, F: SomeFloat](i: I, f: F): F {.noSideEffect, inline.} =
  F(i) + f
proc `+`*[I: SomeInteger, F: SomeFloat](f: F, i: I): F {.noSideEffect, inline.} =
  f + F(i)

proc `-`*[I: SomeInteger, F: SomeFloat](i: I, f: F): F {.noSideEffect, inline.} =
  F(i) - f
proc `-`*[I: SomeInteger, F: SomeFloat](f: F, i: I): F {.noSideEffect, inline.} =
  f - F(i)

proc `*`*[I: SomeInteger, F: SomeFloat](i: I, f: F): F {.noSideEffect, inline.} =
  F(i) * f
proc `*`*[I: SomeInteger, F: SomeFloat](f: F, i: I): F {.noSideEffect, inline.} =
  f * F(i)

proc `/`*[I: SomeInteger, F: SomeFloat](i: I, f: F): F {.noSideEffect, inline.} =
  F(i) / f
proc `/`*[I: SomeInteger, F: SomeFloat](f: F, i: I): F {.noSideEffect, inline.} =
  f / F(i)

proc `<`*[I: SomeInteger, F: SomeFloat](i: I, f: F): bool {.noSideEffect, inline.} =
  F(i) < f
proc `<`*[I: SomeInteger, F: SomeFloat](f: F, i: I): bool {.noSideEffect, inline.} =
  f < F(i)
proc `<=`*[I: SomeInteger, F: SomeFloat](i: I, f: F): bool {.noSideEffect, inline.} =
  F(i) <= f
proc `<=`*[I: SomeInteger, F: SomeFloat](f: F, i: I): bool {.noSideEffect, inline.} =
  f <= F(i)

# Note that we must not defined `>=` and `>`, because system.nim already has a
# template with signature (x, y: untyped): untyped, which would lead to
# ambiguous calls.