growthbook / growthbook-flutter

GrowthBook Flutter SDK
MIT License
6 stars 0 forks source link

Hashing gives different results in Flutter web & mobile #26

Open kobreu opened 1 week ago

kobreu commented 1 week ago

Hi,

The current implementation of the hashing algorithm has different results for web & mobile in some cases. This leads to cases where users see multiple versions of an experiment if they switch between web & mobile. E.g. for sample hashValue 00000000-0c8a-4a39-904b-7d284d628772

The cause is that the current implementation can lead to integers > 2 pow 53 which leads to precision issues on the web.

I found this implementation to work for web and mobile:

int fnv1a32(String data) {
    int hash = init32;
    for (int i = 0; i < data.length; i++) {
      int b = data.codeUnitAt(i) & 0xff; // Get the ASCII value of the character
      hash ^= b; // XOR the hash with the character's value
      hash = ((hash << 24) +
              (hash << 8) +
              (hash << 7) +
              (hash << 4) +
              (hash << 1) +
              hash) // same as (hash * 0x01000193). On web this is mod 2^32 automatically as web operates shift operators on 32 bits
          .toUnsigned(32); // ensure mod 2^32 for mobile
    }
    return hash;
  }
vazarkevych commented 1 week ago

Hi, @kobreu. We will check that and write to you.