From: whitequark Date: Sun, 22 Mar 2020 20:50:07 +0000 (+0000) Subject: hdl.ast: implement abs() on values. X-Git-Url: https://git.libre-soc.org/?a=commitdiff_plain;h=939d68e77df7271655ac930af41eeb1bf8925d11;p=nmigen.git hdl.ast: implement abs() on values. --- 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))