1. 7
  1.  

  2. 3

    Am I the only one who thinks the “correct” code is awful? I’d much rather just see an if statement added to the first padding code. Bit twiddling should be reserved for inner-inner-inner-loop optimisations. They’re all about “how” with none of the “why”

    1. 2

      Yeah, I looked at the “fixed” code and am like, “oh man, I have to get out a REPL an start seeing how this works”

      def pad(amount,size):
          q, r = divmod(amount,size)
          if r == 0:
              padded = q * size
          else:
              padded = (q + 1) * size
      
          assert padded % size == 0, padded
          return padded
      

      or this

      /*
         pad to next whole 2048 up
      */
      int obvious_pad(int size) {
          int q = size / 2048;
          int r = size % 2048;
          return (q + (r != 0 ? 1 : 0)) * 2048;
      }
      
      1. 1

        I came up with your second solution too :)
        return ((size / 2048) + (((size % 2048) != 0) ? 1 : 0)) * 2048;

      2. 1

        i’m guessing once you’ve done enough bit twiddling, that just reads as a mod operation to you

      3. 1

        Unit testing. I know, this was the 90’s, unit testing didn’t exist yet. I’m sure everyone would write a unit test for this nowadays. Right?