[Git][NTPsec/ntpsec][unit-rewrite] Added fitinfield() and tests.

Ian Bruene gitlab at mg.gitlab.com
Sun Apr 9 23:58:30 UTC 2017


Ian Bruene pushed to branch unit-rewrite at NTPsec / ntpsec


Commits:
21b271fc by Ian Bruene at 2017-04-09T18:56:54-05:00
Added fitinfield() and tests.

fitinfield() attempts to fit a value in a given field size, padding if there
is extra room, cropping if there is not enough room. fitinfield() will never
crop above the decimal point.

- - - - -


2 changed files:

- pylib/util.py
- tests/pylib/test_util.py


Changes:

=====================================
pylib/util.py
=====================================
--- a/pylib/util.py
+++ b/pylib/util.py
@@ -275,6 +275,23 @@ def scalestring(value):
     return (newvalue, unitsmoved)
 
 
+def fitinfield(value, fieldsize):
+    "Attempt to fit value into a field, preserving as much data as possible"
+    vallen = len(value)
+    if vallen == fieldsize:  # Goldilocks!
+        newvalue = value
+    elif vallen < fieldsize:  # Extra room, pad it out
+        pad = " " * (fieldsize - vallen)
+        newvalue = pad + value
+    else:  # Insufficient room, crop as few digits as possible
+        above, below, neg = breaknumberstring(value)
+        diff = vallen - fieldsize
+        bellen = len(below)
+        croplen = min(bellen, diff)  # Never crop above the decimal point
+        newvalue = value[:-croplen]
+    return newvalue
+
+
 def unitformatter(f, unitgroup, startingunit, baseunit=None,
                   strip=False, width=8):
     "Formatting for unit associated values in N characters."


=====================================
tests/pylib/test_util.py
=====================================
--- a/tests/pylib/test_util.py
+++ b/tests/pylib/test_util.py
@@ -243,6 +243,20 @@ class TestPylibUtilMethods(unittest.TestCase):
         # ditto, negative
         self.assertEqual(f("123", "456", True), "-123.456")
 
+    def test_fitinfield(self):
+        f = ntp.util.fitinfield
+
+        # Field too small, crop decimals
+        self.assertEqual(f("123.456", 5), "123.4")
+        # ditto, negative
+        self.assertEqual(f("-123.456", 5), "-123.")
+        # Field too small, blow field
+        self.assertEqual(f("12345.678", 4), "12345.")
+        # Goldilocks
+        self.assertEqual(f("123.456", 7), "123.456")
+        # Field too big
+        self.assertEqual(f("123.456", 10), "   123.456")
+
 
 if __name__ == '__main__':
     unittest.main()



View it on GitLab: https://gitlab.com/NTPsec/ntpsec/commit/21b271fce4310fcc81c213279976e2fbe13f2bf9
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.ntpsec.org/pipermail/vc/attachments/20170409/c77944d6/attachment.html>


More information about the vc mailing list