goldforge 0.8.1

Library for handling file formats used by GoldSrc and related engines.
Documentation
// Copyright 2025-2026 Gabriel Bjørnager Jensen.
//
// This Source Code Form is subject to the terms of
// the Mozilla Public License, v. 2.0. If a copy of
// the MPL was not distributed with this file, you
// can obtain one at:
// <https://mozilla.org/MPL/2.0/>.

//! [`Builder::flatten`].

use super::Inner;

use crate::wad::Builder;

impl Builder {
	/// Flattens all patches, keeping only the
	/// inserted of each name.
	pub fn flatten(&mut self) {
		loop {
			// Get the index of the first duplicate.

			let index = 'find_first_duplicate: {
				// Start from the end, going up the front.

				let directory = self.inner.directory();

				for (index, lump) in directory.iter().enumerate().rev() {
					// Search from the front, going down the end.

					for (other_index, other) in directory.iter().enumerate() {
						// Test that this isn't the last patch.

						if other_index == index {
							break;
						}

						// Indicate the duplicate patch.

						// NOTE: We guarantee that padding bytes are always
						// null.
						if other.name() == lump.name() {
							break 'find_first_duplicate index;
						}
					}
				}

				return;
			};

			// Remove the found duplicate.

			match self.inner {
				Inner::Wad { ref mut directory, .. } => {
					directory.remove(index);
				}

				Inner::Wad2 { ref mut directory, .. } => {
					directory.remove(index);
				}

				Inner::Wad3 { ref mut directory, .. } => {
					directory.remove(index);
				}
			}

			// Research for duplicates.
		}
	}
}