bl4 0.8.5

Borderlands 4 save editor library - encryption, decryption, and parsing
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
//! Class mod skill manipulation
//!
//! Decode, resolve, and edit passive skills on class mod items.
//! Skills are encoded as Part tokens with indices mapping to
//! `passive_{color}_{position}_tier_{N}` part names.

use crate::manifest;
use crate::serial::{PartEncoding, Token};

/// Class mod category IDs
pub const CLASS_MOD_CATEGORIES: &[i64] = &[254, 255, 256, 259, 404];

/// A decoded skill from a class mod serial
#[derive(Debug, Clone)]
pub struct DecodedSkill {
    pub position: String,
    pub tier: u8,
    pub display_name: String,
    pub part_name: String,
    pub part_index: i64,
}

/// A skill to add via --add
#[derive(Debug, Clone)]
pub struct SkillAdd {
    pub position: String,
    pub tier: u8,
}

/// A skill to remove via --remove
#[derive(Debug, Clone)]
pub struct SkillRemove {
    pub position: String,
}

/// Before/after comparison for a skill slot
#[derive(Debug, Clone)]
pub struct SkillDiffEntry {
    pub slot: usize,
    pub before: Option<DecodedSkill>,
    pub after: Option<DecodedSkill>,
    pub changed: bool,
}

/// Check if a category is a class mod
pub fn is_class_mod(category: i64) -> bool {
    CLASS_MOD_CATEGORIES.contains(&category)
}

/// Extract all passive skills from a token list for a given category.
pub fn decode_skills(tokens: &[Token], category: i64) -> Vec<DecodedSkill> {
    let mut skills = Vec::new();

    for token in tokens {
        let (index, _values) = match token {
            Token::Part { index, values, .. } => (*index, values),
            _ => continue,
        };

        let part_name = match manifest::part_name(category, index as i64) {
            Some(n) => n,
            None => continue,
        };

        let (position, tier) = match manifest::parse_passive_part(part_name) {
            Some(p) => p,
            None => continue,
        };

        let display_name = manifest::skill_display_name(category, position)
            .map(|info| info.display_name.clone())
            .unwrap_or_default();

        skills.push(DecodedSkill {
            position: position.to_string(),
            tier,
            display_name,
            part_name: part_name.to_string(),
            part_index: index as i64,
        });
    }

    // Group by position, keep only the highest tier per position
    let mut by_position: std::collections::HashMap<String, DecodedSkill> =
        std::collections::HashMap::new();
    for skill in skills {
        let entry = by_position
            .entry(skill.position.clone())
            .or_insert_with(|| skill.clone());
        if skill.tier > entry.tier {
            *entry = skill;
        }
    }

    let mut result: Vec<DecodedSkill> = by_position.into_values().collect();
    result.sort_by(|a, b| a.position.cmp(&b.position));
    result
}

/// Parse a --add argument: `"Name@Tier"` or `"position@Tier"`
pub fn parse_add(spec: &str, category: i64) -> Result<SkillAdd, String> {
    let (name, tier_str) = spec
        .rsplit_once('@')
        .ok_or_else(|| format!("missing @tier in '{}' (expected 'Name@N')", spec))?;

    let tier: u8 = tier_str
        .parse()
        .map_err(|_| format!("invalid tier '{}' in '{}'", tier_str, spec))?;

    if !(1..=5).contains(&tier) {
        return Err(format!("tier must be 1-5, got {}", tier));
    }

    let position = resolve_skill_name(name.trim(), category)?;
    Ok(SkillAdd { position, tier })
}

/// Parse a --remove argument: just the skill name or position
pub fn parse_remove(name: &str, category: i64) -> Result<SkillRemove, String> {
    let position = resolve_skill_name(name.trim(), category)?;
    Ok(SkillRemove { position })
}

