aboutsummaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorRobert Hensing <roberth@users.noreply.github.com>2020-08-02 16:58:49 +0200
committerGitHub <noreply@github.com>2020-08-02 16:58:49 +0200
commit150bf4fa3b548fe907fbcd5583eb3beb9a9feedd (patch)
tree2537684c01278b50c1c0e99c3ed4b2fd9985a592 /lib
parent475c761d9320d611d6e0600995a840f423dc9ace (diff)
parent83b16885f526d6ab7b39e98159e2b48024f3238c (diff)
Merge pull request #75584 from Infinisil/settings-formats
Configuration file formats for JSON, INI, YAML and TOML
Diffstat (limited to 'lib')
-rw-r--r--lib/generators.nix6
-rw-r--r--lib/strings.nix16
2 files changed, 20 insertions, 2 deletions
diff --git a/lib/generators.nix b/lib/generators.nix
index efe6ea6031d3..abd237eb7d37 100644
--- a/lib/generators.nix
+++ b/lib/generators.nix
@@ -48,8 +48,10 @@ rec {
else if isAttrs v then err "attrsets" v
# functions can’t be printed of course
else if isFunction v then err "functions" v
- # let’s not talk about floats. There is no sensible `toString` for them.
- else if isFloat v then err "floats" v
+ # Floats currently can't be converted to precise strings,
+ # condition warning on nix version once this isn't a problem anymore
+ # See https://github.com/NixOS/nix/pull/3480
+ else if isFloat v then libStr.floatToString v
else err "this value is" (toString v);
diff --git a/lib/strings.nix b/lib/strings.nix
index 74e3eaa0722d..0baa942355c0 100644
--- a/lib/strings.nix
+++ b/lib/strings.nix
@@ -612,6 +612,22 @@ rec {
*/
fixedWidthNumber = width: n: fixedWidthString width "0" (toString n);
+ /* Convert a float to a string, but emit a warning when precision is lost
+ during the conversion
+
+ Example:
+ floatToString 0.000001
+ => "0.000001"
+ floatToString 0.0000001
+ => trace: warning: Imprecise conversion from float to string 0.000000
+ "0.000000"
+ */
+ floatToString = float: let
+ result = toString float;
+ precise = float == builtins.fromJSON result;
+ in if precise then result
+ else lib.warn "Imprecise conversion from float to string ${result}" result;
+
/* Check whether a value can be coerced to a string */
isCoercibleToString = x:
builtins.elem (builtins.typeOf x) [ "path" "string" "null" "int" "float" "bool" ] ||