All files / chart-parser/src/core bmson-keys.ts

100% Statements 28/28
100% Branches 10/10
100% Functions 4/4
100% Lines 28/28

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63  443x 443x   443x             651x 2569x 12x     639x         100318x 6x   100312x 1370x   98942x 98942x 196294x 196294x   98942x       1888x                       1890x 1890x 1890x 1890x 73147x 73147x 64649x 64649x 64649x   73147x   1890x    
/** Two-character BMS export capacities; bmson's internal resource keys may grow beyond these limits. */
export const BMSON_BASE36_KEY_CAPACITY = 36 * 36 - 1;
export const BMSON_BASE62_KEY_CAPACITY = 62 * 62 - 1;
 
const BASE62_DIGITS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
 
/**
 * The radix the chart's keys need: base 36 while every resource fits in 1,295 keys, else base 62. The radix is
 * chart-wide (`bms.base`), so one oversized resource moves every key to base 62.
 */
export function resolveBmsonKeyBase(slotCounts: readonly number[]): 36 | 62 {
  for (const count of slotCounts) {
    if (count > BMSON_BASE36_KEY_CAPACITY) {
      return 62;
    }
  }
  return 36;
}
 
/** A minimum-two-character key for a positive, safe-integer slot. */
export function encodeBmsonKey(slot: number, base: 36 | 62): string | undefined {
  if (!Number.isSafeInteger(slot) || slot < 1) {
    return undefined;
  }
  if (base === 36) {
    return slot.toString(36).toUpperCase().padStart(2, '0');
  }
  let key = '';
  do {
    key = BASE62_DIGITS[slot % 62]! + key;
    slot = Math.floor(slot / 62);
  } while (slot > 0);
  return key.padStart(2, '0');
}
 
export function countDistinctValues(values: readonly number[]): number {
  return new Set(values).size;
}
 
export interface BmsonValueKeyTable {
  /** The key for each input value, index for index. */
  keys: string[];
  /** Key → value, ready to merge into the matching resource table. */
  table: Record<string, number>;
}
 
/** One exact key per distinct value, in first-appearance order; repeated values share a key. */
export function createBmsonValueKeyTable(values: readonly number[], base: 36 | 62): BmsonValueKeyTable {
  const keyByValue = new Map<number, string>();
  const table: Record<string, number> = {};
  const keys: string[] = [];
  for (const value of values) {
    let key = keyByValue.get(value);
    if (key === undefined) {
      key = encodeBmsonKey(keyByValue.size + 1, base)!;
      table[key] = value;
      keyByValue.set(value, key);
    }
    keys.push(key);
  }
  return { keys, table };
}