From 2d1e12d00ca13ce6ad92fe145beeaa74925de6ef Mon Sep 17 00:00:00 2001 From: whitequark Date: Sun, 22 Mar 2020 20:50:07 +0000 Subject: [PATCH] hdl.ast: implement abs() on values. --- nmigen/hdl/ast.py | 7 +++++++ nmigen/test/test_sim.py | 7 +++++++ 2 files changed, 14 insertions(+) diff --git a/nmigen/hdl/ast.py b/nmigen/hdl/ast.py index af1d831..cadf960 100644 --- a/nmigen/hdl/ast.py +++ b/nmigen/hdl/ast.py @@ -220,6 +220,13 @@ class Value(metaclass=ABCMeta): def __ge__(self, other): return Operator(">=", [self, other]) + def __abs__(self): + width, signed = self.shape() + if signed: + return Mux(self >= 0, self, -self) + else: + return self + def __len__(self): return self.shape().width diff --git a/nmigen/test/test_sim.py b/nmigen/test/test_sim.py index 677f257..7996bec 100644 --- a/nmigen/test/test_sim.py +++ b/nmigen/test/test_sim.py @@ -180,6 +180,13 @@ class SimulatorUnitTestCase(FHDLTestCase): self.assertStatement(stmt, [C(2, 4), C(3, 4), C(0)], C(3, 4)) self.assertStatement(stmt, [C(2, 4), C(3, 4), C(1)], C(2, 4)) + def test_abs(self): + stmt = lambda y, a: y.eq(abs(a)) + self.assertStatement(stmt, [C(3, unsigned(8))], C(3, unsigned(8))) + self.assertStatement(stmt, [C(-3, unsigned(8))], C(-3, unsigned(8))) + self.assertStatement(stmt, [C(3, signed(8))], C(3, signed(8))) + self.assertStatement(stmt, [C(-3, signed(8))], C(3, signed(8))) + def test_slice(self): stmt1 = lambda y, a: y.eq(a[2]) self.assertStatement(stmt1, [C(0b10110100, 8)], C(0b1, 1)) -- 2.30.2