From 4b0416e92a067f11a28f730727a4a5b5d8ff60a3 Mon Sep 17 00:00:00 2001 From: Seth Hillbrand Date: Mon, 28 Aug 2023 15:20:30 -0700 Subject: [PATCH] Simplify logic when setting field vector Previous logic could get stuck in infinite loop if removing element from the middle of the vector Fixes https://gitlab.com/kicad/code/kicad/-/issues/15498 (cherry picked from commit 9636321c09a7868a71c78441870cafe76d3b636d) --- eeschema/sch_sheet.cpp | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/eeschema/sch_sheet.cpp b/eeschema/sch_sheet.cpp index 156f2710cf..9cabbfef4c 100644 --- a/eeschema/sch_sheet.cpp +++ b/eeschema/sch_sheet.cpp @@ -347,19 +347,17 @@ void SCH_SHEET::SwapData( SCH_ITEM* aItem ) void SCH_SHEET::SetFields( const std::vector& aFields ) { m_fields = aFields; - int next_id = SHEET_MANDATORY_FIELDS; - for( int ii = 0; ii < int( m_fields.size() ); ) - { - if( m_fields[ii].GetId() < 0 || m_fields[ii].GetId() >= ssize_t( m_fields.size() ) ) - m_fields[ii].SetId( next_id++ ); + // Ensure that mandatory fields are at the beginning + std::sort( m_fields.begin(), m_fields.end(), + []( const SCH_FIELD& a, const SCH_FIELD& b ) + { + return a.GetId() < b.GetId(); + } ); - if( m_fields[ii].GetId() != ii ) - std::swap( m_fields[ii], m_fields[m_fields[ii].GetId()]); - - if( m_fields[ii].GetId() == ii ) - ++ii; - } + // After mandatory fields, the rest should be sequential user fields + for( int ii = SHEET_MANDATORY_FIELDS; ii < static_cast( m_fields.size() ); ++ii ) + m_fields[ii].SetId( ii ); // Make sure that we get the UNIX variant of the file path SetFileName( m_fields[SHEETFILENAME].GetText() );