Sfoglia il codice sorgente

fix(FortuneServiceImpl): fix hash operator precedence, use floorMod for negative-safe index

openhands 3 mesi fa
parent
commit
ffb482afc7

+ 9 - 7
cfc-backend/src/main/java/com/etotem/cfc/service/impl/FortuneServiceImpl.java

@@ -270,18 +270,20 @@ public class FortuneServiceImpl implements FortuneService {
         
         
         // 占位算法:五行三合
         // 占位算法:五行三合
         String[] elements = {"木", "火", "土", "金", "水"};
         String[] elements = {"木", "火", "土", "金", "水"};
-        int hash = (int)(familyId ^ (familyId >>> 32) + date.toEpochDay());
-        fortune.setDominantElement(elements[Math.abs(hash) % elements.length]);
+        // 注意:原写法因运算符优先级问题(+ 高于 >>> 且 ^ 低于两者)会导致移位越界,可能造成 ArrayIndexOutOfBoundsException
+        int hash = (int)(familyId.longValue() ^ (familyId.longValue() >>> 32) ^ date.toEpochDay());
+        int idx = Math.floorMod(Math.abs(hash), elements.length);
+        fortune.setDominantElement(elements[idx]);
         
         
         // 吉位
         // 吉位
         fortune.setLuckyDirection(calculateLuckyDirection(familyId, date));
         fortune.setLuckyDirection(calculateLuckyDirection(familyId, date));
         
         
         // 运势等级
         // 运势等级
         String[] fortuneLevels = {"大吉", "吉", "平", "凶", "大凶"};
         String[] fortuneLevels = {"大吉", "吉", "平", "凶", "大凶"};
-        fortune.setFortuneLevel(fortuneLevels[Math.abs(hash) % 5]);
+        fortune.setFortuneLevel(fortuneLevels[Math.floorMod(hash, fortuneLevels.length)]);
         
         
         // 心情分数
         // 心情分数
-        fortune.setMoodScore(50 + Math.abs(hash) % 50);
+        fortune.setMoodScore(50 + Math.floorMod(hash, 50));
         
         
         // 每日提示
         // 每日提示
         String[] tips = {
         String[] tips = {
@@ -291,12 +293,12 @@ public class FortuneServiceImpl implements FortuneService {
             "健康为本,注意休息",
             "健康为本,注意休息",
             "运势平稳,切勿冒险"
             "运势平稳,切勿冒险"
         };
         };
-        fortune.setFortuneDescription(tips[Math.abs(hash) % tips.length]);
+        fortune.setFortuneDescription(tips[Math.floorMod(hash, tips.length)]);
         
         
         // 心情描述
         // 心情描述
         String[] moods = {"心如止水", "喜悦满溢", "平静如常", "略感烦躁", "情绪低落"};
         String[] moods = {"心如止水", "喜悦满溢", "平静如常", "略感烦躁", "情绪低落"};
-        fortune.setMoodEmoji(getMoodEmoji(Math.abs(hash) % 5));
-        fortune.setMoodText(moods[Math.abs(hash) % moods.length]);
+        fortune.setMoodEmoji(getMoodEmoji(Math.floorMod(hash, 5)));
+        fortune.setMoodText(moods[Math.floorMod(hash, moods.length)]);
         
         
         // 每周提示
         // 每周提示
         fortune.setWeeklyTip(getWeeklyTip(fortune.getDominantElement()));
         fortune.setWeeklyTip(getWeeklyTip(fortune.getDominantElement()));