/// Resolve a skill name (display name or part position) to a position string.
fn resolve_skill_name(name: &str, category: i64) -> Result<String, String> {
    // Try as part position directly (with or without passive_ prefix)
    let bare = name.strip_prefix("passive_").unwrap_or(name);
    if manifest::skill_display_name(category, bare).is_some() {
        return Ok(bare.to_string());
    }

    // Try as part position by checking if tier_1 exists in the parts database
    let test_part = format!("passive_{}_tier_1", bare);
    if manifest::part_index(category, &test_part).is_some() {
        return Ok(bare.to_string());
    }

    // Try as display name (case-insensitive)
    if let Some(pos) = manifest::skill_position_from_name(category, name) {
        return Ok(pos.to_string());
    }

    // Try fuzzy: prefix match on display names
    let available = manifest::skills_for_category(category);
    let lower = name.to_lowercase();
    let matches: Vec<_> = available
        .iter()
        .filter(|(_, info)| info.display_name.to_lowercase().starts_with(&lower))
        .collect();

    if matches.len() == 1 {
        return Ok(matches[0].0.to_string());
    }

    if matches.len() > 1 {
        let names: Vec<_> = matches
            .iter()
            .map(|(_, info)| info.display_name.as_str())
            .collect();
        return Err(format!(
            "ambiguous skill name '{}', matches: {}",
            name,
            names.join(", ")
        ));
    }

    Err(format!(
        "skill '{}' not found in category {}",
        name, category
    ))
}

/// A planned edit to a class mod's skill parts.
///
/// `remove_indices` are manifest part indices to strip from the token
/// stream, and `add_parts` are `(part_index, part_name)` pairs to
/// append for each tier being added. `apply_edits` consumes this plan
/// to produce the new token list.
pub struct SkillEditPlan {
    pub remove_indices: Vec<i64>,
    pub add_parts: Vec<(i64, String)>,
}

/// Compute the token edits for add/remove operations.
pub fn compute_edits(
    current: &[DecodedSkill],
    adds: &[SkillAdd],
    removes: &[SkillRemove],
    category: i64,
) -> Result<SkillEditPlan, String> {
    let mut remove_indices: Vec<i64> = Vec::new();
    let mut add_parts: Vec<(i64, String)> = Vec::new();

    // Process explicit removals first
    for rm in removes {
        collect_tier_removals(&rm.position, category, &mut remove_indices);
    }

    // For adds: if the skill already exists, remove its old tiers first
    // If at max capacity and no explicit removal freed a slot, auto-remove lowest tier
    let mut replaced_positions: Vec<String> = removes.iter().map(|r| r.position.clone()).collect();
    let add_positions: Vec<&str> = adds.iter().map(|a| a.position.as_str()).collect();

    for add in adds {
        // If this skill already exists, remove its old tiers
        if current.iter().any(|s| s.position == add.position) {
            collect_tier_removals(&add.position, category, &mut remove_indices);
            if !replaced_positions.contains(&add.position) {
                replaced_positions.push(add.position.clone());
            }
        } else {
            // New skill — need a free slot
            let current_count = current.len();
            let removed_count = replaced_positions.len();
            let net = current_count.saturating_sub(removed_count);

            // If no slot available, auto-remove the lowest-tier skill
            if net >= current_count && !current.is_empty() {
                let replaced_set: Vec<bool> = current
                    .iter()
                    .map(|s| replaced_positions.contains(&s.position))
                    .collect();

                if let Some(victim) = find_replacement_slot(current, &replaced_set, &add_positions)
                {
                    let victim_pos = current[victim].position.clone();
                    collect_tier_removals(&victim_pos, category, &mut remove_indices);
                    replaced_positions.push(victim_pos);
                }
            }
        }

        // Add tier parts for the new skill (tier_1 through tier_N)
        for t in 1..=add.tier {
            let part_name = format!("passive_{}_tier_{}", add.position, t);
            let part_idx = manifest::part_index(category, &part_name).ok_or_else(|| {
                format!("part '{}' not found in category {}", part_name, category)
            })?;
            add_parts.push((part_idx, part_name));
        }
    }

    Ok(SkillEditPlan {
        remove_indices,
        add_parts,
    })
}

/// Build the before/after diff for display.
pub fn build_diff(
    current: &[DecodedSkill],
    adds: &[SkillAdd],
    removes: &[SkillRemove],
    category: i64,
) -> Result<Vec<SkillDiffEntry>, String> {
    let mut state = DiffState::new(current.len(), removes);

    push_removal_entries(current, removes, &mut state);
    push_add_entries(current, adds, category, &mut state);
    push_unchanged_entries(current, &mut state);

    state.diff.sort_by_key(|d| d.slot);
    Ok(state.diff)
}

/// Shared mutable state for the three build_diff phases.
///
/// `handled[i]` tracks whether `current[i]` has already been accounted
/// for by a removal or add; the unchanged phase emits entries only
/// for slots still unhandled. `replaced_positions` grows as adds
/// consume victim slots so later adds don't double-pick the same
/// skill.
struct DiffState {
    diff: Vec<SkillDiffEntry>,
    handled: Vec<bool>,
    replaced_positions: Vec<String>,
}

