From 725bb4e48c6491598f53b83c2dcd1a307115c6cc Mon Sep 17 00:00:00 2001 From: edef Date: Thu, 4 Apr 2024 14:05:18 +0000 Subject: lib: add xor This gets clumsily reimplemented in various places, to no useful end. --- lib/default.nix | 2 +- lib/tests/misc.nix | 16 ++++++++++++++++ lib/trivial.nix | 18 ++++++++++++++++++ 3 files changed, 35 insertions(+), 1 deletion(-) (limited to 'lib') diff --git a/lib/default.nix b/lib/default.nix index f6cb7932507a..b442ddf5fa0f 100644 --- a/lib/default.nix +++ b/lib/default.nix @@ -69,7 +69,7 @@ let hasAttr head isAttrs isBool isInt isList isPath isString length lessThan listToAttrs pathExists readFile replaceStrings seq stringLength sub substring tail trace; - inherit (self.trivial) id const pipe concat or and bitAnd bitOr bitXor + inherit (self.trivial) id const pipe concat or and xor bitAnd bitOr bitXor bitNot boolToString mergeAttrs flip mapNullable inNixShell isFloat min max importJSON importTOML warn warnIf warnIfNot throwIf throwIfNot checkListOfEnum info showWarnings nixpkgsVersion version isInOldestRelease diff --git a/lib/tests/misc.nix b/lib/tests/misc.nix index 3cb96c1b68bc..9d2da7a63913 100644 --- a/lib/tests/misc.nix +++ b/lib/tests/misc.nix @@ -102,6 +102,7 @@ let types updateManyAttrsByPath versions + xor ; testingThrow = expr: { @@ -210,6 +211,21 @@ runTests { expected = false; }; + testXor = { + expr = [ + (xor true false) + (xor true true) + (xor false false) + (xor false true) + ]; + expected = [ + true + false + false + true + ]; + }; + testFix = { expr = fix (x: {a = if x ? a then "a" else "b";}); expected = {a = "a";}; diff --git a/lib/trivial.nix b/lib/trivial.nix index 936ad207c03d..5b7a1ee30f7a 100644 --- a/lib/trivial.nix +++ b/lib/trivial.nix @@ -199,6 +199,24 @@ in { */ and = x: y: x && y; + /** + boolean “exclusive or” + + + # Inputs + + `x` + + : 1\. Function argument + + `y` + + : 2\. Function argument + */ + # We explicitly invert the arguments purely as a type assertion. + # This is invariant under XOR, so it does not affect the result. + xor = x: y: (!x) != (!y); + /** bitwise “not” */ -- cgit 1.4.1