Great code
From
Bonita Montero@3:633/10 to
All on Mon Jun 15 11:10:46 2026
I've written a tool called "bg" to combine Windows' runas with start.
One parameter is the affinity-mask for the processors which the star-
ted program is attached to. The below code is the parsing function.
The code wouldn't apply if this function has to be performance since
I work with regexes. But having this this way makes the code rather
short for what is required - imagine you'd have to do that in C.
bool params::state::checkAffinity( params &pms )
{
if( _wcsicmp( m_todo.front(), L"--affinity" ) != 0 )
return false;
if( m_todo.size() < 2 )
{
m_todo = {};
m_errs.emplace_back( L"please specify affinity" );
cerr << "" << endl;
return false;
};
DWORD_PTR dwpAff = 0;
match_results<wstring_view::iterator> match;
defer chop2( [&] { m_todo = m_todo.subspan( 2 ); } );
wstring_view svPattern( m_todo[1] );
constexpr const wchar_t
*RxHex = L"^0x([0-9a-f]+)$",
*RxBin = sizeof( DWORD_PTR ) == 8 ? L"^b((?:[01]+){1,64})$" : L"^b((?:[01]+){1,32})$",
*RxRange = L"^([0-9]+)(?:-([0-9]+))?(,)?";
if( wregex rxHex( RxHex, regex_constants::icase ); regex_match( svPattern.begin(), svPattern.end(), match, rxHex ) )
wistringstream( wstring( svPattern ) ) >> hex >> dwpAff;
else if( wregex rxBinary( RxBin, regex_constants::icase );
regex_match( svPattern.begin(), svPattern.end(), match, rxBinary ) )
for( wchar_t c : wstring_view( match[1].first, match[1].second ) )
dwpAff = dwpAff << 1 | (c - '0');
else
{
defer affZero( [&] { dwpAff = 0; } );
auto it = svPattern.begin();
wregex rx( RxRange );
match_results<wstring_view::iterator> match;
for( ; regex_search( it, svPattern.end(), match, rx ); it = match[0].second )
{
if( match[3].matched && match[3].second == svPattern.end() )
break;
unsigned from, to;
wistringstream( wstring( match[1].first, match[1].second )
) >> from;
if( match[2].matched )
{
wistringstream( wstring( match[2].first,
match[2].second ) ) >> to;
++to;
}
else
to = from + 1;
constexpr unsigned BITS = sizeof(ULONG_PTR) * 8;
if( from >= to || from >= BITS || to > BITS )
break;
constexpr DWORD_PTR ALL = -1;
DWORD_PTR dwpBits = ALL << from;
if( to < BITS )
dwpBits &= ~(ALL << to);
dwpAff |= dwpBits;
}
if( it == svPattern.end() )
affZero.disable();
}
if( !dwpAff )
{
wostringstream woss;
woss << "invalid affinity pattern: " << svPattern;
m_errs.emplace_back( woss.str() );
return true;
}
DWORD_PTR dwpProc, dwpSys;
GetProcessAffinityMask( GetCurrentProcess(), &dwpProc, &dwpSys );
if( (dwpAff &= dwpProc) )
pms.dwpAffinity = dwpAff;
return true;
}
--- PyGate Linux v1.5.16
* Origin: Dragon's Lair, PyGate NNTP<>Fido Gate (3:633/10)