impl DiffState {
    fn new(current_len: usize, removes: &[SkillRemove]) -> Self {
        Self {
            diff: Vec::new(),
            handled: vec![false; current_len],
            replaced_positions: removes.iter().map(|r| r.position.clone()).collect(),
        }
    }
}

fn push_removal_entries(current: &[DecodedSkill], removes: &[SkillRemove], state: &mut DiffState) {
    for rm in removes {
        if let Some(idx) = current.iter().position(|s| s.position == rm.position) {
            state.handled[idx] = true;
            state.diff.push(SkillDiffEntry {
                slot: idx + 1,
                before: Some(current[idx].clone()),
                after: None,
                changed: true,
            });
        }
    }
}

fn push_add_entries(
    current: &[DecodedSkill],
    adds: &[SkillAdd],
    category: i64,
    state: &mut DiffState,
) {
    let add_positions: Vec<&str> = adds.iter().map(|a| a.position.as_str()).collect();

    for add in adds {
        let new_skill = build_new_skill(add, category);

        if let Some(idx) = current.iter().position(|s| s.position == add.position) {
            // Retiering an existing skill at the same position.
            state.handled[idx] = true;
            state.diff.push(SkillDiffEntry {
                slot: idx + 1,
                before: Some(current[idx].clone()),
                after: Some(new_skill),
                changed: current[idx].tier != add.tier,
            });
            continue;
        }

        let replaced_set: Vec<bool> = current
            .iter()
            .map(|s| {
                state.handled[find_index(current, &s.position)]
                    || state.replaced_positions.contains(&s.position)
            })
            .collect();

        match find_replacement_slot(current, &replaced_set, &add_positions) {
            Some(victim) => {
                state.handled[victim] = true;
                state
                    .replaced_positions
                    .push(current[victim].position.clone());
                state.diff.push(SkillDiffEntry {
                    slot: victim + 1,
                    before: Some(current[victim].clone()),
                    after: Some(new_skill),
                    changed: true,
                });
            }
            None => {
                // Under capacity — grow into a fresh slot.
                state.diff.push(SkillDiffEntry {
                    slot: current.len() + 1,
                    before: None,
                    after: Some(new_skill),
                    changed: true,
                });
            }
        }
    }
}

fn push_unchanged_entries(current: &[DecodedSkill], state: &mut DiffState) {
    for (i, skill) in current.iter().enumerate() {
        if !state.handled[i] {
            state.diff.push(SkillDiffEntry {
                slot: i + 1,
                before: Some(skill.clone()),
                after: Some(skill.clone()),
                changed: false,
            });
        }
    }
}

fn build_new_skill(add: &SkillAdd, category: i64) -> DecodedSkill {
    let display_name = manifest::skill_display_name(category, &add.position)
        .map(|info| info.display_name.clone())
        .unwrap_or_default();

    DecodedSkill {
        position: add.position.clone(),
        tier: add.tier,
        display_name,
        part_name: format!("passive_{}_tier_{}", add.position, add.tier),
        part_index: 0,
    }
}

fn find_index(current: &[DecodedSkill], position: &str) -> usize {
    current
        .iter()
        .position(|c| c.position == position)
        .expect("position came from current, must exist")
}

/// Find the slot with the lowest tier to replace, excluding protected positions.
fn find_replacement_slot(
    current: &[DecodedSkill],
    already_replaced: &[bool],
    protected_positions: &[&str],
) -> Option<usize> {
    current
        .iter()
        .enumerate()
        .filter(|(i, skill)| {
            !already_replaced[*i] && !protected_positions.contains(&skill.position.as_str())
        })
        .min_by_key(|(_, skill)| skill.tier)
        .map(|(i, _)| i)
}

/// Collect all part indices for a given skill position (all tiers) for removal.
fn collect_tier_removals(position: &str, category: i64, remove_indices: &mut Vec<i64>) {
    for t in 1..=5 {
        let part_name = format!("passive_{}_tier_{}", position, t);
        if let Some(idx) = manifest::part_index(category, &part_name) {
            remove_indices.push(idx);
        }
    }
}

