1. /**
    
  2.  * Copyright (c) Meta Platforms, Inc. and affiliates.
    
  3.  *
    
  4.  * This source code is licensed under the MIT license found in the
    
  5.  * LICENSE file in the root directory of this source tree.
    
  6.  *
    
  7.  * @flow
    
  8.  */
    
  9. 
    
  10. // TODO: This is pretty well supported by browsers. Maybe we can drop it.
    
  11. 
    
  12. export const clz32: (x: number) => number = Math.clz32
    
  13.   ? Math.clz32
    
  14.   : clz32Fallback;
    
  15. 
    
  16. // Count leading zeros.
    
  17. // Based on:
    
  18. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32
    
  19. const log = Math.log;
    
  20. const LN2 = Math.LN2;
    
  21. function clz32Fallback(x: number): number {
    
  22.   const asUint = x >>> 0;
    
  23.   if (asUint === 0) {
    
  24.     return 32;
    
  25.   }
    
  26.   return (31 - ((log(asUint) / LN2) | 0)) | 0;
    
  27. }