/// Apply skill edits to a token stream, preserving structural position.
///
/// Finds the contiguous range of passive skill Part tokens in the stream,
/// removes the old ones, and inserts the new ones at the same position.
/// This preserves firmware VarInts and other non-skill tokens that sit
/// between or after skill parts.
pub fn apply_edits(
    tokens: &[Token],
    remove_indices: &[i64],
    add_parts: &[(i64, String)],
    category: i64,
) -> Vec<Token> {
    let skill_range = find_skill_range(tokens, category);

    let Some((start, end)) = skill_range else {
        return append_initial_skills(tokens, add_parts);
    };

    let remove_set: std::collections::HashSet<i64> = remove_indices.iter().copied().collect();
    let new_skills = rebuild_skill_section(&tokens[start..end], &remove_set, add_parts);

    let mut result = Vec::with_capacity(tokens.len());
    result.extend_from_slice(&tokens[..start]);
    result.extend(new_skills);
    result.extend_from_slice(&tokens[end..]);
    result
}

/// Locate the contiguous range of passive skill Part tokens in the stream.
/// Returns `Some((start, end))` where `end` is exclusive, or `None` if
/// the item has no skill parts yet (e.g. unallocated class mod).
fn find_skill_range(tokens: &[Token], category: i64) -> Option<(usize, usize)> {
    let mut start: Option<usize> = None;
    let mut end = 0usize;
    for (i, token) in tokens.iter().enumerate() {
        if let Token::Part { index, .. } = token {
            if let Some(name) = manifest::part_name(category, *index as i64) {
                if manifest::parse_passive_part(name).is_some() {
                    if start.is_none() {
                        start = Some(i);
                    }
                    end = i + 1;
                }
            }
        }
    }
    start.map(|s| (s, end))
}

/// Append newly-added skill parts to a token stream that had none.
/// Insertion happens immediately before the final `Separator` so the
/// trailing terminator survives the edit.
fn append_initial_skills(tokens: &[Token], add_parts: &[(i64, String)]) -> Vec<Token> {
    let mut result = tokens.to_vec();
    let insert_pos = result
        .iter()
        .rposition(|t| matches!(t, Token::Separator))
        .unwrap_or(result.len());
    for (idx, _) in add_parts {
        result.insert(insert_pos, new_skill_part(*idx));
    }
    result
}

/// Given the existing skill-part slice, produce the replacement slice:
/// existing parts minus any whose index is in `remove_set`, then the
/// new `add_parts` appended at the end.
fn rebuild_skill_section(
    existing: &[Token],
    remove_set: &std::collections::HashSet<i64>,
    add_parts: &[(i64, String)],
) -> Vec<Token> {
    let mut new_skills: Vec<Token> = Vec::new();
    for token in existing {
        if let Token::Part { index, .. } = token {
            if !remove_set.contains(&(*index as i64)) {
                new_skills.push(token.clone());
            }
        }
    }
    for (idx, _) in add_parts {
        new_skills.push(new_skill_part(*idx));
    }
    new_skills
}

fn new_skill_part(part_index: i64) -> Token {
    Token::Part {
        index: part_index as u64,
        values: vec![],
        encoding: PartEncoding::None,
    }
}

/// Validate that a skill position can drop on the given category.
pub fn validate_skill_drop(position: &str, tier: u8, category: i64) -> Result<(), String> {
    let part_name = format!("passive_{}_tier_{}", position, tier);
    match manifest::part_index(category, &part_name) {
        Some(_) => Ok(()),
        None => Err(format!(
            "skill '{}' at tier {} is not a valid drop for category {} (part '{}' not found)",
            position, tier, category, part_name
        )),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_is_class_mod() {
        assert!(is_class_mod(254));
        assert!(is_class_mod(404));
        assert!(!is_class_mod(3));
        assert!(!is_class_mod(10024));
    }

    #[test]
    fn test_parse_add() {
        let result = parse_add("red_1_1@3", 254);
        assert!(result.is_ok(), "Should parse position-based add");
        let add = result.unwrap();
        assert_eq!(add.position, "red_1_1");
        assert_eq!(add.tier, 3);
    }

    #[test]
    fn test_parse_add_invalid_tier() {
        assert!(parse_add("red_1_1@0", 254).is_err());
        assert!(parse_add("red_1_1@6", 254).is_err());
    }

    #[test]
    fn test_parse_add_missing_at() {
        assert!(parse_add("red_1_1", 254).is_err());
    }

    #[test]
    fn test_parse_remove() {
        let result = parse_remove("red_1_1", 254);
        assert!(result.is_ok());
        assert_eq!(result.unwrap().position, "red_1_1");
    }
}