Compare commits

...

3 Commits

Author SHA1 Message Date
Leonard Hecker
3f24c6194d wip 2023-01-31 15:10:50 +01:00
Leonard Hecker
392f22dace wip 2023-01-30 23:40:02 +01:00
Leonard Hecker
12d306fdd7 Replace gsl::byte/span with std 2023-01-30 16:18:42 +01:00
207 changed files with 1050 additions and 1080 deletions

View File

@@ -64,13 +64,13 @@ try
// of the wave form to determine the frequency that the sound buffer
// has to be played to achieve the equivalent note frequency.
const auto frequency = std::pow(2.0, (noteNumber - 69.0) / 12.0) * 440.0 * WAVE_SIZE;
buffer->SetFrequency(gsl::narrow_cast<DWORD>(frequency));
buffer->SetFrequency(til::safe_cast_nothrow<DWORD>(frequency));
// For the volume, we're using the formula defined in the General
// MIDI Level 2 specification: Gain in dB = 40 * log10(v/127). We need
// to multiply by 4000, though, because the SetVolume method expects
// the volume to be in hundredths of a decibel.
const auto volume = 4000.0 * std::log10(velocity / 127.0);
buffer->SetVolume(gsl::narrow_cast<LONG>(volume));
buffer->SetVolume(til::safe_cast_nothrow<LONG>(volume));
// Resetting the buffer to a position that is slightly off from the
// last position will help to produce a clearer separation between
// tones when repeating sequences of the same note.

View File

@@ -113,7 +113,7 @@ OutputCellIterator::OutputCellIterator(const std::wstring_view utf16Text, const
// - This is an iterator over legacy colors only. The text is not modified.
// Arguments:
// - legacyAttrs - One legacy color item per cell
OutputCellIterator::OutputCellIterator(const gsl::span<const WORD> legacyAttrs) noexcept :
OutputCellIterator::OutputCellIterator(const std::span<const WORD> legacyAttrs) noexcept :
_mode(Mode::LegacyAttr),
_currentView(s_GenerateViewLegacyAttr(til::at(legacyAttrs, 0))),
_run(legacyAttrs),
@@ -128,7 +128,7 @@ OutputCellIterator::OutputCellIterator(const gsl::span<const WORD> legacyAttrs)
// - This is an iterator over legacy cell data. We will use the unicode text and the legacy color attribute.
// Arguments:
// - charInfos - Multiple cell with unicode text and legacy color data.
OutputCellIterator::OutputCellIterator(const gsl::span<const CHAR_INFO> charInfos) noexcept :
OutputCellIterator::OutputCellIterator(const std::span<const CHAR_INFO> charInfos) noexcept :
_mode(Mode::CharInfo),
_currentView(s_GenerateView(til::at(charInfos, 0))),
_run(charInfos),
@@ -143,7 +143,7 @@ OutputCellIterator::OutputCellIterator(const gsl::span<const CHAR_INFO> charInfo
// - This is an iterator over existing OutputCells with full text and color data.
// Arguments:
// - cells - Multiple cells in a run
OutputCellIterator::OutputCellIterator(const gsl::span<const OutputCell> cells) :
OutputCellIterator::OutputCellIterator(const std::span<const OutputCell> cells) :
_mode(Mode::Cell),
_currentView(s_GenerateView(til::at(cells, 0))),
_run(cells),
@@ -181,15 +181,15 @@ OutputCellIterator::operator bool() const noexcept
}
case Mode::Cell:
{
return _pos < std::get<gsl::span<const OutputCell>>(_run).size();
return _pos < std::get<std::span<const OutputCell>>(_run).size();
}
case Mode::CharInfo:
{
return _pos < std::get<gsl::span<const CHAR_INFO>>(_run).size();
return _pos < std::get<std::span<const CHAR_INFO>>(_run).size();
}
case Mode::LegacyAttr:
{
return _pos < std::get<gsl::span<const WORD>>(_run).size();
return _pos < std::get<std::span<const WORD>>(_run).size();
}
default:
FAIL_FAST_HR(E_NOTIMPL);
@@ -263,7 +263,7 @@ OutputCellIterator& OutputCellIterator::operator++()
_pos++;
if (operator bool())
{
_currentView = s_GenerateView(til::at(std::get<gsl::span<const OutputCell>>(_run), _pos));
_currentView = s_GenerateView(til::at(std::get<std::span<const OutputCell>>(_run), _pos));
}
break;
}
@@ -273,7 +273,7 @@ OutputCellIterator& OutputCellIterator::operator++()
_pos++;
if (operator bool())
{
_currentView = s_GenerateView(til::at(std::get<gsl::span<const CHAR_INFO>>(_run), _pos));
_currentView = s_GenerateView(til::at(std::get<std::span<const CHAR_INFO>>(_run), _pos));
}
break;
}
@@ -283,7 +283,7 @@ OutputCellIterator& OutputCellIterator::operator++()
_pos++;
if (operator bool())
{
_currentView = s_GenerateViewLegacyAttr(til::at(std::get<gsl::span<const WORD>>(_run), _pos));
_currentView = s_GenerateViewLegacyAttr(til::at(std::get<std::span<const WORD>>(_run), _pos));
}
break;
}
@@ -508,7 +508,7 @@ OutputCellView OutputCellIterator::s_GenerateView(const OutputCell& cell)
// - The number of items of the input run consumed between these two iterators.
til::CoordType OutputCellIterator::GetInputDistance(OutputCellIterator other) const noexcept
{
return gsl::narrow_cast<til::CoordType>(_pos - other._pos);
return til::safe_cast_nothrow<til::CoordType>(_pos - other._pos);
}
// Routine Description:
@@ -517,5 +517,5 @@ til::CoordType OutputCellIterator::GetInputDistance(OutputCellIterator other) co
// - The number of cells in the backing buffer filled between these two iterators.
til::CoordType OutputCellIterator::GetCellDistance(OutputCellIterator other) const noexcept
{
return gsl::narrow_cast<til::CoordType>(_distance - other._distance);
return til::safe_cast_nothrow<til::CoordType>(_distance - other._distance);
}

View File

@@ -39,9 +39,9 @@ public:
OutputCellIterator(const CHAR_INFO& charInfo, const size_t fillLimit = 0) noexcept;
OutputCellIterator(const std::wstring_view utf16Text) noexcept;
OutputCellIterator(const std::wstring_view utf16Text, const TextAttribute& attribute, const size_t fillLimit = 0) noexcept;
OutputCellIterator(const gsl::span<const WORD> legacyAttributes) noexcept;
OutputCellIterator(const gsl::span<const CHAR_INFO> charInfos) noexcept;
OutputCellIterator(const gsl::span<const OutputCell> cells);
OutputCellIterator(const std::span<const WORD> legacyAttributes) noexcept;
OutputCellIterator(const std::span<const CHAR_INFO> charInfos) noexcept;
OutputCellIterator(const std::span<const OutputCell> cells);
~OutputCellIterator() = default;
OutputCellIterator& operator=(const OutputCellIterator& it) = default;
@@ -86,13 +86,13 @@ private:
};
Mode _mode;
gsl::span<const WORD> _legacyAttrs;
std::span<const WORD> _legacyAttrs;
std::variant<
std::wstring_view,
gsl::span<const WORD>,
gsl::span<const CHAR_INFO>,
gsl::span<const OutputCell>,
std::span<const WORD>,
std::span<const CHAR_INFO>,
std::span<const OutputCell>,
std::monostate>
_run;

View File

@@ -25,7 +25,7 @@ OutputCellRect::OutputCellRect(const til::CoordType rows, const til::CoordType c
_rows(rows),
_cols(cols)
{
_storage.resize(gsl::narrow<size_t>(rows * cols));
_storage.resize(til::safe_cast<size_t>(rows * cols));
}
// Routine Description:
@@ -34,9 +34,9 @@ OutputCellRect::OutputCellRect(const til::CoordType rows, const til::CoordType c
// - row - The Y position or row index in the buffer.
// Return Value:
// - Read/write span of OutputCells
gsl::span<OutputCell> OutputCellRect::GetRow(const til::CoordType row)
std::span<OutputCell> OutputCellRect::GetRow(const til::CoordType row)
{
return gsl::span<OutputCell>(_FindRowOffset(row), _cols);
return std::span<OutputCell>(_FindRowOffset(row), _cols);
}
// Routine Description:
@@ -47,7 +47,7 @@ gsl::span<OutputCell> OutputCellRect::GetRow(const til::CoordType row)
// - Read-only iterator of OutputCells
OutputCellIterator OutputCellRect::GetRowIter(const til::CoordType row) const
{
const gsl::span<const OutputCell> view(_FindRowOffset(row), _cols);
const std::span<const OutputCell> view(_FindRowOffset(row), _cols);
return OutputCellIterator(view);
}
@@ -61,7 +61,7 @@ OutputCellIterator OutputCellRect::GetRowIter(const til::CoordType row) const
// - Pointer to the location in the rectangle that represents the start of the requested row.
OutputCell* OutputCellRect::_FindRowOffset(const til::CoordType row)
{
return &_storage.at(gsl::narrow_cast<size_t>(row * _cols));
return &_storage.at(til::safe_cast_nothrow<size_t>(row * _cols));
}
// Routine Description:
@@ -73,7 +73,7 @@ OutputCell* OutputCellRect::_FindRowOffset(const til::CoordType row)
// - Pointer to the location in the rectangle that represents the start of the requested row.
const OutputCell* OutputCellRect::_FindRowOffset(const til::CoordType row) const
{
return &_storage.at(gsl::narrow_cast<size_t>(row * _cols));
return &_storage.at(til::safe_cast_nothrow<size_t>(row * _cols));
}
// Routine Description:

View File

@@ -32,7 +32,7 @@ public:
OutputCellRect() noexcept;
OutputCellRect(const til::CoordType rows, const til::CoordType cols);
gsl::span<OutputCell> GetRow(const til::CoordType row);
std::span<OutputCell> GetRow(const til::CoordType row);
OutputCellIterator GetRowIter(const til::CoordType row) const;
til::CoordType Height() const noexcept;

View File

@@ -226,7 +226,7 @@ void ROW::Resize(wchar_t* charsBuffer, uint16_t* charOffsetsBuffer, uint16_t row
void ROW::TransferAttributes(const til::small_rle<TextAttribute, uint16_t, 1>& attr, til::CoordType newWidth)
{
_attr = attr;
_attr.resize_trailing_extent(gsl::narrow<uint16_t>(newWidth));
_attr.resize_trailing_extent(til::safe_cast<uint16_t>(newWidth));
}
// Routine Description:
@@ -260,7 +260,7 @@ OutputCellIterator ROW::WriteCells(OutputCellIterator it, const til::CoordType c
auto currentColor = it->TextAttr();
uint16_t colorUses = 0;
auto colorStarts = gsl::narrow_cast<uint16_t>(columnBegin);
auto colorStarts = til::safe_cast_nothrow<uint16_t>(columnBegin);
auto currentIndex = colorStarts;
while (it && currentIndex <= finalColumnInRow)
@@ -451,8 +451,8 @@ void ROW::ReplaceCharacters(til::CoordType columnBegin, til::CoordType width, co
it = iota_n_mut(it, leadingSpaces, chPos);
*it++ = chPos;
it = fill_small(it, _charOffsets.begin() + colEnd, gsl::narrow_cast<uint16_t>(chPos | CharOffsetsTrailer));
chPos = gsl::narrow_cast<uint16_t>(chPos + chars.size());
it = fill_small(it, _charOffsets.begin() + colEnd, til::safe_cast_nothrow<uint16_t>(chPos | CharOffsetsTrailer));
chPos = til::safe_cast_nothrow<uint16_t>(chPos + chars.size());
it = iota_n_mut(it, trailingSpaces, chPos);
}
@@ -475,7 +475,7 @@ void ROW::_resizeChars(uint16_t colExtEnd, uint16_t chExtBeg, uint16_t chExtEnd,
else
{
const auto minCapacity = std::min<size_t>(UINT16_MAX, _chars.size() + (_chars.size() >> 1));
const auto newCapacity = gsl::narrow<uint16_t>(std::max(newLength, minCapacity));
const auto newCapacity = til::safe_cast<uint16_t>(std::max(newLength, minCapacity));
auto charsHeap = std::make_unique_for_overwrite<wchar_t[]>(newCapacity);
const std::span chars{ charsHeap.get(), newCapacity };
@@ -491,7 +491,7 @@ void ROW::_resizeChars(uint16_t colExtEnd, uint16_t chExtBeg, uint16_t chExtEnd,
const auto end = _charOffsets.end();
for (; it != end; ++it)
{
*it = gsl::narrow_cast<uint16_t>(*it + diff);
*it = til::safe_cast_nothrow<uint16_t>(*it + diff);
}
}
@@ -538,7 +538,7 @@ til::CoordType ROW::MeasureLeft() const noexcept
}
}
return gsl::narrow_cast<til::CoordType>(it - beg);
return til::safe_cast_nothrow<til::CoordType>(it - beg);
}
til::CoordType ROW::MeasureRight() const noexcept
@@ -562,7 +562,7 @@ til::CoordType ROW::MeasureRight() const noexcept
//
// An example: The row is 10 cells wide and `it` points to the second character.
// `it - beg` would return 1, but it's possible it's actually 1 wide glyph and 8 whitespace.
return gsl::narrow_cast<til::CoordType>(_columnCount - (end - it));
return til::safe_cast_nothrow<til::CoordType>(_columnCount - (end - it));
}
bool ROW::ContainsText() const noexcept

View File

@@ -39,7 +39,7 @@ public:
}
explicit constexpr TextAttribute(const WORD wLegacyAttr) noexcept :
_attrs{ gsl::narrow_cast<WORD>(wLegacyAttr & USED_META_ATTRS) },
_attrs{ til::safe_cast_nothrow<WORD>(wLegacyAttr & USED_META_ATTRS) },
_foreground{ gsl::at(s_legacyForegroundColorMap, wLegacyAttr & FG_ATTRS) },
_background{ gsl::at(s_legacyBackgroundColorMap, (wLegacyAttr & BG_ATTRS) >> 4) },
_hyperlinkId{ 0 }

View File

@@ -144,7 +144,7 @@ public:
// 0 and 2. We do this by XORing the index with 00000101, but only if
// one (but not both) of those bit positions is set.
const auto oneBitSet = (index ^ (index >> 2)) & 1;
return gsl::narrow_cast<BYTE>(index ^ oneBitSet ^ (oneBitSet << 2));
return til::safe_cast_nothrow<BYTE>(index ^ oneBitSet ^ (oneBitSet << 2));
}
private:

View File

@@ -19,8 +19,8 @@ namespace
{
BufferAllocator(til::size sz)
{
const auto w = gsl::narrow<uint16_t>(sz.width);
const auto h = gsl::narrow<uint16_t>(sz.height);
const auto w = til::safe_cast<uint16_t>(sz.width);
const auto h = til::safe_cast<uint16_t>(sz.height);
const auto charsBytes = w * sizeof(wchar_t);
// The ROW::_indices array stores 1 more item than the buffer is wide.
@@ -29,7 +29,7 @@ namespace
const auto rowStride = charsBytes + indicesBytes;
// 65535*65535 cells would result in a charsAreaSize of 8GiB.
// --> Use uint64_t so that we can safely do our calculations even on x86.
const auto allocSize = gsl::narrow<size_t>(::base::strict_cast<uint64_t>(rowStride) * ::base::strict_cast<uint64_t>(h));
const auto allocSize = til::safe_cast<size_t>(::base::strict_cast<uint64_t>(rowStride) * ::base::strict_cast<uint64_t>(h));
_buffer = wil::unique_virtualalloc_ptr<std::byte>{ static_cast<std::byte*>(VirtualAlloc(nullptr, allocSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)) };
THROW_IF_NULL_ALLOC(_buffer);
@@ -144,7 +144,7 @@ void TextBuffer::CopyProperties(const TextBuffer& OtherBuffer) noexcept
// - Total number of rows in the buffer
til::CoordType TextBuffer::TotalRowCount() const noexcept
{
return gsl::narrow_cast<til::CoordType>(_storage.size());
return til::safe_cast_nothrow<til::CoordType>(_storage.size());
}
// Routine Description:
@@ -157,7 +157,7 @@ til::CoordType TextBuffer::TotalRowCount() const noexcept
const ROW& TextBuffer::GetRowByOffset(const til::CoordType index) const noexcept
{
// Rows are stored circularly, so the index you ask for is offset by the start position and mod the total of rows.
const auto offsetIndex = gsl::narrow_cast<size_t>(_firstRow + index) % _storage.size();
const auto offsetIndex = til::safe_cast_nothrow<size_t>(_firstRow + index) % _storage.size();
return til::at(_storage, offsetIndex);
}
@@ -171,7 +171,7 @@ const ROW& TextBuffer::GetRowByOffset(const til::CoordType index) const noexcept
ROW& TextBuffer::GetRowByOffset(const til::CoordType index) noexcept
{
// Rows are stored circularly, so the index you ask for is offset by the start position and mod the total of rows.
const auto offsetIndex = gsl::narrow_cast<size_t>(_firstRow + index) % _storage.size();
const auto offsetIndex = til::safe_cast_nothrow<size_t>(_firstRow + index) % _storage.size();
return til::at(_storage, offsetIndex);
}
@@ -751,7 +751,7 @@ const Viewport TextBuffer::GetSize() const noexcept
void TextBuffer::_UpdateSize()
{
_size = Viewport::FromDimensions({ _storage.at(0).size(), gsl::narrow<til::CoordType>(_storage.size()) });
_size = Viewport::FromDimensions({ _storage.at(0).size(), til::safe_cast<til::CoordType>(_storage.size()) });
}
void TextBuffer::_SetFirstRowIndex(const til::CoordType FirstRowIndex) noexcept
@@ -893,7 +893,7 @@ void TextBuffer::SetCurrentLineRendition(const LineRendition lineRendition)
auto fillAttrs = GetCurrentAttributes();
fillAttrs.SetStandardErase();
const auto fillOffset = GetLineWidth(rowIndex);
const auto fillLength = gsl::narrow<size_t>(GetSize().Width() - fillOffset);
const auto fillLength = til::safe_cast<size_t>(GetSize().Width() - fillOffset);
const OutputCellIterator fillData{ fillChar, fillAttrs, fillLength };
row.WriteCells(fillData, fillOffset, false);
// We also need to make sure the cursor is clamped within the new width.
@@ -1798,11 +1798,11 @@ const TextBuffer::TextAndColor TextBuffer::GetText(const bool includeCRLF,
std::vector<COLORREF> selectionBkAttr;
// preallocate to avoid reallocs
selectionText.reserve(gsl::narrow<size_t>(highlight.Width()) + 2); // + 2 for \r\n if we munged it
selectionText.reserve(til::safe_cast<size_t>(highlight.Width()) + 2); // + 2 for \r\n if we munged it
if (copyTextColor)
{
selectionFgAttr.reserve(gsl::narrow<size_t>(highlight.Width()) + 2);
selectionBkAttr.reserve(gsl::narrow<size_t>(highlight.Width()) + 2);
selectionFgAttr.reserve(til::safe_cast<size_t>(highlight.Width()) + 2);
selectionBkAttr.reserve(til::safe_cast<size_t>(highlight.Width()) + 2);
}
// copy char data into the string buffer, skipping trailing bytes
@@ -1888,7 +1888,7 @@ size_t TextBuffer::SpanLength(const til::point coordStart, const til::point coor
const auto bufferSize = GetSize();
// The coords are inclusive, so to get the (inclusive) length we add 1.
const auto length = bufferSize.CompareInBounds(coordEnd, coordStart) + 1;
return gsl::narrow<size_t>(length);
return til::safe_cast<size_t>(length);
}
// Routine Description:
@@ -2085,8 +2085,8 @@ std::string TextBuffer::GenHTML(const TextAndColor& rows,
// these values are byte offsets from start of clipboard
const auto htmlStartPos = ClipboardHeaderSize;
const auto htmlEndPos = ClipboardHeaderSize + gsl::narrow<size_t>(htmlBuilder.tellp());
const auto fragStartPos = ClipboardHeaderSize + gsl::narrow<size_t>(htmlHeader.length());
const auto htmlEndPos = ClipboardHeaderSize + til::safe_cast<size_t>(htmlBuilder.tellp());
const auto fragStartPos = ClipboardHeaderSize + til::safe_cast<size_t>(htmlHeader.length());
const auto fragEndPos = htmlEndPos - HtmlFooter.length();
// header required by HTML 0.9 format
@@ -2293,10 +2293,10 @@ void TextBuffer::_AppendRTFText(std::ostringstream& contentBuilder, const std::w
case L'\\':
case L'{':
case L'}':
contentBuilder << "\\" << gsl::narrow<char>(codeUnit);
contentBuilder << "\\" << til::safe_cast<char>(codeUnit);
break;
default:
contentBuilder << gsl::narrow<char>(codeUnit);
contentBuilder << til::safe_cast<char>(codeUnit);
}
}
else
@@ -2791,7 +2791,7 @@ PointTree TextBuffer::GetPatterns(const til::CoordType firstRow, const til::Coor
std::wstring concatAll;
const auto rowSize = GetRowByOffset(0).size();
concatAll.reserve(gsl::narrow_cast<size_t>(rowSize) * gsl::narrow_cast<size_t>(lastRow - firstRow + 1));
concatAll.reserve(til::safe_cast_nothrow<size_t>(rowSize) * til::safe_cast_nothrow<size_t>(lastRow - firstRow + 1));
// to deal with text that spans multiple lines, we will first concatenate
// all the text into one string and find the patterns in that string

View File

@@ -160,7 +160,7 @@ TextBufferCellIterator& TextBufferCellIterator::operator+=(const ptrdiff_t& move
if (newY == oldY)
{
// hot path
const auto diff = gsl::narrow_cast<ptrdiff_t>(newX) - gsl::narrow_cast<ptrdiff_t>(oldX);
const auto diff = til::safe_cast_nothrow<ptrdiff_t>(newX) - til::safe_cast_nothrow<ptrdiff_t>(oldX);
_attrIter += diff;
_view.UpdateTextAttribute(*_attrIter);
@@ -298,7 +298,7 @@ void TextBufferCellIterator::_SetPos(const til::point newPos) noexcept
if (newPos.x != _pos.x)
{
const auto diff = gsl::narrow_cast<ptrdiff_t>(newPos.x) - gsl::narrow_cast<ptrdiff_t>(_pos.x);
const auto diff = til::safe_cast_nothrow<ptrdiff_t>(newPos.x) - til::safe_cast_nothrow<ptrdiff_t>(_pos.x);
_attrIter += diff;
}

View File

@@ -46,7 +46,7 @@ int __stdcall wWinMain(HINSTANCE, HINSTANCE, LPWSTR, int)
std::wstring appUserModelId;
const auto result = wil::AdaptFixedSizeToAllocatedResult<std::wstring, APPLICATION_USER_MODEL_ID_MAX_LENGTH>(
appUserModelId, [&](PWSTR value, size_t valueLength, gsl::not_null<size_t*> valueLengthNeededWithNull) noexcept -> HRESULT {
UINT32 length = gsl::narrow_cast<UINT32>(valueLength);
UINT32 length = til::safe_cast_nothrow<UINT32>(valueLength);
const LONG rc = GetCurrentApplicationUserModelId(&length, value);
switch (rc)
{

View File

@@ -79,7 +79,7 @@ namespace SettingsModelLocalTests
VERIFY_ARE_EQUAL(til::color(0xFF, 0xFF, 0xFF, 255), til::color{ scheme->CursorColor() });
std::array<COLORREF, COLOR_TABLE_SIZE> expectedCampbellTable;
const auto campbellSpan = gsl::make_span(expectedCampbellTable);
const auto campbellSpan = std::span{ expectedCampbellTable };
Utils::InitializeColorTable(campbellSpan);
for (size_t i = 0; i < expectedCampbellTable.size(); i++)

View File

@@ -14,7 +14,7 @@ static LPCWSTR term_window_class = L"HwndTerminalClass";
// This magic flag is "documented" at https://msdn.microsoft.com/en-us/library/windows/desktop/ms646301(v=vs.85).aspx
// "If the high-order bit is 1, the key is down; otherwise, it is up."
static constexpr short KeyPressed{ gsl::narrow_cast<short>(0x8000) };
static constexpr short KeyPressed{ til::safe_cast_nothrow<short>(0x8000) };
static constexpr bool _IsMouseMessage(UINT uMsg)
{

View File

@@ -52,7 +52,7 @@ void HwndTerminalAutomationPeer::RecordKeyEvent(const WORD vkey)
{
if (const auto charCode{ MapVirtualKey(vkey, MAPVK_VK_TO_CHAR) })
{
if (const auto keyEventChar{ gsl::narrow_cast<wchar_t>(charCode) }; IsReadable({ &keyEventChar, 1 }))
if (const auto keyEventChar{ til::safe_cast_nothrow<wchar_t>(charCode) }; IsReadable({ &keyEventChar, 1 }))
{
_keyEvents.emplace_back(keyEventChar);
}

View File

@@ -227,7 +227,7 @@ namespace winrt::TerminalApp::implementation
{
if (const auto index = realArgs.TerminalArgs().ProfileIndex())
{
if (gsl::narrow<uint32_t>(index.Value()) >= _settings.ActiveProfiles().Size())
if (til::safe_cast<uint32_t>(index.Value()) >= _settings.ActiveProfiles().Size())
{
args.Handled(false);
return;
@@ -405,7 +405,7 @@ namespace winrt::TerminalApp::implementation
{
if (const auto index = newTerminalArgs.ProfileIndex())
{
if (gsl::narrow<uint32_t>(index.Value()) >= _settings.ActiveProfiles().Size())
if (til::safe_cast<uint32_t>(index.Value()) >= _settings.ActiveProfiles().Size())
{
args.Handled(false);
return;

View File

@@ -293,8 +293,8 @@ bool Pane::_Resize(const ResizeDirection& direction)
// Make sure we're not making a pane explode here by resizing it to 0 characters.
const auto changeWidth = _splitState == SplitState::Vertical;
const Size actualSize{ gsl::narrow_cast<float>(_root.ActualWidth()),
gsl::narrow_cast<float>(_root.ActualHeight()) };
const Size actualSize{ static_cast<float>(_root.ActualWidth()),
static_cast<float>(_root.ActualHeight()) };
// actualDimension is the size in DIPs of this pane in the direction we're
// resizing.
const auto actualDimension = changeWidth ? actualSize.Width : actualSize.Height;
@@ -470,8 +470,8 @@ std::shared_ptr<Pane> Pane::NavigateDirection(const std::shared_ptr<Pane> source
// move focus from one child to another child.
// We now must keep track of state while we recurse.
// If we have it, get the size of this pane.
const auto scaleX = _root.ActualWidth() > 0 ? gsl::narrow_cast<float>(_root.ActualWidth()) : 1.f;
const auto scaleY = _root.ActualHeight() > 0 ? gsl::narrow_cast<float>(_root.ActualHeight()) : 1.f;
const auto scaleX = _root.ActualWidth() > 0 ? static_cast<float>(_root.ActualWidth()) : 1.f;
const auto scaleY = _root.ActualHeight() > 0 ? static_cast<float>(_root.ActualHeight()) : 1.f;
const auto paneNeighborPair = _FindPaneAndNeighbor(sourcePane, direction, { 0, 0, scaleX, scaleY });
if (paneNeighborPair.source && paneNeighborPair.neighbor)
@@ -2429,8 +2429,8 @@ SplitState Pane::_convertAutomaticOrDirectionalSplitState(const SplitDirection&
{
// If the requested split type was "auto", determine which direction to
// split based on our current dimensions
const Size actualSize{ gsl::narrow_cast<float>(_root.ActualWidth()),
gsl::narrow_cast<float>(_root.ActualHeight()) };
const Size actualSize{ static_cast<float>(_root.ActualWidth()),
static_cast<float>(_root.ActualHeight()) };
return actualSize.Width >= actualSize.Height ? SplitState::Vertical : SplitState::Horizontal;
}
if (splitType == SplitDirection::Up || splitType == SplitDirection::Down)

View File

@@ -531,7 +531,7 @@ namespace winrt::TerminalApp::implementation
_LastTabClosedHandlers(*this, nullptr);
}
else if (focusedTabIndex.has_value() && focusedTabIndex.value() == gsl::narrow_cast<uint32_t>(tabIndex))
else if (focusedTabIndex.has_value() && focusedTabIndex.value() == til::safe_cast_nothrow<uint32_t>(tabIndex))
{
// Manually select the new tab to get focus, rather than relying on TabView since:
// 1. We want to customize this behavior (e.g., use MRU logic)
@@ -1010,7 +1010,7 @@ namespace winrt::TerminalApp::implementation
{
auto tabView = sender.as<MUX::Controls::TabView>();
auto selectedIndex = tabView.SelectedIndex();
if (selectedIndex >= 0 && selectedIndex < gsl::narrow_cast<int32_t>(_tabs.Size()))
if (selectedIndex >= 0 && selectedIndex < til::safe_cast_nothrow<int32_t>(_tabs.Size()))
{
const auto tab{ _tabs.GetAt(selectedIndex) };
_UpdatedSelectedTab(tab);
@@ -1063,7 +1063,7 @@ namespace winrt::TerminalApp::implementation
// - <none>
void TerminalPage::_TryMoveTab(const uint32_t currentTabIndex, const int32_t suggestedNewTabIndex)
{
auto newTabIndex = gsl::narrow_cast<uint32_t>(std::clamp<int32_t>(suggestedNewTabIndex, 0, _tabs.Size() - 1));
auto newTabIndex = til::safe_cast_nothrow<uint32_t>(std::clamp<int32_t>(suggestedNewTabIndex, 0, _tabs.Size() - 1));
if (currentTabIndex != newTabIndex)
{
auto tab = _tabs.GetAt(currentTabIndex);

View File

@@ -1406,8 +1406,8 @@ namespace winrt::TerminalApp::implementation
void TerminalPage::_KeyDownHandler(const Windows::Foundation::IInspectable& /*sender*/, const Windows::UI::Xaml::Input::KeyRoutedEventArgs& e)
{
const auto keyStatus = e.KeyStatus();
const auto vkey = gsl::narrow_cast<WORD>(e.OriginalKey());
const auto scanCode = gsl::narrow_cast<WORD>(keyStatus.ScanCode);
const auto vkey = til::safe_cast_nothrow<WORD>(e.OriginalKey());
const auto scanCode = til::safe_cast_nothrow<WORD>(keyStatus.ScanCode);
const auto modifiers = _GetPressedModifierKeys();
// GH#11076:
@@ -1486,7 +1486,7 @@ namespace winrt::TerminalApp::implementation
modifiers.IsAltPressed(),
modifiers.IsShiftPressed(),
modifiers.IsWinPressed(),
gsl::narrow_cast<int32_t>(vkey),
til::safe_cast_nothrow<int32_t>(vkey),
scanCode,
}))
{
@@ -1565,7 +1565,7 @@ namespace winrt::TerminalApp::implementation
// http://archives.miloush.net/michkap/archive/2006/09/10/748775.html
// > "The key here is to keep trying to pass stuff to ToUnicode until -1 is not returned."
std::array<wchar_t, 16> buffer;
while (ToUnicodeEx(vkey, scanCode, keyState.data(), buffer.data(), gsl::narrow_cast<int>(buffer.size()), 0b1, nullptr) < 0)
while (ToUnicodeEx(vkey, scanCode, keyState.data(), buffer.data(), til::safe_cast_nothrow<int>(buffer.size()), 0b1, nullptr) < 0)
{
}
}
@@ -2230,7 +2230,7 @@ namespace winrt::TerminalApp::implementation
auto mappedCh = MapVirtualKeyW(keyChord.Vkey(), MAPVK_VK_TO_CHAR);
if (mappedCh != 0)
{
menuItem.KeyboardAcceleratorTextOverride(overrideString + gsl::narrow_cast<wchar_t>(mappedCh));
menuItem.KeyboardAcceleratorTextOverride(overrideString + til::safe_cast_nothrow<wchar_t>(mappedCh));
}
}
}

View File

@@ -992,7 +992,7 @@ namespace winrt::TerminalApp::implementation
// any non-indeterminate state has a value, set the progress ring as such
_tabStatus.IsProgressRingIndeterminate(false);
const auto progressValue = gsl::narrow<uint32_t>(state.Progress());
const auto progressValue = til::safe_cast<uint32_t>(state.Progress());
_tabStatus.ProgressValue(progressValue);
}
// Hide the tab icon (the progress ring is placed over it)

View File

@@ -26,7 +26,7 @@ std::optional<std::wstring_view> ConsoleInputReader::Read()
{
_buffer.resize(BufferSize);
auto succeeded =
ReadConsoleInputW(_handle, _buffer.data(), gsl::narrow_cast<DWORD>(_buffer.size()), &readCount);
ReadConsoleInputW(_handle, _buffer.data(), til::safe_cast_nothrow<DWORD>(_buffer.size()), &readCount);
if (!succeeded)
{
return std::nullopt;

View File

@@ -98,8 +98,8 @@ int wmain(int /*argc*/, wchar_t** /*argv*/)
AzureConnection azureConn{};
winrt::Windows::Foundation::Collections::ValueSet vs{};
vs.Insert(L"initialRows", winrt::Windows::Foundation::PropertyValue::CreateUInt32(gsl::narrow_cast<uint32_t>(size.height)));
vs.Insert(L"initialCols", winrt::Windows::Foundation::PropertyValue::CreateUInt32(gsl::narrow_cast<uint32_t>(size.width)));
vs.Insert(L"initialRows", winrt::Windows::Foundation::PropertyValue::CreateUInt32(til::safe_cast_nothrow<uint32_t>(size.height)));
vs.Insert(L"initialCols", winrt::Windows::Foundation::PropertyValue::CreateUInt32(til::safe_cast_nothrow<uint32_t>(size.width)));
azureConn.Initialize(vs);
const auto state = RunConnectionToCompletion(azureConn, conOut, conIn);

View File

@@ -75,8 +75,8 @@ namespace winrt::Microsoft::Terminal::TerminalConnection::implementation
{
if (settings)
{
_initialRows = gsl::narrow<til::CoordType>(winrt::unbox_value_or<uint32_t>(settings.TryLookup(L"initialRows").try_as<Windows::Foundation::IPropertyValue>(), _initialRows));
_initialCols = gsl::narrow<til::CoordType>(winrt::unbox_value_or<uint32_t>(settings.TryLookup(L"initialCols").try_as<Windows::Foundation::IPropertyValue>(), _initialCols));
_initialRows = til::safe_cast<til::CoordType>(winrt::unbox_value_or<uint32_t>(settings.TryLookup(L"initialRows").try_as<Windows::Foundation::IPropertyValue>(), _initialRows));
_initialCols = til::safe_cast<til::CoordType>(winrt::unbox_value_or<uint32_t>(settings.TryLookup(L"initialCols").try_as<Windows::Foundation::IPropertyValue>(), _initialCols));
}
}
@@ -126,7 +126,7 @@ namespace winrt::Microsoft::Terminal::TerminalConnection::implementation
{
return pInstance->_OutputThread();
}
return gsl::narrow_cast<DWORD>(E_INVALIDARG);
return til::safe_cast_nothrow<DWORD>(E_INVALIDARG);
},
this,
0,
@@ -615,7 +615,7 @@ namespace winrt::Microsoft::Terminal::TerminalConnection::implementation
// - helper function to list the user's tenants and let them decide which tenant they wish to connect to
void AzureConnection::_RunTenantChoiceState()
{
auto numTenants = gsl::narrow<int>(_tenantList.size());
auto numTenants = til::safe_cast<int>(_tenantList.size());
for (auto i = 0; i < numTenants; i++)
{
_WriteStringWithNewline(_formatTenant(i, til::at(_tenantList, i)));

View File

@@ -312,7 +312,7 @@ namespace winrt::Microsoft::Terminal::TerminalConnection::implementation
_transitionToState(ConnectionState::Connecting);
const til::size dimensions{ gsl::narrow<til::CoordType>(_cols), gsl::narrow<til::CoordType>(_rows) };
const til::size dimensions{ til::safe_cast<til::CoordType>(_cols), til::safe_cast<til::CoordType>(_rows) };
// If we do not have pipes already, then this is a fresh connection... not an inbound one that is a received
// handoff from an already-started PTY process.
@@ -392,7 +392,7 @@ namespace winrt::Microsoft::Terminal::TerminalConnection::implementation
{
return pInstance->_OutputThread();
}
return gsl::narrow_cast<DWORD>(E_INVALIDARG);
return til::safe_cast_nothrow<DWORD>(E_INVALIDARG);
},
this,
0,
@@ -618,7 +618,7 @@ namespace winrt::Microsoft::Terminal::TerminalConnection::implementation
{
DWORD read{};
const auto readFail{ !ReadFile(_outPipe.get(), _buffer.data(), gsl::narrow_cast<DWORD>(_buffer.size()), &read, nullptr) };
const auto readFail{ !ReadFile(_outPipe.get(), _buffer.data(), til::safe_cast_nothrow<DWORD>(_buffer.size()), &read, nullptr) };
// When we call CancelSynchronousIo() in Close() this is the branch that's taken and gets us out of here.
if (_isStateAtOrBeyond(ConnectionState::Closing))
@@ -639,7 +639,7 @@ namespace winrt::Microsoft::Terminal::TerminalConnection::implementation
{
_indicateExitWithStatus(HRESULT_FROM_WIN32(lastError)); // print a message
_transitionToState(ConnectionState::Failed);
return gsl::narrow_cast<DWORD>(HRESULT_FROM_WIN32(lastError));
return til::safe_cast_nothrow<DWORD>(HRESULT_FROM_WIN32(lastError));
}
}
@@ -649,7 +649,7 @@ namespace winrt::Microsoft::Terminal::TerminalConnection::implementation
// EXIT POINT
_indicateExitWithStatus(result); // print a message
_transitionToState(ConnectionState::Failed);
return gsl::narrow_cast<DWORD>(result);
return til::safe_cast_nothrow<DWORD>(result);
}
if (_u16Str.empty())

View File

@@ -22,7 +22,7 @@ namespace winrt::Microsoft::Terminal::TerminalConnection::implementation
{
if (wch < 0x20)
{
prettyPrint << L"^" << gsl::narrow_cast<wchar_t>(wch + 0x40);
prettyPrint << L"^" << til::safe_cast_nothrow<wchar_t>(wch + 0x40);
}
else if (wch == 0x7f)
{

View File

@@ -934,8 +934,8 @@ namespace winrt::Microsoft::Terminal::Control::implementation
return;
}
auto cx = gsl::narrow_cast<til::CoordType>(_panelWidth * _compositionScale);
auto cy = gsl::narrow_cast<til::CoordType>(_panelHeight * _compositionScale);
auto cx = til::safe_cast_nothrow<til::CoordType>(_panelWidth * _compositionScale);
auto cy = til::safe_cast_nothrow<til::CoordType>(_panelHeight * _compositionScale);
// Don't actually resize so small that a single character wouldn't fit
// in either dimension. The buffer really doesn't like being size 0.

View File

@@ -204,7 +204,7 @@ namespace winrt::Microsoft::Terminal::Control::implementation
{
// transfer ownership of UiaTextRanges to this new vector
auto providers = SafeArrayToOwningVector<::Microsoft::Terminal::TermControlUiaTextRange>(textRanges);
auto count = gsl::narrow<int>(providers.size());
auto count = til::safe_cast<int>(providers.size());
std::vector<XamlAutomation::ITextRangeProvider> vec;
vec.reserve(count);

View File

@@ -948,7 +948,7 @@ namespace winrt::Microsoft::Terminal::Control::implementation
const auto ch = e.Character();
const auto keyStatus = e.KeyStatus();
const auto scanCode = gsl::narrow_cast<WORD>(keyStatus.ScanCode);
const auto scanCode = til::safe_cast_nothrow<WORD>(keyStatus.ScanCode);
auto modifiers = _GetPressedModifierKeys();
if (keyStatus.IsExtendedKey)
@@ -996,7 +996,7 @@ namespace winrt::Microsoft::Terminal::Control::implementation
modifiers.IsAltPressed(),
modifiers.IsShiftPressed(),
modifiers.IsWinPressed(),
gsl::narrow_cast<WORD>(vkey),
til::safe_cast_nothrow<WORD>(vkey),
0
};
@@ -1015,7 +1015,7 @@ namespace winrt::Microsoft::Terminal::Control::implementation
if (!handled && sendToTerminal)
{
// _TrySendKeyEvent pretends it didn't handle F7 for some unknown reason.
(void)_TrySendKeyEvent(gsl::narrow_cast<WORD>(vkey), scanCode, modifiers, true);
(void)_TrySendKeyEvent(til::safe_cast_nothrow<WORD>(vkey), scanCode, modifiers, true);
// GH#6438: Note that we're _not_ sending the key up here - that'll
// get passed through XAML to our KeyUp handler normally.
handled = true;
@@ -1046,8 +1046,8 @@ namespace winrt::Microsoft::Terminal::Control::implementation
}
const auto keyStatus = e.KeyStatus();
const auto vkey = gsl::narrow_cast<WORD>(e.OriginalKey());
const auto scanCode = gsl::narrow_cast<WORD>(keyStatus.ScanCode);
const auto vkey = til::safe_cast_nothrow<WORD>(e.OriginalKey());
const auto scanCode = til::safe_cast_nothrow<WORD>(keyStatus.ScanCode);
auto modifiers = _GetPressedModifierKeys();
if (keyStatus.IsExtendedKey)
@@ -1193,7 +1193,7 @@ namespace winrt::Microsoft::Terminal::Control::implementation
// http://archives.miloush.net/michkap/archive/2006/09/10/748775.html
// > "The key here is to keep trying to pass stuff to ToUnicode until -1 is not returned."
std::array<wchar_t, 16> buffer;
while (ToUnicodeEx(vkey, scanCode, keyState.data(), buffer.data(), gsl::narrow_cast<int>(buffer.size()), 0b1, nullptr) < 0)
while (ToUnicodeEx(vkey, scanCode, keyState.data(), buffer.data(), til::safe_cast_nothrow<int>(buffer.size()), 0b1, nullptr) < 0)
{
}
}
@@ -2152,7 +2152,7 @@ namespace winrt::Microsoft::Terminal::Control::implementation
width += scale * (thickness.Left + thickness.Right);
height += scale * (thickness.Top + thickness.Bottom);
return { gsl::narrow_cast<float>(width), gsl::narrow_cast<float>(height) };
return { static_cast<float>(width), static_cast<float>(height) };
}
// Method Description:
@@ -2195,7 +2195,7 @@ namespace winrt::Microsoft::Terminal::Control::implementation
width += padding.Left + padding.Right;
height += padding.Top + padding.Bottom;
return { gsl::narrow_cast<float>(width), gsl::narrow_cast<float>(height) };
return { static_cast<float>(width), static_cast<float>(height) };
}
else
{
@@ -2224,13 +2224,13 @@ namespace winrt::Microsoft::Terminal::Control::implementation
const auto fontDimension = widthOrHeight ? fontSize.Width : fontSize.Height;
const auto padding = GetPadding();
auto nonTerminalArea = gsl::narrow_cast<float>(widthOrHeight ?
padding.Left + padding.Right :
padding.Top + padding.Bottom);
auto nonTerminalArea = static_cast<float>(widthOrHeight ?
padding.Left + padding.Right :
padding.Top + padding.Bottom);
if (widthOrHeight && _core.Settings().ScrollState() != ScrollbarState::Hidden)
{
nonTerminalArea += gsl::narrow_cast<float>(ScrollBar().ActualWidth());
nonTerminalArea += static_cast<float>(ScrollBar().ActualWidth());
}
const auto gridSize = dimension - nonTerminalArea;
@@ -2544,7 +2544,7 @@ namespace winrt::Microsoft::Terminal::Control::implementation
auto stream = fileDropData.as<IRandomAccessStream>();
stream.Seek(0);
const uint32_t streamSize = gsl::narrow_cast<uint32_t>(stream.Size());
const uint32_t streamSize = til::safe_cast_nothrow<uint32_t>(stream.Size());
const Buffer buf(streamSize);
const auto buffer = co_await stream.ReadAsync(buf, streamSize, InputStreamOptions::None);

View File

@@ -110,7 +110,7 @@ namespace winrt::Microsoft::Terminal::Control::implementation
{
if (const auto charCode{ MapVirtualKey(vkey, MAPVK_VK_TO_CHAR) })
{
if (const auto keyEventChar{ gsl::narrow_cast<wchar_t>(charCode) }; IsReadable({ &keyEventChar, 1 }))
if (const auto keyEventChar{ til::safe_cast_nothrow<wchar_t>(charCode) }; IsReadable({ &keyEventChar, 1 }))
{
_keyEvents.lock()->emplace_back(keyEventChar);
}

View File

@@ -954,7 +954,7 @@ try
// * If bit 0 is set, a menu is active.
// If this flag is not specified ToUnicodeEx will send us character events on certain Alt+Key combinations (e.g. Alt+Arrow-Up).
// * If bit 2 is set, keyboard state is not changed (Windows 10, version 1607 and newer)
const auto result = ToUnicodeEx(vkey, scanCode, keyState.data(), buffer.data(), gsl::narrow_cast<int>(buffer.size()), 0b101, nullptr);
const auto result = ToUnicodeEx(vkey, scanCode, keyState.data(), buffer.data(), til::safe_cast_nothrow<int>(buffer.size()), 0b101, nullptr);
// TODO:GH#2853 We're only handling single UTF-16 code points right now, since that's the only thing KeyEvent supports.
return result == 1 || result == -1 ? buffer.at(0) : 0;

View File

@@ -53,8 +53,8 @@ namespace winrt::Microsoft::Terminal::Settings::Editor::implementation
}
else
{
const std::wstring xPosString = isnan(InitialPosX()) ? RS_(L"Globals_LaunchModeDefault/Content").c_str() : std::to_wstring(gsl::narrow_cast<int>(InitialPosX()));
const std::wstring yPosString = isnan(InitialPosY()) ? RS_(L"Globals_LaunchModeDefault/Content").c_str() : std::to_wstring(gsl::narrow_cast<int>(InitialPosY()));
const std::wstring xPosString = isnan(InitialPosX()) ? RS_(L"Globals_LaunchModeDefault/Content").c_str() : std::to_wstring(til::safe_cast_nothrow<int>(InitialPosX()));
const std::wstring yPosString = isnan(InitialPosY()) ? RS_(L"Globals_LaunchModeDefault/Content").c_str() : std::to_wstring(til::safe_cast_nothrow<int>(InitialPosY()));
result = fmt::format(L"{}, ({},{})", launchModeString, xPosString, yPosString);
}
@@ -69,7 +69,7 @@ namespace winrt::Microsoft::Terminal::Settings::Editor::implementation
// If there's no value here, return NAN - XAML will ignore it and
// put the placeholder text in the box instead
const auto xCoord = x.try_as<int32_t>();
return xCoord.has_value() ? gsl::narrow_cast<double>(xCoord.value()) : NAN;
return xCoord.has_value() ? static_cast<double>(xCoord.value()) : NAN;
}
double LaunchViewModel::InitialPosY()
@@ -78,7 +78,7 @@ namespace winrt::Microsoft::Terminal::Settings::Editor::implementation
// If there's no value here, return NAN - XAML will ignore it and
// put the placeholder text in the box instead
const auto yCoord = y.try_as<int32_t>();
return yCoord.has_value() ? gsl::narrow_cast<double>(yCoord.value()) : NAN;
return yCoord.has_value() ? static_cast<double>(yCoord.value()) : NAN;
}
void LaunchViewModel::InitialPosX(double xCoord)
@@ -87,7 +87,7 @@ namespace winrt::Microsoft::Terminal::Settings::Editor::implementation
// If the value was cleared, xCoord will be NAN, so check for that
if (!isnan(xCoord))
{
xCoordRef = gsl::narrow_cast<int32_t>(xCoord);
xCoordRef = til::safe_cast_nothrow<int32_t>(xCoord);
}
const LaunchPosition newPos{ xCoordRef, _Settings.GlobalSettings().InitialPosition().Y };
_Settings.GlobalSettings().InitialPosition(newPos);
@@ -100,7 +100,7 @@ namespace winrt::Microsoft::Terminal::Settings::Editor::implementation
// If the value was cleared, yCoord will be NAN, so check for that
if (!isnan(yCoord))
{
yCoordRef = gsl::narrow_cast<int32_t>(yCoord);
yCoordRef = til::safe_cast_nothrow<int32_t>(yCoord);
}
const LaunchPosition newPos{ _Settings.GlobalSettings().InitialPosition().X, yCoordRef };
_Settings.GlobalSettings().InitialPosition(newPos);

View File

@@ -510,7 +510,7 @@ namespace winrt::Microsoft::Terminal::Settings::Editor::implementation
void MainPage::BreadcrumbBar_ItemClicked(const Microsoft::UI::Xaml::Controls::BreadcrumbBar& /*sender*/, const Microsoft::UI::Xaml::Controls::BreadcrumbBarItemClickedEventArgs& args)
{
if (gsl::narrow_cast<uint32_t>(args.Index()) < (_breadcrumbs.Size() - 1))
if (til::safe_cast_nothrow<uint32_t>(args.Index()) < (_breadcrumbs.Size() - 1))
{
const auto tag = args.Item().as<Breadcrumb>()->Tag();
const auto subPage = args.Item().as<Breadcrumb>()->SubPage();

View File

@@ -24,7 +24,7 @@ namespace winrt::Microsoft::Terminal::Settings::Model::implementation
if (const auto args = actionAndArgs.Args())
{
hasher = til::hasher{ gsl::narrow_cast<size_t>(args.Hash()) };
hasher = til::hasher{ til::safe_cast_nothrow<size_t>(args.Hash()) };
}
else
{
@@ -38,7 +38,7 @@ namespace winrt::Microsoft::Terminal::Settings::Model::implementation
case ShortcutAction::action: \
{ \
/* If it does, hash the default values for the args. */ \
static const auto cachedHash = gsl::narrow_cast<size_t>( \
static const auto cachedHash = til::safe_cast_nothrow<size_t>( \
winrt::make_self<implementation::action##Args>()->Hash()); \
hash = cachedHash; \
break; \

View File

@@ -571,7 +571,7 @@ Model::Profile CascadiaSettings::GetProfileForArgs(const Model::NewTerminalArgs&
if (const auto index = newTerminalArgs.ProfileIndex())
{
if (auto profile = GetProfileByIndex(gsl::narrow<uint32_t>(index.Value())))
if (auto profile = GetProfileByIndex(til::safe_cast<uint32_t>(index.Value())))
{
return profile;
}
@@ -669,7 +669,7 @@ Model::Profile CascadiaSettings::_getProfileForCommandLine(const winrt::hstring&
for (; it != end; ++it)
{
const auto& prefix = it->first;
const auto length = gsl::narrow<int>(prefix.size());
const auto length = til::safe_cast<int>(prefix.size());
if (CompareStringOrdinal(needle.data(), length, prefix.data(), length, TRUE) == CSTR_EQUAL)
{
return it->second;

View File

@@ -80,7 +80,7 @@ namespace winrt::Microsoft::Terminal::Settings::Model::implementation
static void _rethrowSerializationExceptionWithLocationInfo(const JsonUtils::DeserializationError& e, const std::string_view& settingsString);
static Json::Value _parseJSON(const std::string_view& content);
static const Json::Value& _getJSONValue(const Json::Value& json, const std::string_view& key) noexcept;
gsl::span<const winrt::com_ptr<implementation::Profile>> _getNonUserOriginProfiles() const;
std::span<const winrt::com_ptr<implementation::Profile>> _getNonUserOriginProfiles() const;
void _parse(const OriginTag origin, const winrt::hstring& source, const std::string_view& content, ParsedSettings& settings);
void _parseFragment(const winrt::hstring& source, const std::string_view& content, ParsedSettings& settings);
static JsonSettings _parseJson(const std::string_view& content);

View File

@@ -531,10 +531,10 @@ const Json::Value& SettingsLoader::_getJSONValue(const Json::Value& json, const
// Thus no matter how many profiles are added later on, the following condition holds true:
// The userSettings.profiles in the range [0, _userProfileCount) contain all profiles specified by the user.
// In turn all profiles in the range [_userProfileCount, ∞) contain newly generated/added profiles.
// gsl::make_span(userSettings.profiles).subspan(_userProfileCount) gets us the latter range.
gsl::span<const winrt::com_ptr<Profile>> SettingsLoader::_getNonUserOriginProfiles() const
// std::span{ userSettings.profiles }.subspan(_userProfileCount) gets us the latter range.
std::span<const winrt::com_ptr<Profile>> SettingsLoader::_getNonUserOriginProfiles() const
{
return gsl::make_span(userSettings.profiles).subspan(_userProfileCount);
return std::span{ userSettings.profiles }.subspan(_userProfileCount);
}
// Parses the given JSON string ("content") and fills a ParsedSettings instance with it.
@@ -783,7 +783,7 @@ void SettingsLoader::_executeGenerator(const IDynamicProfileGenerator& generator
{
generator.GenerateProfiles(inboxSettings.profiles);
}
CATCH_LOG_MSG("Dynamic Profile Namespace: \"%.*s\"", gsl::narrow<int>(generatorNamespace.size()), generatorNamespace.data())
CATCH_LOG_MSG("Dynamic Profile Namespace: \"%.*s\"", til::safe_cast<int>(generatorNamespace.size()), generatorNamespace.data())
// If the generator produced some profiles we're going to give them default attributes.
// By setting the Origin/Source/etc. here, we deduplicate some code and ensure they aren't missing accidentally.
@@ -791,7 +791,7 @@ void SettingsLoader::_executeGenerator(const IDynamicProfileGenerator& generator
{
const winrt::hstring source{ generatorNamespace };
for (const auto& profile : gsl::span(inboxSettings.profiles).subspan(previousSize))
for (const auto& profile : std::span(inboxSettings.profiles).subspan(previousSize))
{
profile->Origin(OriginTag::Generated);
profile->Source(source);
@@ -1303,7 +1303,7 @@ void CascadiaSettings::_resolveNewTabMenuProfiles() const
// continuous lookups in the _activeProfiles vector, we create a map <int, Profile>
// to store these indices in-flight.
auto remainingProfilesMap = std::map<int, Model::Profile>{};
auto activeProfileCount = gsl::narrow_cast<int>(_activeProfiles.Size());
auto activeProfileCount = til::safe_cast_nothrow<int>(_activeProfiles.Size());
for (auto profileIndex = 0; profileIndex < activeProfileCount; profileIndex++)
{
remainingProfilesMap.emplace(profileIndex, _activeProfiles.GetAt(profileIndex));
@@ -1428,7 +1428,7 @@ void CascadiaSettings::_resolveNewTabMenuProfilesSet(const IVector<Model::NewTab
matchEntry->Profiles(single_threaded_map<int, Model::Profile>());
auto activeProfileCount = gsl::narrow_cast<int>(_activeProfiles.Size());
auto activeProfileCount = til::safe_cast_nothrow<int>(_activeProfiles.Size());
for (auto profileIndex = 0; profileIndex < activeProfileCount; profileIndex++)
{
const auto profile = _activeProfiles.GetAt(profileIndex);

View File

@@ -39,7 +39,7 @@ winrt::hstring DefaultTerminal::Version() const
fmt::wmemory_buffer buffer;
fmt::format_to(buffer, L"{}.{}.{}.{}", version.major, version.minor, version.build, version.revision);
return winrt::hstring{ buffer.data(), gsl::narrow_cast<winrt::hstring::size_type>(buffer.size()) };
return winrt::hstring{ buffer.data(), til::safe_cast_nothrow<winrt::hstring::size_type>(buffer.size()) };
}
winrt::hstring DefaultTerminal::Author() const

View File

@@ -17,7 +17,7 @@ static constexpr std::wstring_view PACKAGED_PROFILE_ICON_EXTENSION{ L".png" };
// - A Profile, ready to be filled in
winrt::com_ptr<winrt::Microsoft::Terminal::Settings::Model::implementation::Profile> CreateDynamicProfile(const std::wstring_view& name)
{
const auto profileGuid = Microsoft::Console::Utils::CreateV5Uuid(TERMINAL_PROFILE_NAMESPACE_GUID, gsl::as_bytes(gsl::make_span(name)));
const auto profileGuid = Microsoft::Console::Utils::CreateV5Uuid(TERMINAL_PROFILE_NAMESPACE_GUID, std::as_bytes(std::span{ name }));
std::wstring iconPath{ PACKAGED_PROFILE_ICON_PATH };
iconPath.append(Microsoft::Console::Utils::GuidToString(profileGuid));

View File

@@ -156,7 +156,7 @@ namespace winrt::Microsoft::Terminal::Settings::Model
// the file size changed and we've failed to read the full file.
std::string buffer(static_cast<size_t>(fileSize) + 1, '\0');
DWORD bytesRead = 0;
THROW_IF_WIN32_BOOL_FALSE(ReadFile(file.get(), buffer.data(), gsl::narrow<DWORD>(buffer.size()), &bytesRead, nullptr));
THROW_IF_WIN32_BOOL_FALSE(ReadFile(file.get(), buffer.data(), til::safe_cast<DWORD>(buffer.size()), &bytesRead, nullptr));
// This implementation isn't atomic as we'd need to use an exclusive file lock.
// But this would be annoying for users as it forces them to close the file in their editor.
@@ -272,7 +272,7 @@ namespace winrt::Microsoft::Terminal::Settings::Model
nullptr) };
THROW_LAST_ERROR_IF(!file);
const auto fileSize = gsl::narrow<DWORD>(content.size());
const auto fileSize = til::safe_cast<DWORD>(content.size());
DWORD bytesWritten = 0;
THROW_IF_WIN32_BOOL_FALSE(WriteFile(file.get(), content.data(), fileSize, &bytesWritten, nullptr));

View File

@@ -57,7 +57,7 @@ namespace Microsoft::Terminal::Settings::Model::JsonUtils
const char* begin{ nullptr };
const char* end{ nullptr };
json.getString(&begin, &end);
const std::string_view zeroCopyString{ begin, gsl::narrow_cast<size_t>(end - begin) };
const std::string_view zeroCopyString{ begin, til::safe_cast_nothrow<size_t>(end - begin) };
return zeroCopyString;
}
}

View File

@@ -104,7 +104,7 @@ static int32_t parseNumericCode(const std::wstring_view& str, const std::wstring
const auto value = til::to_ulong({ str.data() + prefix.size(), str.size() - prefix.size() - suffix.size() });
if (value > 0 && value < 256)
{
return gsl::narrow_cast<int32_t>(value);
return til::safe_cast_nothrow<int32_t>(value);
}
throw winrt::hresult_invalid_argument(L"Invalid numeric argument to vk() or sc()");
@@ -291,7 +291,7 @@ static std::wstring _toString(const KeyChord& chord)
// Quick lookup: ranges of vkeys that correlate directly to a key.
if ((vkey >= L'0' && vkey <= L'9') || (vkey >= L'A' && vkey <= L'Z'))
{
buffer.push_back(til::tolower_ascii(gsl::narrow_cast<wchar_t>(vkey)));
buffer.push_back(til::tolower_ascii(til::safe_cast_nothrow<wchar_t>(vkey)));
return buffer;
}
@@ -304,7 +304,7 @@ static std::wstring _toString(const KeyChord& chord)
const auto mappedChar = MapVirtualKeyW(vkey, MAPVK_VK_TO_CHAR);
if (mappedChar != 0)
{
buffer.push_back(gsl::narrow_cast<wchar_t>(mappedChar));
buffer.push_back(til::safe_cast_nothrow<wchar_t>(mappedChar));
return buffer;
}

View File

@@ -217,7 +217,7 @@ static void _accumulateStorePowerShellInstances(std::vector<PowerShellInstance>&
if (previewPackage)
{
out.emplace_back(PowerShellInstance{
gsl::narrow_cast<int>(previewPackage.Id().Version().Major),
til::safe_cast_nothrow<int>(previewPackage.Id().Version().Major),
PowerShellFlags::Store | PowerShellFlags::Preview,
previewPath / PWSH_EXE });
}

View File

@@ -283,12 +283,12 @@ winrt::guid Profile::_GenerateGuidForProfile(const std::wstring_view& name, cons
// our source to build the namespace guid, instead of using the default GUID.
const auto namespaceGuid = !source.empty() ?
Utils::CreateV5Uuid(RUNTIME_GENERATED_PROFILE_NAMESPACE_GUID, gsl::as_bytes(gsl::make_span(source))) :
Utils::CreateV5Uuid(RUNTIME_GENERATED_PROFILE_NAMESPACE_GUID, std::as_bytes(std::span{ source })) :
RUNTIME_GENERATED_PROFILE_NAMESPACE_GUID;
// Always use the name to generate the temporary GUID. That way, across
// reloads, we'll generate the same static GUID.
return { Utils::CreateV5Uuid(namespaceGuid, gsl::as_bytes(gsl::make_span(name))) };
return { Utils::CreateV5Uuid(namespaceGuid, std::as_bytes(std::span{ name })) };
}
// Method Description:

View File

@@ -395,11 +395,11 @@ namespace winrt::Microsoft::Terminal::Settings::Model::implementation
return colorTable;
}
gsl::span<winrt::Microsoft::Terminal::Core::Color> TerminalSettings::_getColorTableImpl()
std::span<winrt::Microsoft::Terminal::Core::Color> TerminalSettings::_getColorTableImpl()
{
if (_ColorTable.has_value())
{
return gsl::make_span(*_ColorTable);
return std::span{ *_ColorTable };
}
for (auto&& parent : _parents)
{

View File

@@ -163,7 +163,7 @@ namespace winrt::Microsoft::Terminal::Settings::Model::implementation
private:
std::optional<std::array<Microsoft::Terminal::Core::Color, COLOR_TABLE_SIZE>> _ColorTable;
gsl::span<Microsoft::Terminal::Core::Color> _getColorTableImpl();
std::span<Microsoft::Terminal::Core::Color> _getColorTableImpl();
static winrt::com_ptr<implementation::TerminalSettings> _CreateWithProfileCommon(const Model::CascadiaSettings& appSettings, const Model::Profile& profile);
void _ApplyProfileSettings(const Model::Profile& profile);

View File

@@ -685,7 +685,7 @@ struct ::Microsoft::Terminal::Settings::Model::JsonUtils::ConversionTrait<::winr
{
const auto indexStr = string.substr(1);
const auto idx = til::to_ulong(indexStr, 16);
color.r = gsl::narrow_cast<uint8_t>(std::min(idx, 15ul));
color.r = til::safe_cast_nothrow<uint8_t>(std::min(idx, 15ul));
}
else
{

View File

@@ -17,7 +17,7 @@ void VsDevCmdGenerator::GenerateProfiles(const VsSetupConfiguration::VsSetupInst
}
const auto seed = GetProfileGuidSeed(instance);
const winrt::guid profileGuid{ ::Microsoft::Console::Utils::CreateV5Uuid(TERMINAL_PROFILE_NAMESPACE_GUID, gsl::as_bytes(gsl::make_span(seed))) };
const winrt::guid profileGuid{ ::Microsoft::Console::Utils::CreateV5Uuid(TERMINAL_PROFILE_NAMESPACE_GUID, std::as_bytes(std::span{ seed })) };
auto profile = winrt::make_self<implementation::Profile>(profileGuid);
profile->Name(winrt::hstring{ GetProfileName(instance) });
profile->Commandline(winrt::hstring{ GetProfileCommandLine(instance) });

View File

@@ -18,7 +18,7 @@ void VsDevShellGenerator::GenerateProfiles(const VsSetupConfiguration::VsSetupIn
}
const auto seed = GetProfileGuidSeed(instance);
const winrt::guid profileGuid{ ::Microsoft::Console::Utils::CreateV5Uuid(TERMINAL_PROFILE_NAMESPACE_GUID, gsl::as_bytes(gsl::make_span(seed))) };
const winrt::guid profileGuid{ ::Microsoft::Console::Utils::CreateV5Uuid(TERMINAL_PROFILE_NAMESPACE_GUID, std::as_bytes(std::span{ seed })) };
auto profile = winrt::make_self<implementation::Profile>(profileGuid);
profile->Name(winrt::hstring{ GetProfileName(instance) });
profile->Commandline(winrt::hstring{ GetProfileCommandLine(instance) });

View File

@@ -189,7 +189,7 @@ static bool getWslNames(const wil::unique_hkey& wslRootKey,
std::wstring buffer;
auto result = wil::AdaptFixedSizeToAllocatedResult<std::wstring, 256>(buffer, [&](PWSTR value, size_t valueLength, size_t* valueLengthNeededWithNull) -> HRESULT {
auto length = gsl::narrow<DWORD>(valueLength * sizeof(wchar_t));
auto length = til::safe_cast<DWORD>(valueLength * sizeof(wchar_t));
const auto status = RegQueryValueExW(distroKey.get(), RegKeyDistroName, 0, nullptr, reinterpret_cast<BYTE*>(value), &length);
// length will receive the number of bytes including trailing null byte. Convert to a number of wchar_t's.
// AdaptFixedSizeToAllocatedResult will then resize buffer to valueLengthNeededWithNull.

View File

@@ -463,7 +463,7 @@ void ConptyRoundtripTests::TestWrappingALongString()
const auto initialTermView = term->GetViewport();
const auto charsToWrite = gsl::narrow_cast<til::CoordType>(TestUtils::Test100CharsString.size());
const auto charsToWrite = til::safe_cast_nothrow<til::CoordType>(TestUtils::Test100CharsString.size());
VERIFY_ARE_EQUAL(100, charsToWrite);
VERIFY_ARE_EQUAL(0, initialTermView.Top());
@@ -512,7 +512,7 @@ void ConptyRoundtripTests::TestAdvancedWrapping()
_flushFirstFrame();
const auto charsToWrite = gsl::narrow_cast<til::CoordType>(TestUtils::Test100CharsString.size());
const auto charsToWrite = til::safe_cast_nothrow<til::CoordType>(TestUtils::Test100CharsString.size());
VERIFY_ARE_EQUAL(100, charsToWrite);
hostSm.ProcessString(TestUtils::Test100CharsString);
@@ -2537,9 +2537,9 @@ void ConptyRoundtripTests::TestCursorInDeferredEOLPositionOnNewLineWithSpaces()
_checkConptyOutput = false;
// newline down to the bottom
hostSm.ProcessString(std::wstring(gsl::narrow_cast<size_t>(TerminalViewHeight), L'\n'));
hostSm.ProcessString(std::wstring(til::safe_cast_nothrow<size_t>(TerminalViewHeight), L'\n'));
// fill width-1 with "A", then add one space and another character..
hostSm.ProcessString(std::wstring(gsl::narrow_cast<size_t>(TerminalViewWidth) - 1, L'A') + L" B");
hostSm.ProcessString(std::wstring(til::safe_cast_nothrow<size_t>(TerminalViewWidth) - 1, L'A') + L" B");
auto verifyBuffer = [&](const TextBuffer& tb, til::CoordType bottomRow) {
// Buffer contents should look like the following: (80 wide)
@@ -2561,7 +2561,7 @@ void ConptyRoundtripTests::TestCursorInDeferredEOLPositionOnNewLineWithSpaces()
VERIFY_IS_TRUE(secondToLastRow.WasWrapForced());
VERIFY_IS_FALSE(lastRow.WasWrapForced());
auto expectedStringSecondToLastRow{ std::wstring(gsl::narrow_cast<size_t>(tb.GetSize().Width()) - 1, L'A') + L" " };
auto expectedStringSecondToLastRow{ std::wstring(til::safe_cast_nothrow<size_t>(tb.GetSize().Width()) - 1, L'A') + L" " };
TestUtils::VerifyExpectedString(tb, expectedStringSecondToLastRow, { 0, bottomRow - 1 });
TestUtils::VerifyExpectedString(tb, L"B", { 0, bottomRow });
};

View File

@@ -56,7 +56,7 @@ namespace
HRESULT InvalidateAll() noexcept { return S_OK; }
HRESULT InvalidateCircling(_Out_ bool* /*pForcePaint*/) noexcept { return S_OK; }
HRESULT PaintBackground() noexcept { return S_OK; }
HRESULT PaintBufferLine(gsl::span<const Cluster> /*clusters*/, til::point /*coord*/, bool /*fTrimLeft*/, bool /*lineWrapped*/) noexcept { return S_OK; }
HRESULT PaintBufferLine(std::span<const Cluster> /*clusters*/, til::point /*coord*/, bool /*fTrimLeft*/, bool /*lineWrapped*/) noexcept { return S_OK; }
HRESULT PaintBufferGridLines(GridLineSet /*lines*/, COLORREF /*color*/, size_t /*cchLine*/, til::point /*coordTarget*/) noexcept { return S_OK; }
HRESULT PaintSelection(const til::rect& /*rect*/) noexcept { return S_OK; }
HRESULT PaintCursor(const CursorOptions& /*options*/) noexcept { return S_OK; }
@@ -65,7 +65,7 @@ namespace
HRESULT UpdateDpi(int /*iDpi*/) noexcept { return S_OK; }
HRESULT UpdateViewport(const til::inclusive_rect& /*srNewViewport*/) noexcept { return S_OK; }
HRESULT GetProposedFont(const FontInfoDesired& /*FontInfoDesired*/, _Out_ FontInfo& /*FontInfo*/, int /*iDpi*/) noexcept { return S_OK; }
HRESULT GetDirtyArea(gsl::span<const til::rect>& /*area*/) noexcept { return S_OK; }
HRESULT GetDirtyArea(std::span<const til::rect>& /*area*/) noexcept { return S_OK; }
HRESULT GetFontSize(_Out_ til::size* /*pFontSize*/) noexcept { return S_OK; }
HRESULT IsGlyphWideByFont(std::wstring_view /*glyph*/, _Out_ bool* /*pResult*/) noexcept { return S_OK; }

View File

@@ -504,7 +504,7 @@ namespace TerminalCoreUnitTests
term.MultiClickSelection(clickPos, Terminal::SelectionExpansion::Word);
// Validate selection area
ValidateSingleRowSelection(term, til::inclusive_rect{ 4, 10, gsl::narrow<til::CoordType>(4 + text.size() - 1), 10 });
ValidateSingleRowSelection(term, til::inclusive_rect{ 4, 10, til::safe_cast<til::CoordType>(4 + text.size() - 1), 10 });
}
TEST_METHOD(DoubleClick_Delimiter)

View File

@@ -351,66 +351,66 @@ void TerminalCoreUnitTests::TerminalApiTest::SetTaskbarProgress()
auto& stateMachine = *(term._stateMachine);
// Initial values for taskbar state and progress should be 0
VERIFY_ARE_EQUAL(term.GetTaskbarState(), gsl::narrow<size_t>(0));
VERIFY_ARE_EQUAL(term.GetTaskbarProgress(), gsl::narrow<size_t>(0));
VERIFY_ARE_EQUAL(term.GetTaskbarState(), til::safe_cast<size_t>(0));
VERIFY_ARE_EQUAL(term.GetTaskbarProgress(), til::safe_cast<size_t>(0));
// Set some values for taskbar state and progress through state machine
stateMachine.ProcessString(L"\x1b]9;4;1;50\x1b\\");
VERIFY_ARE_EQUAL(term.GetTaskbarState(), gsl::narrow<size_t>(1));
VERIFY_ARE_EQUAL(term.GetTaskbarProgress(), gsl::narrow<size_t>(50));
VERIFY_ARE_EQUAL(term.GetTaskbarState(), til::safe_cast<size_t>(1));
VERIFY_ARE_EQUAL(term.GetTaskbarProgress(), til::safe_cast<size_t>(50));
// Reset to 0
stateMachine.ProcessString(L"\x1b]9;4;0;0\x1b\\");
VERIFY_ARE_EQUAL(term.GetTaskbarState(), gsl::narrow<size_t>(0));
VERIFY_ARE_EQUAL(term.GetTaskbarProgress(), gsl::narrow<size_t>(0));
VERIFY_ARE_EQUAL(term.GetTaskbarState(), til::safe_cast<size_t>(0));
VERIFY_ARE_EQUAL(term.GetTaskbarProgress(), til::safe_cast<size_t>(0));
// Set an out of bounds value for state
stateMachine.ProcessString(L"\x1b]9;4;5;50\x1b\\");
// Nothing should have changed (dispatch should have returned false)
VERIFY_ARE_EQUAL(term.GetTaskbarState(), gsl::narrow<size_t>(0));
VERIFY_ARE_EQUAL(term.GetTaskbarProgress(), gsl::narrow<size_t>(0));
VERIFY_ARE_EQUAL(term.GetTaskbarState(), til::safe_cast<size_t>(0));
VERIFY_ARE_EQUAL(term.GetTaskbarProgress(), til::safe_cast<size_t>(0));
// Set an out of bounds value for progress
stateMachine.ProcessString(L"\x1b]9;4;1;999\x1b\\");
// Progress should have been clamped to 100
VERIFY_ARE_EQUAL(term.GetTaskbarState(), gsl::narrow<size_t>(1));
VERIFY_ARE_EQUAL(term.GetTaskbarProgress(), gsl::narrow<size_t>(100));
VERIFY_ARE_EQUAL(term.GetTaskbarState(), til::safe_cast<size_t>(1));
VERIFY_ARE_EQUAL(term.GetTaskbarProgress(), til::safe_cast<size_t>(100));
// Don't specify any params
stateMachine.ProcessString(L"\x1b]9;4\x1b\\");
// State and progress should both be reset to 0
VERIFY_ARE_EQUAL(term.GetTaskbarState(), gsl::narrow<size_t>(0));
VERIFY_ARE_EQUAL(term.GetTaskbarProgress(), gsl::narrow<size_t>(0));
VERIFY_ARE_EQUAL(term.GetTaskbarState(), til::safe_cast<size_t>(0));
VERIFY_ARE_EQUAL(term.GetTaskbarProgress(), til::safe_cast<size_t>(0));
// Specify additional params
stateMachine.ProcessString(L"\x1b]9;4;1;80;123\x1b\\");
// Additional params should be ignored, state and progress still set normally
VERIFY_ARE_EQUAL(term.GetTaskbarState(), gsl::narrow<size_t>(1));
VERIFY_ARE_EQUAL(term.GetTaskbarProgress(), gsl::narrow<size_t>(80));
VERIFY_ARE_EQUAL(term.GetTaskbarState(), til::safe_cast<size_t>(1));
VERIFY_ARE_EQUAL(term.GetTaskbarProgress(), til::safe_cast<size_t>(80));
// Edge cases + trailing semicolon testing
stateMachine.ProcessString(L"\x1b]9;4;2;\x1b\\");
// String should be processed correctly despite the trailing semicolon,
// taskbar progress should remain unchanged from previous value
VERIFY_ARE_EQUAL(term.GetTaskbarState(), gsl::narrow<size_t>(2));
VERIFY_ARE_EQUAL(term.GetTaskbarProgress(), gsl::narrow<size_t>(80));
VERIFY_ARE_EQUAL(term.GetTaskbarState(), til::safe_cast<size_t>(2));
VERIFY_ARE_EQUAL(term.GetTaskbarProgress(), til::safe_cast<size_t>(80));
stateMachine.ProcessString(L"\x1b]9;4;3;75\x1b\\");
// Given progress value should be ignored because this is the indeterminate state,
// so the progress value should remain unchanged
VERIFY_ARE_EQUAL(term.GetTaskbarState(), gsl::narrow<size_t>(3));
VERIFY_ARE_EQUAL(term.GetTaskbarProgress(), gsl::narrow<size_t>(80));
VERIFY_ARE_EQUAL(term.GetTaskbarState(), til::safe_cast<size_t>(3));
VERIFY_ARE_EQUAL(term.GetTaskbarProgress(), til::safe_cast<size_t>(80));
stateMachine.ProcessString(L"\x1b]9;4;0;50\x1b\\");
// Taskbar progress should be 0 (the given value should be ignored)
VERIFY_ARE_EQUAL(term.GetTaskbarState(), gsl::narrow<size_t>(0));
VERIFY_ARE_EQUAL(term.GetTaskbarProgress(), gsl::narrow<size_t>(0));
VERIFY_ARE_EQUAL(term.GetTaskbarState(), til::safe_cast<size_t>(0));
VERIFY_ARE_EQUAL(term.GetTaskbarProgress(), til::safe_cast<size_t>(0));
stateMachine.ProcessString(L"\x1b]9;4;2;\x1b\\");
// String should be processed correctly despite the trailing semicolon,
// taskbar progress should be set to a 'minimum', non-zero value
VERIFY_ARE_EQUAL(term.GetTaskbarState(), gsl::narrow<size_t>(2));
VERIFY_IS_GREATER_THAN(term.GetTaskbarProgress(), gsl::narrow<size_t>(0));
VERIFY_ARE_EQUAL(term.GetTaskbarState(), til::safe_cast<size_t>(2));
VERIFY_IS_GREATER_THAN(term.GetTaskbarProgress(), til::safe_cast<size_t>(0));
}
void TerminalCoreUnitTests::TerminalApiTest::SetWorkingDirectory()

View File

@@ -103,7 +103,7 @@ void TerminalBufferTests::TestWrappingCharByChar()
const auto initialView = term->GetViewport();
auto& cursor = termTb.GetCursor();
const auto charsToWrite = gsl::narrow_cast<til::CoordType>(TestUtils::Test100CharsString.size());
const auto charsToWrite = til::safe_cast_nothrow<til::CoordType>(TestUtils::Test100CharsString.size());
VERIFY_ARE_EQUAL(0, initialView.Top());
VERIFY_ARE_EQUAL(32, initialView.BottomExclusive());
@@ -142,7 +142,7 @@ void TerminalBufferTests::TestWrappingALongString()
const auto initialView = term->GetViewport();
auto& cursor = termTb.GetCursor();
const auto charsToWrite = gsl::narrow_cast<til::CoordType>(TestUtils::Test100CharsString.size());
const auto charsToWrite = til::safe_cast_nothrow<til::CoordType>(TestUtils::Test100CharsString.size());
VERIFY_ARE_EQUAL(100, charsToWrite);
VERIFY_ARE_EQUAL(0, initialView.Top());

View File

@@ -26,7 +26,7 @@ using namespace std::chrono_literals;
// This magic flag is "documented" at https://msdn.microsoft.com/en-us/library/windows/desktop/ms646301(v=vs.85).aspx
// "If the high-order bit is 1, the key is down; otherwise, it is up."
static constexpr short KeyPressed{ gsl::narrow_cast<short>(0x8000) };
static constexpr short KeyPressed{ til::safe_cast_nothrow<short>(0x8000) };
AppHost::AppHost() noexcept :
_app{},
@@ -172,8 +172,8 @@ void AppHost::SetTaskbarProgress(const winrt::Windows::Foundation::IInspectable&
if (_logic)
{
const auto state = _logic.TaskbarState();
_window->SetTaskbarProgress(gsl::narrow_cast<size_t>(state.State()),
gsl::narrow_cast<size_t>(state.Progress()));
_window->SetTaskbarProgress(til::safe_cast_nothrow<size_t>(state.State()),
til::safe_cast_nothrow<size_t>(state.Progress()));
}
}
@@ -569,8 +569,8 @@ void AppHost::_HandleCreateWindow(const HWND hwnd, til::rect proposedRect, Launc
// Acquire the actual initial position
auto initialPos = _logic.GetInitialPosition(proposedRect.left, proposedRect.top);
const auto centerOnLaunch = _logic.CenterOnLaunch();
proposedRect.left = gsl::narrow<til::CoordType>(initialPos.X);
proposedRect.top = gsl::narrow<til::CoordType>(initialPos.Y);
proposedRect.left = til::safe_cast<til::CoordType>(initialPos.X);
proposedRect.top = til::safe_cast<til::CoordType>(initialPos.Y);
long adjustedHeight = 0;
long adjustedWidth = 0;
@@ -1081,7 +1081,7 @@ winrt::fire_and_forget AppHost::_setupGlobalHotkeys()
// If a hotkey with a given HWND and ID combination already exists
// then a duplicate one will be added, which we don't want.
// (Additionally we want to remove hotkeys that were removed from the settings.)
for (auto i = 0, count = gsl::narrow_cast<int>(_hotkeys.size()); i < count; ++i)
for (auto i = 0, count = til::safe_cast_nothrow<int>(_hotkeys.size()); i < count; ++i)
{
_window->UnregisterHotKey(i);
}
@@ -1093,7 +1093,7 @@ winrt::fire_and_forget AppHost::_setupGlobalHotkeys()
{
if (auto summonArgs = cmd.ActionAndArgs().Args().try_as<Settings::Model::GlobalSummonArgs>())
{
auto index = gsl::narrow_cast<int>(_hotkeys.size());
auto index = til::safe_cast_nothrow<int>(_hotkeys.size());
const auto succeeded = _window->RegisterHotKey(index, keyChord);
TraceLoggingWrite(g_hWindowsTerminalProvider,

View File

@@ -232,12 +232,12 @@ LRESULT IslandWindow::_OnSizing(const WPARAM wParam, const LPARAM lParam)
// If user has dragged anything but the top or bottom border (so e.g. left border,
// top-right corner etc.), then this means that the width has changed. We thus ask to
// adjust this new width so that terminal(s) is/are aligned to their character grid(s).
clientWidth = gsl::narrow_cast<decltype(clientWidth)>(_pfnSnapDimensionCallback(true, gsl::narrow_cast<float>(clientWidth)));
clientWidth = til::safe_cast_nothrow<decltype(clientWidth)>(_pfnSnapDimensionCallback(true, static_cast<float>(clientWidth)));
}
if (wParam != WMSZ_LEFT && wParam != WMSZ_RIGHT)
{
// Analogous to above, but for height.
clientHeight = gsl::narrow_cast<decltype(clientHeight)>(_pfnSnapDimensionCallback(false, gsl::narrow_cast<float>(clientHeight)));
clientHeight = til::safe_cast_nothrow<decltype(clientHeight)>(_pfnSnapDimensionCallback(false, static_cast<float>(clientHeight)));
}
// Now make the window rectangle match the calculated client width and height,
@@ -405,7 +405,7 @@ void IslandWindow::_OnGetMinMaxInfo(const WPARAM /*wParam*/, const LPARAM lParam
// - The total dimension
long IslandWindow::_calculateTotalSize(const bool isWidth, const long clientSize, const long nonClientSize)
{
return gsl::narrow_cast<int>(_pfnSnapDimensionCallback(isWidth, gsl::narrow_cast<float>(clientSize)) + nonClientSize);
return til::safe_cast_nothrow<int>(_pfnSnapDimensionCallback(isWidth, static_cast<float>(clientSize)) + nonClientSize);
}
[[nodiscard]] LRESULT IslandWindow::MessageHandler(UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept

View File

@@ -451,13 +451,13 @@ til::rect NonClientIslandWindow::_GetDragAreaRect() const noexcept
// of the parent HWND.
//
// x here is the width of the tabs.
const auto x = gsl::narrow_cast<til::CoordType>(clientDragBarRect.X * scale);
const auto x = til::safe_cast_nothrow<til::CoordType>(clientDragBarRect.X * scale);
return {
x,
gsl::narrow_cast<til::CoordType>(clientDragBarRect.Y * scale),
gsl::narrow_cast<til::CoordType>((clientDragBarRect.Width + clientDragBarRect.X) * scale) - x,
gsl::narrow_cast<til::CoordType>((clientDragBarRect.Height + clientDragBarRect.Y) * scale),
til::safe_cast_nothrow<til::CoordType>(clientDragBarRect.Y * scale),
til::safe_cast_nothrow<til::CoordType>((clientDragBarRect.Width + clientDragBarRect.X) * scale) - x,
til::safe_cast_nothrow<til::CoordType>((clientDragBarRect.Height + clientDragBarRect.Y) * scale),
};
}

View File

@@ -155,7 +155,7 @@ HMENU NotificationIcon::_CreateContextMenu(const IVectorView<winrt::Microsoft::T
SetMenuInfo(hMenu, &mi);
// Focus Current Terminal Window
AppendMenu(hMenu, MF_STRING, gsl::narrow<UINT_PTR>(NotificationIconMenuItemAction::FocusTerminal), RS_(L"NotificationIconFocusTerminal").c_str());
AppendMenu(hMenu, MF_STRING, til::safe_cast<UINT_PTR>(NotificationIconMenuItemAction::FocusTerminal), RS_(L"NotificationIconFocusTerminal").c_str());
AppendMenu(hMenu, MF_SEPARATOR, 0, L"");
// Submenu for Windows
@@ -176,7 +176,7 @@ HMENU NotificationIcon::_CreateContextMenu(const IVectorView<winrt::Microsoft::T
displayText << L" [" << std::wstring_view{ p.Name } << L"]";
}
AppendMenu(submenu, MF_STRING, gsl::narrow<UINT_PTR>(p.Id), displayText.str().c_str());
AppendMenu(submenu, MF_STRING, til::safe_cast<UINT_PTR>(p.Id), displayText.str().c_str());
}
MENUINFO submenuInfo{};
@@ -209,7 +209,7 @@ void NotificationIcon::MenuItemSelected(const HMENU menu, const UINT menuItemInd
GetMenuInfo(menu, &mi);
if (mi.dwMenuData)
{
if (gsl::narrow<NotificationIconMenuItemAction>(mi.dwMenuData) == NotificationIconMenuItemAction::SummonWindow)
if (til::safe_cast<NotificationIconMenuItemAction>(mi.dwMenuData) == NotificationIconMenuItemAction::SummonWindow)
{
winrt::Microsoft::Terminal::Remoting::SummonWindowSelectionArgs args{};
args.WindowID(GetMenuItemID(menu, menuItemIndex));
@@ -222,7 +222,7 @@ void NotificationIcon::MenuItemSelected(const HMENU menu, const UINT menuItemInd
}
// Now check the menu item itself for an action.
const auto action = gsl::narrow<NotificationIconMenuItemAction>(GetMenuItemID(menu, menuItemIndex));
const auto action = til::safe_cast<NotificationIconMenuItemAction>(GetMenuItemID(menu, menuItemIndex));
switch (action)
{
case NotificationIconMenuItemAction::FocusTerminal:

View File

@@ -171,7 +171,7 @@ std::vector<wil::com_ptr<T>> SafeArrayToOwningVector(SAFEARRAY* safeArray)
// any of the elements in the SAFEARRAY because we
// cannot identify how many elements there are.
std::vector<wil::com_ptr<T>> result{ gsl::narrow<std::size_t>(count) };
std::vector<wil::com_ptr<T>> result{ til::safe_cast<std::size_t>(count) };
for (int i = 0; i < count; i++)
{
result[i].attach(pVals[i]);

View File

@@ -103,7 +103,7 @@
Conhost code converts DWORDs to HANDLEs for instance.
C4467: usage of ATL attributes is deprecated
Conhost code still uses ATL.
C26445: Do not assign gsl::span or std::string_view to a reference. They are cheap to construct and are not owners of the underlying data. (gsl.view).
C26445: Do not assign std::span or std::string_view to a reference. They are cheap to construct and are not owners of the underlying data. (gsl.view).
Even for MSVC v19.32 this is actually far from true. Copying (as opposed to referencing) larger
than register-sized structures is fairly expensive. Example: https://godbolt.org/z/oPco88PaP
C26813: Use 'bitwise and' to check if a flag is set.

View File

@@ -74,7 +74,7 @@ public:
std::unique_ptr<IWaitRoutine>& waiter) noexcept override;
[[nodiscard]] HRESULT ReadConsoleAImpl(IConsoleInputObject& context,
gsl::span<char> buffer,
std::span<char> buffer,
size_t& written,
std::unique_ptr<IWaitRoutine>& waiter,
const std::string_view initialData,
@@ -85,7 +85,7 @@ public:
DWORD& controlKeyState) noexcept override;
[[nodiscard]] HRESULT ReadConsoleWImpl(IConsoleInputObject& context,
gsl::span<char> buffer,
std::span<char> buffer,
size_t& written,
std::unique_ptr<IWaitRoutine>& waiter,
const std::string_view initialData,
@@ -194,41 +194,41 @@ public:
[[nodiscard]] HRESULT ReadConsoleOutputAttributeImpl(const SCREEN_INFORMATION& context,
const til::point origin,
gsl::span<WORD> buffer,
std::span<WORD> buffer,
size_t& written) noexcept override;
[[nodiscard]] HRESULT ReadConsoleOutputCharacterAImpl(const SCREEN_INFORMATION& context,
const til::point origin,
gsl::span<char> buffer,
std::span<char> buffer,
size_t& written) noexcept override;
[[nodiscard]] HRESULT ReadConsoleOutputCharacterWImpl(const SCREEN_INFORMATION& context,
const til::point origin,
gsl::span<wchar_t> buffer,
std::span<wchar_t> buffer,
size_t& written) noexcept override;
[[nodiscard]] HRESULT WriteConsoleInputAImpl(InputBuffer& context,
const gsl::span<const INPUT_RECORD> buffer,
const std::span<const INPUT_RECORD> buffer,
size_t& written,
const bool append) noexcept override;
[[nodiscard]] HRESULT WriteConsoleInputWImpl(InputBuffer& context,
const gsl::span<const INPUT_RECORD> buffer,
const std::span<const INPUT_RECORD> buffer,
size_t& written,
const bool append) noexcept override;
[[nodiscard]] HRESULT WriteConsoleOutputAImpl(SCREEN_INFORMATION& context,
gsl::span<CHAR_INFO> buffer,
std::span<CHAR_INFO> buffer,
const Microsoft::Console::Types::Viewport& requestRectangle,
Microsoft::Console::Types::Viewport& writtenRectangle) noexcept override;
[[nodiscard]] HRESULT WriteConsoleOutputWImpl(SCREEN_INFORMATION& context,
gsl::span<CHAR_INFO> buffer,
std::span<CHAR_INFO> buffer,
const Microsoft::Console::Types::Viewport& requestRectangle,
Microsoft::Console::Types::Viewport& writtenRectangle) noexcept override;
[[nodiscard]] HRESULT WriteConsoleOutputAttributeImpl(IConsoleOutputObject& OutContext,
const gsl::span<const WORD> attrs,
const std::span<const WORD> attrs,
const til::point target,
size_t& used) noexcept override;
@@ -243,28 +243,28 @@ public:
size_t& used) noexcept override;
[[nodiscard]] HRESULT ReadConsoleOutputAImpl(const SCREEN_INFORMATION& context,
gsl::span<CHAR_INFO> buffer,
std::span<CHAR_INFO> buffer,
const Microsoft::Console::Types::Viewport& sourceRectangle,
Microsoft::Console::Types::Viewport& readRectangle) noexcept override;
[[nodiscard]] HRESULT ReadConsoleOutputWImpl(const SCREEN_INFORMATION& context,
gsl::span<CHAR_INFO> buffer,
std::span<CHAR_INFO> buffer,
const Microsoft::Console::Types::Viewport& sourceRectangle,
Microsoft::Console::Types::Viewport& readRectangle) noexcept override;
[[nodiscard]] HRESULT GetConsoleTitleAImpl(gsl::span<char> title,
[[nodiscard]] HRESULT GetConsoleTitleAImpl(std::span<char> title,
size_t& written,
size_t& needed) noexcept override;
[[nodiscard]] HRESULT GetConsoleTitleWImpl(gsl::span<wchar_t> title,
[[nodiscard]] HRESULT GetConsoleTitleWImpl(std::span<wchar_t> title,
size_t& written,
size_t& needed) noexcept override;
[[nodiscard]] HRESULT GetConsoleOriginalTitleAImpl(gsl::span<char> title,
[[nodiscard]] HRESULT GetConsoleOriginalTitleAImpl(std::span<char> title,
size_t& written,
size_t& needed) noexcept override;
[[nodiscard]] HRESULT GetConsoleOriginalTitleWImpl(gsl::span<wchar_t> title,
[[nodiscard]] HRESULT GetConsoleOriginalTitleWImpl(std::span<wchar_t> title,
size_t& written,
size_t& needed) noexcept override;
@@ -301,12 +301,12 @@ public:
const std::wstring_view exeName) noexcept override;
[[nodiscard]] HRESULT GetConsoleAliasAImpl(const std::string_view source,
gsl::span<char> target,
std::span<char> target,
size_t& written,
const std::string_view exeName) noexcept override;
[[nodiscard]] HRESULT GetConsoleAliasWImpl(const std::wstring_view source,
gsl::span<wchar_t> target,
std::span<wchar_t> target,
size_t& written,
const std::wstring_view exeName) noexcept override;
@@ -321,17 +321,17 @@ public:
[[nodiscard]] HRESULT GetConsoleAliasExesLengthWImpl(size_t& bufferRequired) noexcept override;
[[nodiscard]] HRESULT GetConsoleAliasesAImpl(const std::string_view exeName,
gsl::span<char> alias,
std::span<char> alias,
size_t& written) noexcept override;
[[nodiscard]] HRESULT GetConsoleAliasesWImpl(const std::wstring_view exeName,
gsl::span<wchar_t> alias,
std::span<wchar_t> alias,
size_t& written) noexcept override;
[[nodiscard]] HRESULT GetConsoleAliasExesAImpl(gsl::span<char> aliasExes,
[[nodiscard]] HRESULT GetConsoleAliasExesAImpl(std::span<char> aliasExes,
size_t& written) noexcept override;
[[nodiscard]] HRESULT GetConsoleAliasExesWImpl(gsl::span<wchar_t> aliasExes,
[[nodiscard]] HRESULT GetConsoleAliasExesWImpl(std::span<wchar_t> aliasExes,
size_t& written) noexcept override;
#pragma region CMDext Private API
@@ -353,11 +353,11 @@ public:
size_t& length) noexcept override;
[[nodiscard]] HRESULT GetConsoleCommandHistoryAImpl(const std::string_view exeName,
gsl::span<char> commandHistory,
std::span<char> commandHistory,
size_t& written) noexcept override;
[[nodiscard]] HRESULT GetConsoleCommandHistoryWImpl(const std::wstring_view exeName,
gsl::span<wchar_t> commandHistory,
std::span<wchar_t> commandHistory,
size_t& written) noexcept override;
#pragma endregion

View File

@@ -36,7 +36,7 @@ static til::size calculatePopupSize(const CommandHistory& history)
size_t width = minSize.width;
for (size_t i = 0; i < history.GetNumberOfCommands(); ++i)
{
const auto& historyItem = history.GetNth(gsl::narrow<short>(i));
const auto& historyItem = history.GetNth(til::safe_cast<short>(i));
width = std::max(width, historyItem.size() + padding);
}
if (width > SHRT_MAX)
@@ -45,9 +45,9 @@ static til::size calculatePopupSize(const CommandHistory& history)
}
// calculate height, it can range up to 20 rows
auto height = std::clamp(gsl::narrow<til::CoordType>(history.GetNumberOfCommands()), minSize.height, 20);
auto height = std::clamp(til::safe_cast<til::CoordType>(history.GetNumberOfCommands()), minSize.height, 20);
return { gsl::narrow_cast<til::CoordType>(width), height };
return { til::safe_cast_nothrow<til::CoordType>(width), height };
}
CommandListPopup::CommandListPopup(SCREEN_INFORMATION& screenInfo, const CommandHistory& history) :
@@ -139,7 +139,7 @@ void CommandListPopup::_setBottomIndex()
{
if (_currentCommand < (SHORT)(_history.GetNumberOfCommands() - Height()))
{
_bottomIndex = std::max(_currentCommand, gsl::narrow<SHORT>(Height() - 1));
_bottomIndex = std::max(_currentCommand, til::safe_cast<SHORT>(Height() - 1));
}
else
{
@@ -204,7 +204,7 @@ void CommandListPopup::_setBottomIndex()
{
auto& history = cookedReadData.History();
if (history.GetNumberOfCommands() <= 1 || _currentCommand == gsl::narrow<short>(history.GetNumberOfCommands()) - 1)
if (history.GetNumberOfCommands() <= 1 || _currentCommand == til::safe_cast<short>(history.GetNumberOfCommands()) - 1)
{
return STATUS_SUCCESS;
}
@@ -345,7 +345,7 @@ void CommandListPopup::_drawList()
auto api = Microsoft::Console::Interactivity::ServiceLocator::LocateGlobals().api;
WriteCoord.y = _region.top + 1;
auto i = gsl::narrow<SHORT>(std::max(_bottomIndex - Height() + 1, 0));
auto i = til::safe_cast<SHORT>(std::max(_bottomIndex - Height() + 1, 0));
for (; i <= _bottomIndex; i++)
{
CHAR CommandNumber[COMMAND_NUMBER_SIZE];
@@ -415,7 +415,7 @@ void CommandListPopup::_drawList()
}
}
WriteCoord.x = gsl::narrow<til::CoordType>(WriteCoord.x + CommandNumberLength);
WriteCoord.x = til::safe_cast<til::CoordType>(WriteCoord.x + CommandNumberLength);
size_t used;
LOG_IF_FAILED(api->WriteConsoleOutputCharacterWImpl(_screenInfo,
{ command.data(), lStringLength },
@@ -466,9 +466,9 @@ void CommandListPopup::_update(const SHORT originalDelta, const bool wrap)
}
else
{
if (NewCmdNum >= gsl::narrow<SHORT>(_history.GetNumberOfCommands()))
if (NewCmdNum >= til::safe_cast<SHORT>(_history.GetNumberOfCommands()))
{
NewCmdNum = gsl::narrow<SHORT>(_history.GetNumberOfCommands()) - 1;
NewCmdNum = til::safe_cast<SHORT>(_history.GetNumberOfCommands()) - 1;
}
else if (NewCmdNum < 0)
{
@@ -484,16 +484,16 @@ void CommandListPopup::_update(const SHORT originalDelta, const bool wrap)
_bottomIndex += delta;
if (_bottomIndex < Size - 1)
{
_bottomIndex = gsl::narrow<SHORT>(Size - 1);
_bottomIndex = til::safe_cast<SHORT>(Size - 1);
}
Scroll = true;
}
else if (NewCmdNum > _bottomIndex)
{
_bottomIndex += delta;
if (_bottomIndex >= gsl::narrow<SHORT>(_history.GetNumberOfCommands()))
if (_bottomIndex >= til::safe_cast<SHORT>(_history.GetNumberOfCommands()))
{
_bottomIndex = gsl::narrow<SHORT>(_history.GetNumberOfCommands()) - 1;
_bottomIndex = til::safe_cast<SHORT>(_history.GetNumberOfCommands()) - 1;
}
Scroll = true;
}

View File

@@ -101,8 +101,8 @@ void CommandNumberPopup::_handleEscape(COOKED_READ_DATA& cookedReadData) noexcep
// - cookedReadData - read data to operate on
void CommandNumberPopup::_handleReturn(COOKED_READ_DATA& cookedReadData) noexcept
{
const auto commandNumber = gsl::narrow<short>(std::min(static_cast<size_t>(_parse()),
cookedReadData.History().GetNumberOfCommands() - 1));
const auto commandNumber = til::safe_cast<short>(std::min(static_cast<size_t>(_parse()),
cookedReadData.History().GetNumberOfCommands() - 1));
CommandLine::Instance().EndAllPopups();
SetCurrentCommandLine(cookedReadData, commandNumber);

View File

@@ -49,7 +49,7 @@ CopyFromCharPopup::CopyFromCharPopup(SCREEN_INFORMATION& screenInfo) :
{
// char was found, delete everything between the cursor and it
const auto difference = std::distance(span.begin(), foundLocation);
for (unsigned int i = 0; i < gsl::narrow<unsigned int>(difference); ++i)
for (unsigned int i = 0; i < til::safe_cast<unsigned int>(difference); ++i)
{
CommandLine::Instance().DeleteFromRightOfCursor(cookedReadData);
}

View File

@@ -42,7 +42,7 @@ void CopyToCharPopup::_copyToChar(COOKED_READ_DATA& cookedReadData, const std::w
const auto startIt = std::next(LastCommand.cbegin(), cookedReadData.InsertionPoint());
const auto endIt = location;
cookedReadData.Write({ &*startIt, gsl::narrow<size_t>(std::distance(startIt, endIt)) });
cookedReadData.Write({ &*startIt, til::safe_cast<size_t>(std::distance(startIt, endIt)) });
}
// Routine Description:

View File

@@ -150,7 +150,7 @@ void VtApiRoutines::_SynchronizeCursor(std::unique_ptr<IWaitRoutine>& waiter) no
}
[[nodiscard]] HRESULT VtApiRoutines::ReadConsoleAImpl(IConsoleInputObject& context,
gsl::span<char> buffer,
std::span<char> buffer,
size_t& written,
std::unique_ptr<IWaitRoutine>& waiter,
const std::string_view initialData,
@@ -174,7 +174,7 @@ void VtApiRoutines::_SynchronizeCursor(std::unique_ptr<IWaitRoutine>& waiter) no
}
[[nodiscard]] HRESULT VtApiRoutines::ReadConsoleWImpl(IConsoleInputObject& context,
gsl::span<char> buffer,
std::span<char> buffer,
size_t& written,
std::unique_ptr<IWaitRoutine>& waiter,
const std::string_view initialData,
@@ -433,7 +433,7 @@ void VtApiRoutines::GetLargestConsoleWindowSizeImpl(const SCREEN_INFORMATION& co
[[nodiscard]] HRESULT VtApiRoutines::ReadConsoleOutputAttributeImpl(const SCREEN_INFORMATION& context,
const til::point origin,
gsl::span<WORD> buffer,
std::span<WORD> buffer,
size_t& written) noexcept
{
std::fill_n(buffer.data(), buffer.size(), s_readBackUnicode.Attributes); // should be same as the ascii one.
@@ -443,7 +443,7 @@ void VtApiRoutines::GetLargestConsoleWindowSizeImpl(const SCREEN_INFORMATION& co
[[nodiscard]] HRESULT VtApiRoutines::ReadConsoleOutputCharacterAImpl(const SCREEN_INFORMATION& context,
const til::point origin,
gsl::span<char> buffer,
std::span<char> buffer,
size_t& written) noexcept
{
std::fill_n(buffer.data(), buffer.size(), s_readBackAscii.Char.AsciiChar);
@@ -453,7 +453,7 @@ void VtApiRoutines::GetLargestConsoleWindowSizeImpl(const SCREEN_INFORMATION& co
[[nodiscard]] HRESULT VtApiRoutines::ReadConsoleOutputCharacterWImpl(const SCREEN_INFORMATION& context,
const til::point origin,
gsl::span<wchar_t> buffer,
std::span<wchar_t> buffer,
size_t& written) noexcept
{
std::fill_n(buffer.data(), buffer.size(), s_readBackUnicode.Char.UnicodeChar);
@@ -462,7 +462,7 @@ void VtApiRoutines::GetLargestConsoleWindowSizeImpl(const SCREEN_INFORMATION& co
}
[[nodiscard]] HRESULT VtApiRoutines::WriteConsoleInputAImpl(InputBuffer& context,
const gsl::span<const INPUT_RECORD> buffer,
const std::span<const INPUT_RECORD> buffer,
size_t& written,
const bool append) noexcept
{
@@ -470,7 +470,7 @@ void VtApiRoutines::GetLargestConsoleWindowSizeImpl(const SCREEN_INFORMATION& co
}
[[nodiscard]] HRESULT VtApiRoutines::WriteConsoleInputWImpl(InputBuffer& context,
const gsl::span<const INPUT_RECORD> buffer,
const std::span<const INPUT_RECORD> buffer,
size_t& written,
const bool append) noexcept
{
@@ -478,11 +478,11 @@ void VtApiRoutines::GetLargestConsoleWindowSizeImpl(const SCREEN_INFORMATION& co
}
extern HRESULT _ConvertCellsToWInplace(const UINT codepage,
gsl::span<CHAR_INFO> buffer,
std::span<CHAR_INFO> buffer,
const Viewport& rectangle) noexcept;
[[nodiscard]] HRESULT VtApiRoutines::WriteConsoleOutputAImpl(SCREEN_INFORMATION& context,
gsl::span<CHAR_INFO> buffer,
std::span<CHAR_INFO> buffer,
const Microsoft::Console::Types::Viewport& requestRectangle,
Microsoft::Console::Types::Viewport& writtenRectangle) noexcept
{
@@ -494,7 +494,7 @@ extern HRESULT _ConvertCellsToWInplace(const UINT codepage,
}
[[nodiscard]] HRESULT VtApiRoutines::WriteConsoleOutputWImpl(SCREEN_INFORMATION& context,
gsl::span<CHAR_INFO> buffer,
std::span<CHAR_INFO> buffer,
const Microsoft::Console::Types::Viewport& requestRectangle,
Microsoft::Console::Types::Viewport& writtenRectangle) noexcept
{
@@ -528,7 +528,7 @@ extern HRESULT _ConvertCellsToWInplace(const UINT codepage,
}
[[nodiscard]] HRESULT VtApiRoutines::WriteConsoleOutputAttributeImpl(IConsoleOutputObject& OutContext,
const gsl::span<const WORD> attrs,
const std::span<const WORD> attrs,
const til::point target,
size_t& used) noexcept
{
@@ -577,7 +577,7 @@ extern HRESULT _ConvertCellsToWInplace(const UINT codepage,
}
[[nodiscard]] HRESULT VtApiRoutines::ReadConsoleOutputAImpl(const SCREEN_INFORMATION& context,
gsl::span<CHAR_INFO> buffer,
std::span<CHAR_INFO> buffer,
const Microsoft::Console::Types::Viewport& sourceRectangle,
Microsoft::Console::Types::Viewport& readRectangle) noexcept
{
@@ -587,7 +587,7 @@ extern HRESULT _ConvertCellsToWInplace(const UINT codepage,
}
[[nodiscard]] HRESULT VtApiRoutines::ReadConsoleOutputWImpl(const SCREEN_INFORMATION& context,
gsl::span<CHAR_INFO> buffer,
std::span<CHAR_INFO> buffer,
const Microsoft::Console::Types::Viewport& sourceRectangle,
Microsoft::Console::Types::Viewport& readRectangle) noexcept
{
@@ -596,7 +596,7 @@ extern HRESULT _ConvertCellsToWInplace(const UINT codepage,
return S_OK;
}
[[nodiscard]] HRESULT VtApiRoutines::GetConsoleTitleAImpl(gsl::span<char> title,
[[nodiscard]] HRESULT VtApiRoutines::GetConsoleTitleAImpl(std::span<char> title,
size_t& written,
size_t& needed) noexcept
{
@@ -611,7 +611,7 @@ extern HRESULT _ConvertCellsToWInplace(const UINT codepage,
return S_OK;
}
[[nodiscard]] HRESULT VtApiRoutines::GetConsoleTitleWImpl(gsl::span<wchar_t> title,
[[nodiscard]] HRESULT VtApiRoutines::GetConsoleTitleWImpl(std::span<wchar_t> title,
size_t& written,
size_t& needed) noexcept
{
@@ -626,7 +626,7 @@ extern HRESULT _ConvertCellsToWInplace(const UINT codepage,
return S_OK;
}
[[nodiscard]] HRESULT VtApiRoutines::GetConsoleOriginalTitleAImpl(gsl::span<char> title,
[[nodiscard]] HRESULT VtApiRoutines::GetConsoleOriginalTitleAImpl(std::span<char> title,
size_t& written,
size_t& needed) noexcept
{
@@ -641,7 +641,7 @@ extern HRESULT _ConvertCellsToWInplace(const UINT codepage,
return S_OK;
}
[[nodiscard]] HRESULT VtApiRoutines::GetConsoleOriginalTitleWImpl(gsl::span<wchar_t> title,
[[nodiscard]] HRESULT VtApiRoutines::GetConsoleOriginalTitleWImpl(std::span<wchar_t> title,
size_t& written,
size_t& needed) noexcept
{
@@ -719,7 +719,7 @@ void VtApiRoutines::GetConsoleDisplayModeImpl(ULONG& flags) noexcept
}
[[nodiscard]] HRESULT VtApiRoutines::GetConsoleAliasAImpl(const std::string_view source,
gsl::span<char> target,
std::span<char> target,
size_t& written,
const std::string_view exeName) noexcept
{
@@ -727,7 +727,7 @@ void VtApiRoutines::GetConsoleDisplayModeImpl(ULONG& flags) noexcept
}
[[nodiscard]] HRESULT VtApiRoutines::GetConsoleAliasWImpl(const std::wstring_view source,
gsl::span<wchar_t> target,
std::span<wchar_t> target,
size_t& written,
const std::wstring_view exeName) noexcept
{
@@ -757,26 +757,26 @@ void VtApiRoutines::GetConsoleDisplayModeImpl(ULONG& flags) noexcept
}
[[nodiscard]] HRESULT VtApiRoutines::GetConsoleAliasesAImpl(const std::string_view exeName,
gsl::span<char> alias,
std::span<char> alias,
size_t& written) noexcept
{
return m_pUsualRoutines->GetConsoleAliasesAImpl(exeName, alias, written);
}
[[nodiscard]] HRESULT VtApiRoutines::GetConsoleAliasesWImpl(const std::wstring_view exeName,
gsl::span<wchar_t> alias,
std::span<wchar_t> alias,
size_t& written) noexcept
{
return m_pUsualRoutines->GetConsoleAliasesWImpl(exeName, alias, written);
}
[[nodiscard]] HRESULT VtApiRoutines::GetConsoleAliasExesAImpl(gsl::span<char> aliasExes,
[[nodiscard]] HRESULT VtApiRoutines::GetConsoleAliasExesAImpl(std::span<char> aliasExes,
size_t& written) noexcept
{
return m_pUsualRoutines->GetConsoleAliasExesAImpl(aliasExes, written);
}
[[nodiscard]] HRESULT VtApiRoutines::GetConsoleAliasExesWImpl(gsl::span<wchar_t> aliasExes,
[[nodiscard]] HRESULT VtApiRoutines::GetConsoleAliasExesWImpl(std::span<wchar_t> aliasExes,
size_t& written) noexcept
{
return m_pUsualRoutines->GetConsoleAliasExesWImpl(aliasExes, written);
@@ -817,14 +817,14 @@ void VtApiRoutines::GetConsoleDisplayModeImpl(ULONG& flags) noexcept
}
[[nodiscard]] HRESULT VtApiRoutines::GetConsoleCommandHistoryAImpl(const std::string_view exeName,
gsl::span<char> commandHistory,
std::span<char> commandHistory,
size_t& written) noexcept
{
return m_pUsualRoutines->GetConsoleCommandHistoryAImpl(exeName, commandHistory, written);
}
[[nodiscard]] HRESULT VtApiRoutines::GetConsoleCommandHistoryWImpl(const std::wstring_view exeName,
gsl::span<wchar_t> commandHistory,
std::span<wchar_t> commandHistory,
size_t& written) noexcept
{
return m_pUsualRoutines->GetConsoleCommandHistoryWImpl(exeName, commandHistory, written);

View File

@@ -77,7 +77,7 @@ public:
std::unique_ptr<IWaitRoutine>& waiter) noexcept override;
[[nodiscard]] HRESULT ReadConsoleAImpl(IConsoleInputObject& context,
gsl::span<char> buffer,
std::span<char> buffer,
size_t& written,
std::unique_ptr<IWaitRoutine>& waiter,
const std::string_view initialData,
@@ -88,7 +88,7 @@ public:
DWORD& controlKeyState) noexcept override;
[[nodiscard]] HRESULT ReadConsoleWImpl(IConsoleInputObject& context,
gsl::span<char> buffer,
std::span<char> buffer,
size_t& written,
std::unique_ptr<IWaitRoutine>& waiter,
const std::string_view initialData,
@@ -197,41 +197,41 @@ public:
[[nodiscard]] HRESULT ReadConsoleOutputAttributeImpl(const SCREEN_INFORMATION& context,
const til::point origin,
gsl::span<WORD> buffer,
std::span<WORD> buffer,
size_t& written) noexcept override;
[[nodiscard]] HRESULT ReadConsoleOutputCharacterAImpl(const SCREEN_INFORMATION& context,
const til::point origin,
gsl::span<char> buffer,
std::span<char> buffer,
size_t& written) noexcept override;
[[nodiscard]] HRESULT ReadConsoleOutputCharacterWImpl(const SCREEN_INFORMATION& context,
const til::point origin,
gsl::span<wchar_t> buffer,
std::span<wchar_t> buffer,
size_t& written) noexcept override;
[[nodiscard]] HRESULT WriteConsoleInputAImpl(InputBuffer& context,
const gsl::span<const INPUT_RECORD> buffer,
const std::span<const INPUT_RECORD> buffer,
size_t& written,
const bool append) noexcept override;
[[nodiscard]] HRESULT WriteConsoleInputWImpl(InputBuffer& context,
const gsl::span<const INPUT_RECORD> buffer,
const std::span<const INPUT_RECORD> buffer,
size_t& written,
const bool append) noexcept override;
[[nodiscard]] HRESULT WriteConsoleOutputAImpl(SCREEN_INFORMATION& context,
gsl::span<CHAR_INFO> buffer,
std::span<CHAR_INFO> buffer,
const Microsoft::Console::Types::Viewport& requestRectangle,
Microsoft::Console::Types::Viewport& writtenRectangle) noexcept override;
[[nodiscard]] HRESULT WriteConsoleOutputWImpl(SCREEN_INFORMATION& context,
gsl::span<CHAR_INFO> buffer,
std::span<CHAR_INFO> buffer,
const Microsoft::Console::Types::Viewport& requestRectangle,
Microsoft::Console::Types::Viewport& writtenRectangle) noexcept override;
[[nodiscard]] HRESULT WriteConsoleOutputAttributeImpl(IConsoleOutputObject& OutContext,
const gsl::span<const WORD> attrs,
const std::span<const WORD> attrs,
const til::point target,
size_t& used) noexcept override;
@@ -246,28 +246,28 @@ public:
size_t& used) noexcept override;
[[nodiscard]] HRESULT ReadConsoleOutputAImpl(const SCREEN_INFORMATION& context,
gsl::span<CHAR_INFO> buffer,
std::span<CHAR_INFO> buffer,
const Microsoft::Console::Types::Viewport& sourceRectangle,
Microsoft::Console::Types::Viewport& readRectangle) noexcept override;
[[nodiscard]] HRESULT ReadConsoleOutputWImpl(const SCREEN_INFORMATION& context,
gsl::span<CHAR_INFO> buffer,
std::span<CHAR_INFO> buffer,
const Microsoft::Console::Types::Viewport& sourceRectangle,
Microsoft::Console::Types::Viewport& readRectangle) noexcept override;
[[nodiscard]] HRESULT GetConsoleTitleAImpl(gsl::span<char> title,
[[nodiscard]] HRESULT GetConsoleTitleAImpl(std::span<char> title,
size_t& written,
size_t& needed) noexcept override;
[[nodiscard]] HRESULT GetConsoleTitleWImpl(gsl::span<wchar_t> title,
[[nodiscard]] HRESULT GetConsoleTitleWImpl(std::span<wchar_t> title,
size_t& written,
size_t& needed) noexcept override;
[[nodiscard]] HRESULT GetConsoleOriginalTitleAImpl(gsl::span<char> title,
[[nodiscard]] HRESULT GetConsoleOriginalTitleAImpl(std::span<char> title,
size_t& written,
size_t& needed) noexcept override;
[[nodiscard]] HRESULT GetConsoleOriginalTitleWImpl(gsl::span<wchar_t> title,
[[nodiscard]] HRESULT GetConsoleOriginalTitleWImpl(std::span<wchar_t> title,
size_t& written,
size_t& needed) noexcept override;
@@ -304,12 +304,12 @@ public:
const std::wstring_view exeName) noexcept override;
[[nodiscard]] HRESULT GetConsoleAliasAImpl(const std::string_view source,
gsl::span<char> target,
std::span<char> target,
size_t& written,
const std::string_view exeName) noexcept override;
[[nodiscard]] HRESULT GetConsoleAliasWImpl(const std::wstring_view source,
gsl::span<wchar_t> target,
std::span<wchar_t> target,
size_t& written,
const std::wstring_view exeName) noexcept override;
@@ -324,17 +324,17 @@ public:
[[nodiscard]] HRESULT GetConsoleAliasExesLengthWImpl(size_t& bufferRequired) noexcept override;
[[nodiscard]] HRESULT GetConsoleAliasesAImpl(const std::string_view exeName,
gsl::span<char> alias,
std::span<char> alias,
size_t& written) noexcept override;
[[nodiscard]] HRESULT GetConsoleAliasesWImpl(const std::wstring_view exeName,
gsl::span<wchar_t> alias,
std::span<wchar_t> alias,
size_t& written) noexcept override;
[[nodiscard]] HRESULT GetConsoleAliasExesAImpl(gsl::span<char> aliasExes,
[[nodiscard]] HRESULT GetConsoleAliasExesAImpl(std::span<char> aliasExes,
size_t& written) noexcept override;
[[nodiscard]] HRESULT GetConsoleAliasExesWImpl(gsl::span<wchar_t> aliasExes,
[[nodiscard]] HRESULT GetConsoleAliasExesWImpl(std::span<wchar_t> aliasExes,
size_t& written) noexcept override;
#pragma region CMDext Private API
@@ -356,11 +356,11 @@ public:
size_t& length) noexcept override;
[[nodiscard]] HRESULT GetConsoleCommandHistoryAImpl(const std::string_view exeName,
gsl::span<char> commandHistory,
std::span<char> commandHistory,
size_t& written) noexcept override;
[[nodiscard]] HRESULT GetConsoleCommandHistoryWImpl(const std::wstring_view exeName,
gsl::span<wchar_t> commandHistory,
std::span<wchar_t> commandHistory,
size_t& written) noexcept override;
#pragma endregion

View File

@@ -117,7 +117,7 @@ void VtInputThread::DoReadInput(const bool throwOnFail)
return;
}
auto hr = _HandleRunInput({ buffer, gsl::narrow_cast<size_t>(dwRead) });
auto hr = _HandleRunInput({ buffer, til::safe_cast_nothrow<size_t>(dwRead) });
if (FAILED(hr))
{
if (throwOnFail)

View File

@@ -66,7 +66,7 @@ void WriteToScreen(SCREEN_INFORMATION& screenInfo, const Viewport& region)
// Return Value:
// - S_OK, E_INVALIDARG or similar HRESULT error.
[[nodiscard]] HRESULT ApiRoutines::WriteConsoleOutputAttributeImpl(IConsoleOutputObject& OutContext,
const gsl::span<const WORD> attrs,
const std::span<const WORD> attrs,
const til::point target,
size_t& used) noexcept
{

View File

@@ -725,7 +725,7 @@ using Microsoft::Console::VirtualTerminal::StateMachine;
if (CheckBisectProcessW(screenInfo,
pwchBufferBackupLimit,
pwchBuffer + 1 - pwchBufferBackupLimit,
gsl::narrow_cast<size_t>(coordScreenBufferSize.width) - sOriginalXPosition,
til::safe_cast_nothrow<size_t>(coordScreenBufferSize.width) - sOriginalXPosition,
sOriginalXPosition,
dwFlags & WC_PRINTABLE_CONTROL_CHARS))
{
@@ -765,7 +765,7 @@ using Microsoft::Console::VirtualTerminal::StateMachine;
size_t NumChars = 0;
if (CursorPosition.x >= coordScreenBufferSize.width)
{
NumChars = gsl::narrow<size_t>(coordScreenBufferSize.width - cursor.GetPosition().x);
NumChars = til::safe_cast<size_t>(coordScreenBufferSize.width - cursor.GetPosition().x);
CursorPosition.x = 0;
CursorPosition.y = cursor.GetPosition().y + 1;
@@ -774,7 +774,7 @@ using Microsoft::Console::VirtualTerminal::StateMachine;
}
else
{
NumChars = gsl::narrow<size_t>(CursorPosition.x - cursor.GetPosition().x);
NumChars = til::safe_cast<size_t>(CursorPosition.x - cursor.GetPosition().x);
CursorPosition.y = cursor.GetPosition().y;
}
@@ -1144,12 +1144,12 @@ using Microsoft::Console::VirtualTerminal::StateMachine;
auto wcPtr{ wstr.data() };
auto mbPtr{ buffer.data() };
size_t dbcsLength{};
if (screenInfo.WriteConsoleDbcsLeadByte[0] != 0 && gsl::narrow_cast<byte>(*mbPtr) >= byte{ ' ' })
if (screenInfo.WriteConsoleDbcsLeadByte[0] != 0 && til::safe_cast_nothrow<byte>(*mbPtr) >= byte{ ' ' })
{
// there was a portion of a dbcs character stored from a previous
// call so we take the 2nd half from mbPtr[0], put them together
// and write the wide char to wcPtr[0]
screenInfo.WriteConsoleDbcsLeadByte[1] = gsl::narrow_cast<byte>(*mbPtr);
screenInfo.WriteConsoleDbcsLeadByte[1] = til::safe_cast_nothrow<byte>(*mbPtr);
try
{
@@ -1185,7 +1185,7 @@ using Microsoft::Console::VirtualTerminal::StateMachine;
// back together then
if (mbPtrLength != 0 && CheckBisectStringA(const_cast<char*>(mbPtr), mbPtrLength, &consoleInfo.OutputCPInfo))
{
screenInfo.WriteConsoleDbcsLeadByte[0] = gsl::narrow_cast<byte>(mbPtr[mbPtrLength - 1]);
screenInfo.WriteConsoleDbcsLeadByte[0] = til::safe_cast_nothrow<byte>(mbPtr[mbPtrLength - 1]);
mbPtrLength--;
// Note that we captured a lead byte during this call, but won't actually draw it until later.

View File

@@ -137,7 +137,7 @@ std::unordered_map<std::wstring,
// Return Value:
// - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors.
[[nodiscard]] HRESULT GetConsoleAliasWImplHelper(const std::wstring_view source,
std::optional<gsl::span<wchar_t>> target,
std::optional<std::span<wchar_t>> target,
size_t& writtenOrNeeded,
const std::wstring_view exeName)
{
@@ -195,7 +195,7 @@ std::unordered_map<std::wstring,
// Return Value:
// - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors.
[[nodiscard]] HRESULT ApiRoutines::GetConsoleAliasAImpl(const std::string_view source,
gsl::span<char> target,
std::span<char> target,
size_t& written,
const std::string_view exeName) noexcept
{
@@ -235,7 +235,7 @@ std::unordered_map<std::wstring,
// Call the Unicode version of this method
size_t targetWritten;
RETURN_IF_FAILED(GetConsoleAliasWImplHelper(sourceW,
gsl::span<wchar_t>(targetBuffer.get(), targetNeeded),
std::span<wchar_t>(targetBuffer.get(), targetNeeded),
targetWritten,
exeNameW));
@@ -268,7 +268,7 @@ std::unordered_map<std::wstring,
// Return Value:
// - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors.
[[nodiscard]] HRESULT ApiRoutines::GetConsoleAliasWImpl(const std::wstring_view source,
gsl::span<wchar_t> target,
std::span<wchar_t> target,
size_t& written,
const std::wstring_view exeName) noexcept
{
@@ -440,7 +440,7 @@ void Alias::s_ClearCmdExeAliases()
// Return Value:
// - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors.
[[nodiscard]] HRESULT GetConsoleAliasesWImplHelper(const std::wstring_view exeName,
std::optional<gsl::span<wchar_t>> aliasBuffer,
std::optional<std::span<wchar_t>> aliasBuffer,
size_t& writtenOrNeeded)
{
// Ensure output variables are initialized.
@@ -527,7 +527,7 @@ void Alias::s_ClearCmdExeAliases()
// Return Value:
// - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors.
[[nodiscard]] HRESULT ApiRoutines::GetConsoleAliasesAImpl(const std::string_view exeName,
gsl::span<char> alias,
std::span<char> alias,
size_t& written) noexcept
{
const auto& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
@@ -563,7 +563,7 @@ void Alias::s_ClearCmdExeAliases()
// Call the Unicode version of this method
size_t bufferWritten;
RETURN_IF_FAILED(GetConsoleAliasesWImplHelper(exeNameW, gsl::span<wchar_t>(aliasBuffer.get(), bufferNeeded), bufferWritten));
RETURN_IF_FAILED(GetConsoleAliasesWImplHelper(exeNameW, std::span<wchar_t>(aliasBuffer.get(), bufferNeeded), bufferWritten));
// Convert result to A
const auto converted = ConvertToA(codepage, { aliasBuffer.get(), bufferWritten });
@@ -591,7 +591,7 @@ void Alias::s_ClearCmdExeAliases()
// Return Value:
// - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors.
[[nodiscard]] HRESULT ApiRoutines::GetConsoleAliasesWImpl(const std::wstring_view exeName,
gsl::span<wchar_t> alias,
std::span<wchar_t> alias,
size_t& written) noexcept
{
LockConsole();
@@ -688,7 +688,7 @@ void Alias::s_ClearCmdExeAliases()
// or how many characters would have been needed (if buffer is nullopt).
// Return Value:
// - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors.
[[nodiscard]] HRESULT GetConsoleAliasExesWImplHelper(std::optional<gsl::span<wchar_t>> aliasExesBuffer,
[[nodiscard]] HRESULT GetConsoleAliasExesWImplHelper(std::optional<std::span<wchar_t>> aliasExesBuffer,
size_t& writtenOrNeeded)
{
// Ensure output variables are initialized.
@@ -745,7 +745,7 @@ void Alias::s_ClearCmdExeAliases()
// - written - Specifies how many characters were written
// Return Value:
// - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors.
[[nodiscard]] HRESULT ApiRoutines::GetConsoleAliasExesAImpl(gsl::span<char> aliasExes,
[[nodiscard]] HRESULT ApiRoutines::GetConsoleAliasExesAImpl(std::span<char> aliasExes,
size_t& written) noexcept
{
const auto& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
@@ -777,7 +777,7 @@ void Alias::s_ClearCmdExeAliases()
// Call the Unicode version of this method
size_t bufferWritten;
RETURN_IF_FAILED(GetConsoleAliasExesWImplHelper(gsl::span<wchar_t>(targetBuffer.get(), bufferNeeded), bufferWritten));
RETURN_IF_FAILED(GetConsoleAliasExesWImplHelper(std::span<wchar_t>(targetBuffer.get(), bufferNeeded), bufferWritten));
// Convert result to A
const auto converted = ConvertToA(codepage, { targetBuffer.get(), bufferWritten });
@@ -804,7 +804,7 @@ void Alias::s_ClearCmdExeAliases()
// - pcchAliasExesBufferWrittenOrNeeded - Pointer to space that will specify how many characters were written
// Return Value:
// - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors.
[[nodiscard]] HRESULT ApiRoutines::GetConsoleAliasExesWImpl(gsl::span<wchar_t> aliasExes,
[[nodiscard]] HRESULT ApiRoutines::GetConsoleAliasExesWImpl(std::span<wchar_t> aliasExes,
size_t& written) noexcept
{
LockConsole();
@@ -1225,10 +1225,10 @@ void Alias::s_MatchAndCopyAliasLegacy(_In_reads_bytes_(cbSource) PCWCH pwchSourc
std::copy_n(targetText.data(), targetText.size(), pwchTarget);
// Return bytes copied.
cbTargetWritten = gsl::narrow<ULONG>(targetText.size() * sizeof(wchar_t));
cbTargetWritten = til::safe_cast<ULONG>(targetText.size() * sizeof(wchar_t));
// Return lines info.
lines = gsl::narrow<DWORD>(lineCount);
lines = til::safe_cast<DWORD>(lineCount);
}
}
}

View File

@@ -598,7 +598,7 @@ til::point CommandLine::_moveCursorToEndOfPrompt(COOKED_READ_DATA& cookedReadDat
cookedReadData.InsertionPoint() = cookedReadData.BytesRead() / sizeof(WCHAR);
cookedReadData.SetBufferCurrentPtr(cookedReadData.BufferStartPtr() + cookedReadData.InsertionPoint());
til::point cursorPosition;
cursorPosition.x = gsl::narrow<til::CoordType>(cookedReadData.OriginalCursorPosition().x + cookedReadData.VisibleCharCount());
cursorPosition.x = til::safe_cast<til::CoordType>(cookedReadData.OriginalCursorPosition().x + cookedReadData.VisibleCharCount());
cursorPosition.y = cookedReadData.OriginalCursorPosition().y;
const auto sScreenBufferSizeX = cookedReadData.ScreenInfo().GetBufferSize().Width();

View File

@@ -110,7 +110,7 @@ void ConversionAreaInfo::SetAttributes(const TextAttribute& attr)
void ConversionAreaInfo::WriteText(const std::vector<OutputCell>& text,
const til::CoordType column)
{
gsl::span<const OutputCell> view(text.data(), text.size());
std::span<const OutputCell> view(text.data(), text.size());
_screenBuffer->Write(view, { column, 0 });
}

View File

@@ -57,8 +57,8 @@ void ConsoleImeInfo::RedrawCompMessage()
// - attributes - Encoded attributes including the cursor position and the color index (to the array)
// - colorArray - An array of colors to use for the text
void ConsoleImeInfo::WriteCompMessage(const std::wstring_view text,
const gsl::span<const BYTE> attributes,
const gsl::span<const WORD> colorArray)
const std::span<const BYTE> attributes,
const std::span<const WORD> colorArray)
{
ClearAllAreas();
@@ -181,8 +181,8 @@ void ConsoleImeInfo::ClearAllAreas()
// Return Value:
// - TextAttribute object with color and cursor and line drawing data.
TextAttribute ConsoleImeInfo::s_RetrieveAttributeAt(const size_t pos,
const gsl::span<const BYTE> attributes,
const gsl::span<const WORD> colorArray)
const std::span<const BYTE> attributes,
const std::span<const WORD> colorArray)
{
// Encoded attribute is the shorthand information passed from the IME
// that contains a cursor position packed in along with which color in the
@@ -218,8 +218,8 @@ TextAttribute ConsoleImeInfo::s_RetrieveAttributeAt(const size_t pos,
// Return Value:
// - Vector of OutputCells where each one represents one cell of the output buffer.
std::vector<OutputCell> ConsoleImeInfo::s_ConvertToCells(const std::wstring_view text,
const gsl::span<const BYTE> attributes,
const gsl::span<const WORD> colorArray)
const std::span<const BYTE> attributes,
const std::span<const WORD> colorArray)
{
std::vector<OutputCell> cells;
@@ -369,7 +369,7 @@ std::vector<OutputCell>::const_iterator ConsoleImeInfo::_WriteConversionArea(con
// Set the viewport and positioning parameters for the conversion area to describe to the renderer
// the appropriate location to overlay this conversion area on top of the main screen buffer inside the viewport.
const til::inclusive_rect region{ insertionPos.x, 0, gsl::narrow<til::CoordType>(insertionPos.x + lineVec.size() - 1), 0 };
const til::inclusive_rect region{ insertionPos.x, 0, til::safe_cast<til::CoordType>(insertionPos.x + lineVec.size() - 1), 0 };
area.SetWindowInfo(region);
area.SetViewPos({ 0 - view.Left(), insertionPos.y - view.Top() });
@@ -398,8 +398,8 @@ std::vector<OutputCell>::const_iterator ConsoleImeInfo::_WriteConversionArea(con
// each text character. This view must be the same size as the text view.
// - colorArray - 8 colors to be used to format the text for display
void ConsoleImeInfo::_WriteUndeterminedChars(const std::wstring_view text,
const gsl::span<const BYTE> attributes,
const gsl::span<const WORD> colorArray)
const std::span<const BYTE> attributes,
const std::span<const WORD> colorArray)
{
auto& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
auto& screenInfo = gci.GetActiveOutputBuffer();

View File

@@ -48,8 +48,8 @@ public:
[[nodiscard]] HRESULT ResizeAllAreas(const til::size newSize);
void WriteCompMessage(const std::wstring_view text,
const gsl::span<const BYTE> attributes,
const gsl::span<const WORD> colorArray);
const std::span<const BYTE> attributes,
const std::span<const WORD> colorArray);
void WriteResultMessage(const std::wstring_view text);
@@ -64,18 +64,18 @@ private:
void _ClearComposition();
void _WriteUndeterminedChars(const std::wstring_view text,
const gsl::span<const BYTE> attributes,
const gsl::span<const WORD> colorArray);
const std::span<const BYTE> attributes,
const std::span<const WORD> colorArray);
void _InsertConvertedString(const std::wstring_view text);
static TextAttribute s_RetrieveAttributeAt(const size_t pos,
const gsl::span<const BYTE> attributes,
const gsl::span<const WORD> colorArray);
const std::span<const BYTE> attributes,
const std::span<const WORD> colorArray);
static std::vector<OutputCell> s_ConvertToCells(const std::wstring_view text,
const gsl::span<const BYTE> attributes,
const gsl::span<const WORD> colorArray);
const std::span<const BYTE> attributes,
const std::span<const WORD> colorArray);
std::vector<OutputCell>::const_iterator _WriteConversionArea(const std::vector<OutputCell>::const_iterator begin,
const std::vector<OutputCell>::const_iterator end,

View File

@@ -116,8 +116,8 @@ void WriteConvRegionToScreen(const SCREEN_INFORMATION& ScreenInfo,
}
[[nodiscard]] HRESULT ImeComposeData(std::wstring_view text,
gsl::span<const BYTE> attributes,
gsl::span<const WORD> colorArray)
std::span<const BYTE> attributes,
std::span<const WORD> colorArray)
{
try
{

View File

@@ -55,7 +55,7 @@ bool CheckBisectStringA(_In_reads_bytes_(cbBuf) PCHAR pchBuf, _In_ DWORD cbBuf,
// - buffer - The buffer to walk and fix
// Return Value:
// - The length of the final modified buffer.
DWORD UnicodeRasterFontCellMungeOnRead(const gsl::span<CHAR_INFO> buffer)
DWORD UnicodeRasterFontCellMungeOnRead(const std::span<CHAR_INFO> buffer)
{
// Walk through the source CHAR_INFO and copy each to the destination.
// EXCEPT for trailing bytes (this will de-duplicate the leading/trailing byte double copies of the CHAR_INFOs as stored in the buffer).
@@ -80,7 +80,7 @@ DWORD UnicodeRasterFontCellMungeOnRead(const gsl::span<CHAR_INFO> buffer)
}
// Zero out the remaining part of the destination buffer that we didn't use.
const auto cchDstToClear = gsl::narrow<DWORD>(buffer.size()) - iDst;
const auto cchDstToClear = til::safe_cast<DWORD>(buffer.size()) - iDst;
if (cchDstToClear > 0)
{

View File

@@ -22,7 +22,7 @@ Revision History:
bool CheckBisectStringA(_In_reads_bytes_(cbBuf) PCHAR pchBuf, _In_ DWORD cbBuf, const CPINFO* const pCPInfo);
DWORD UnicodeRasterFontCellMungeOnRead(const gsl::span<CHAR_INFO> buffer);
DWORD UnicodeRasterFontCellMungeOnRead(const std::span<CHAR_INFO> buffer);
bool IsDBCSLeadByteConsole(const CHAR ch, const CPINFO* const pCPInfo);

View File

@@ -452,7 +452,7 @@ void EventsToUnicode(_Inout_ std::deque<std::unique_ptr<IInputEvent>>& inEvents,
// Return Value:
// - HRESULT indicating success or failure
[[nodiscard]] HRESULT ApiRoutines::WriteConsoleInputAImpl(InputBuffer& context,
const gsl::span<const INPUT_RECORD> buffer,
const std::span<const INPUT_RECORD> buffer,
size_t& written,
const bool append) noexcept
{
@@ -496,7 +496,7 @@ void EventsToUnicode(_Inout_ std::deque<std::unique_ptr<IInputEvent>>& inEvents,
// Return Value:
// - HRESULT indicating success or failure
[[nodiscard]] HRESULT ApiRoutines::WriteConsoleInputWImpl(InputBuffer& context,
const gsl::span<const INPUT_RECORD> buffer,
const std::span<const INPUT_RECORD> buffer,
size_t& written,
const bool append) noexcept
{
@@ -524,7 +524,7 @@ void EventsToUnicode(_Inout_ std::deque<std::unique_ptr<IInputEvent>>& inEvents,
// Return Value:
// - Generally S_OK. Could be a memory or math error code.
[[nodiscard]] static HRESULT _ConvertCellsToAInplace(const UINT codepage,
const gsl::span<CHAR_INFO> buffer,
const std::span<CHAR_INFO> buffer,
const Viewport rectangle) noexcept
{
try
@@ -601,7 +601,7 @@ void EventsToUnicode(_Inout_ std::deque<std::unique_ptr<IInputEvent>>& inEvents,
// Return Value:
// - Generally S_OK. Could be a memory or math error code.
[[nodiscard]] HRESULT _ConvertCellsToWInplace(const UINT codepage,
gsl::span<CHAR_INFO> buffer,
std::span<CHAR_INFO> buffer,
const Viewport& rectangle) noexcept
{
try
@@ -671,7 +671,7 @@ void EventsToUnicode(_Inout_ std::deque<std::unique_ptr<IInputEvent>>& inEvents,
CATCH_RETURN();
}
[[nodiscard]] static std::vector<CHAR_INFO> _ConvertCellsToMungedW(gsl::span<CHAR_INFO> buffer, const Viewport& rectangle)
[[nodiscard]] static std::vector<CHAR_INFO> _ConvertCellsToMungedW(std::span<CHAR_INFO> buffer, const Viewport& rectangle)
{
std::vector<CHAR_INFO> result;
result.reserve(buffer.size());
@@ -722,7 +722,7 @@ void EventsToUnicode(_Inout_ std::deque<std::unique_ptr<IInputEvent>>& inEvents,
}
[[nodiscard]] static HRESULT _ReadConsoleOutputWImplHelper(const SCREEN_INFORMATION& context,
gsl::span<CHAR_INFO> targetBuffer,
std::span<CHAR_INFO> targetBuffer,
const Microsoft::Console::Types::Viewport& requestRectangle,
Microsoft::Console::Types::Viewport& readRectangle) noexcept
{
@@ -812,7 +812,7 @@ void EventsToUnicode(_Inout_ std::deque<std::unique_ptr<IInputEvent>>& inEvents,
}
[[nodiscard]] HRESULT ApiRoutines::ReadConsoleOutputAImpl(const SCREEN_INFORMATION& context,
gsl::span<CHAR_INFO> buffer,
std::span<CHAR_INFO> buffer,
const Microsoft::Console::Types::Viewport& sourceRectangle,
Microsoft::Console::Types::Viewport& readRectangle) noexcept
{
@@ -834,7 +834,7 @@ void EventsToUnicode(_Inout_ std::deque<std::unique_ptr<IInputEvent>>& inEvents,
}
[[nodiscard]] HRESULT ApiRoutines::ReadConsoleOutputWImpl(const SCREEN_INFORMATION& context,
gsl::span<CHAR_INFO> buffer,
std::span<CHAR_INFO> buffer,
const Microsoft::Console::Types::Viewport& sourceRectangle,
Microsoft::Console::Types::Viewport& readRectangle) noexcept
{
@@ -858,7 +858,7 @@ void EventsToUnicode(_Inout_ std::deque<std::unique_ptr<IInputEvent>>& inEvents,
}
[[nodiscard]] static HRESULT _WriteConsoleOutputWImplHelper(SCREEN_INFORMATION& context,
gsl::span<CHAR_INFO> buffer,
std::span<CHAR_INFO> buffer,
const Viewport& requestRectangle,
Viewport& writtenRectangle) noexcept
{
@@ -942,7 +942,7 @@ void EventsToUnicode(_Inout_ std::deque<std::unique_ptr<IInputEvent>>& inEvents,
const auto subspan = buffer.subspan(totalOffset, writeRectangle.Width());
// Convert to a CHAR_INFO view to fit into the iterator
const auto charInfos = gsl::span<const CHAR_INFO>(subspan.data(), subspan.size());
const auto charInfos = std::span<const CHAR_INFO>(subspan.data(), subspan.size());
// Make the iterator and write to the target position.
OutputCellIterator it(charInfos);
@@ -958,7 +958,7 @@ void EventsToUnicode(_Inout_ std::deque<std::unique_ptr<IInputEvent>>& inEvents,
}
[[nodiscard]] HRESULT ApiRoutines::WriteConsoleOutputAImpl(SCREEN_INFORMATION& context,
gsl::span<CHAR_INFO> buffer,
std::span<CHAR_INFO> buffer,
const Viewport& requestRectangle,
Viewport& writtenRectangle) noexcept
{
@@ -979,7 +979,7 @@ void EventsToUnicode(_Inout_ std::deque<std::unique_ptr<IInputEvent>>& inEvents,
}
[[nodiscard]] HRESULT ApiRoutines::WriteConsoleOutputWImpl(SCREEN_INFORMATION& context,
gsl::span<CHAR_INFO> buffer,
std::span<CHAR_INFO> buffer,
const Viewport& requestRectangle,
Viewport& writtenRectangle) noexcept
{
@@ -1007,7 +1007,7 @@ void EventsToUnicode(_Inout_ std::deque<std::unique_ptr<IInputEvent>>& inEvents,
[[nodiscard]] HRESULT ApiRoutines::ReadConsoleOutputAttributeImpl(const SCREEN_INFORMATION& context,
const til::point origin,
gsl::span<WORD> buffer,
std::span<WORD> buffer,
size_t& written) noexcept
{
written = 0;
@@ -1028,7 +1028,7 @@ void EventsToUnicode(_Inout_ std::deque<std::unique_ptr<IInputEvent>>& inEvents,
[[nodiscard]] HRESULT ApiRoutines::ReadConsoleOutputCharacterAImpl(const SCREEN_INFORMATION& context,
const til::point origin,
gsl::span<char> buffer,
std::span<char> buffer,
size_t& written) noexcept
{
written = 0;
@@ -1057,7 +1057,7 @@ void EventsToUnicode(_Inout_ std::deque<std::unique_ptr<IInputEvent>>& inEvents,
[[nodiscard]] HRESULT ApiRoutines::ReadConsoleOutputCharacterWImpl(const SCREEN_INFORMATION& context,
const til::point origin,
gsl::span<wchar_t> buffer,
std::span<wchar_t> buffer,
size_t& written) noexcept
{
written = 0;

View File

@@ -194,15 +194,6 @@ static void _releaseNotifier() noexcept
_comServerExitEvent.SetEvent();
}
// This method has the same behavior as gsl::narrow<T>, but instead of throwing an
// exception on narrowing failure it'll return false. On success it returns true.
template<typename T, typename U>
constexpr bool narrow_maybe(U u, T& out) noexcept
{
out = gsl::narrow_cast<T>(u);
return static_cast<U>(out) == u && (std::is_signed_v<T> == std::is_signed_v<U> || (out < T{}) == (u < U{}));
}
// Routine Description:
// - Main entry point for EXE version of console launching.
// This can be used as a debugging/diagnostics tool as well as a method of testing the console without

View File

@@ -85,9 +85,9 @@ struct NullDeviceComm : public IDeviceComm
fakeConnectInfo.ConsoleInfo.SetWindowSize({ 80, 25 });
fakeConnectInfo.ConsoleInfo.SetStartupFlags(STARTF_USECOUNTCHARS);
wcscpy_s(fakeConnectInfo.Title, fakeTitle.data());
fakeConnectInfo.TitleLength = gsl::narrow_cast<DWORD>(fakeTitle.size() * sizeof(wchar_t)); // bytes, not wchars
fakeConnectInfo.TitleLength = til::safe_cast_nothrow<DWORD>(fakeTitle.size() * sizeof(wchar_t)); // bytes, not wchars
wcscpy_s(fakeConnectInfo.AppName, fakeTitle.data());
fakeConnectInfo.AppNameLength = gsl::narrow_cast<DWORD>(fakeTitle.size() * sizeof(wchar_t)); // bytes, not wchars
fakeConnectInfo.AppNameLength = til::safe_cast_nothrow<DWORD>(fakeTitle.size() * sizeof(wchar_t)); // bytes, not wchars
fakeConnectInfo.ConsoleApp = TRUE;
fakeConnectInfo.WindowVisible = TRUE;
RETURN_IF_NTSTATUS_FAILED(ConsoleAllocateConsole(&fakeConnectInfo));

View File

@@ -102,13 +102,13 @@ void BufferTests::TestWritingInactiveScreenBuffer()
Log::Comment(L"Write one line of text to the active/main output buffer.");
DWORD written = 0;
// Ok in legacy mode, ok in modern mode
VERIFY_WIN32_BOOL_SUCCEEDED(WriteConsoleW(out, primary.data(), gsl::narrow<DWORD>(primary.size()), &written, nullptr));
VERIFY_WIN32_BOOL_SUCCEEDED(WriteConsoleW(out, primary.data(), til::safe_cast<DWORD>(primary.size()), &written, nullptr));
VERIFY_ARE_EQUAL(primary.size(), written);
Log::Comment(L"Write a newline character to move the cursor down to the left most cell on the next line down.");
// write a newline too to move the cursor down
written = 0;
VERIFY_WIN32_BOOL_SUCCEEDED(WriteConsoleW(out, newline.data(), gsl::narrow<DWORD>(newline.size()), &written, nullptr));
VERIFY_WIN32_BOOL_SUCCEEDED(WriteConsoleW(out, newline.data(), til::safe_cast<DWORD>(newline.size()), &written, nullptr));
VERIFY_ARE_EQUAL(newline.size(), written);
Log::Comment(L"Create an alternative backing screen buffer that we will NOT be setting as active.");
@@ -118,7 +118,7 @@ void BufferTests::TestWritingInactiveScreenBuffer()
// Ok in legacy mode, NOT ok in modern mode.
Log::Comment(L"Try to write a second line of different text but to the alternative backing screen buffer.");
written = 0;
VERIFY_WIN32_BOOL_SUCCEEDED(WriteConsoleW(handle, alternative.data(), gsl::narrow<DWORD>(alternative.size()), &written, nullptr));
VERIFY_WIN32_BOOL_SUCCEEDED(WriteConsoleW(handle, alternative.data(), til::safe_cast<DWORD>(alternative.size()), &written, nullptr));
VERIFY_ARE_EQUAL(alternative.size(), written);
auto primaryBuffer = std::make_unique<wchar_t[]>(primary.size());
@@ -126,22 +126,22 @@ void BufferTests::TestWritingInactiveScreenBuffer()
Log::Comment(L"Read the first line out of the main/visible screen buffer. It should contain the first thing we wrote.");
DWORD read = 0;
VERIFY_WIN32_BOOL_SUCCEEDED(ReadConsoleOutputCharacterW(out, primaryBuffer.get(), gsl::narrow<DWORD>(primary.size()), { 0, 0 }, &read));
VERIFY_WIN32_BOOL_SUCCEEDED(ReadConsoleOutputCharacterW(out, primaryBuffer.get(), til::safe_cast<DWORD>(primary.size()), { 0, 0 }, &read));
VERIFY_ARE_EQUAL(primary.size(), read);
VERIFY_ARE_EQUAL(String(primary.data()), String(primaryBuffer.get(), gsl::narrow<int>(primary.size())));
VERIFY_ARE_EQUAL(String(primary.data()), String(primaryBuffer.get(), til::safe_cast<int>(primary.size())));
Log::Comment(L"Read the second line out of the main/visible screen buffer. It should be full of blanks. The second thing we wrote wasn't to this buffer so it shouldn't show.");
const std::wstring alternativeExpected(alternative.size(), L'\x20');
read = 0;
VERIFY_WIN32_BOOL_SUCCEEDED(ReadConsoleOutputCharacterW(out, alternativeBuffer.get(), gsl::narrow<DWORD>(alternative.size()), { 0, 1 }, &read));
VERIFY_WIN32_BOOL_SUCCEEDED(ReadConsoleOutputCharacterW(out, alternativeBuffer.get(), til::safe_cast<DWORD>(alternative.size()), { 0, 1 }, &read));
VERIFY_ARE_EQUAL(alternative.size(), read);
VERIFY_ARE_EQUAL(String(alternativeExpected.data()), String(alternativeBuffer.get(), gsl::narrow<int>(alternative.size())));
VERIFY_ARE_EQUAL(String(alternativeExpected.data()), String(alternativeBuffer.get(), til::safe_cast<int>(alternative.size())));
Log::Comment(L"Now read the first line from the alternative/non-visible screen buffer. It should contain the second thing we wrote.");
read = 0;
VERIFY_WIN32_BOOL_SUCCEEDED(ReadConsoleOutputCharacterW(handle, alternativeBuffer.get(), gsl::narrow<DWORD>(alternative.size()), { 0, 0 }, &read));
VERIFY_WIN32_BOOL_SUCCEEDED(ReadConsoleOutputCharacterW(handle, alternativeBuffer.get(), til::safe_cast<DWORD>(alternative.size()), { 0, 0 }, &read));
VERIFY_ARE_EQUAL(alternative.size(), read);
VERIFY_ARE_EQUAL(String(alternative.data()), String(alternativeBuffer.get(), gsl::narrow<int>(alternative.size())));
VERIFY_ARE_EQUAL(String(alternative.data()), String(alternativeBuffer.get(), til::safe_cast<int>(alternative.size())));
}
void BufferTests::ScrollLargeBufferPerformance()

View File

@@ -27,7 +27,7 @@ class FillOutputTests
if (Common::_isV2)
{
VERIFY_WIN32_BOOL_FAILED(FillConsoleOutputCharacterA(handle, originalCh, 1, pos, &written));
VERIFY_ARE_EQUAL(gsl::narrow_cast<DWORD>(HRESULT_CODE(E_UNEXPECTED)), ::GetLastError());
VERIFY_ARE_EQUAL(til::safe_cast_nothrow<DWORD>(HRESULT_CODE(E_UNEXPECTED)), ::GetLastError());
}
else
{
@@ -113,7 +113,7 @@ class FillOutputTests
// Write until a wrap occurs
VERIFY_WIN32_BOOL_SUCCEEDED(WriteConsoleW(hConsole,
input.data(),
gsl::narrow_cast<DWORD>(input.size()),
til::safe_cast_nothrow<DWORD>(input.size()),
&charsWritten,
nullptr));

View File

@@ -389,7 +389,7 @@ void OutputTests::WriteConsoleOutputCharacterWRunoff()
DWORD charsWritten = 0;
VERIFY_SUCCEEDED(WriteConsoleOutputCharacterW(consoleOutputHandle,
text.c_str(),
gsl::narrow<DWORD>(text.size()),
til::safe_cast<DWORD>(text.size()),
target,
&charsWritten));
VERIFY_ARE_EQUAL(charsWritten, 1u);

View File

@@ -323,7 +323,7 @@ void DbcsWriteRead::SendOutput(const HANDLE hOut,
// This console API can treat the buffer as a 2D array. We're only doing 1 dimension so the Y is 1 and the X is the number of CHAR_INFO characters.
COORD coordBufferSize = { 0 };
coordBufferSize.Y = 1;
coordBufferSize.X = gsl::narrow<SHORT>(rgChars.size());
coordBufferSize.X = til::safe_cast<SHORT>(rgChars.size());
// We want to write to the coordinate 0,0 of the buffer. The test setup function has blanked out that line.
COORD coordBufferTarget = { 0 };
@@ -332,7 +332,7 @@ void DbcsWriteRead::SendOutput(const HANDLE hOut,
SMALL_RECT srWriteRegion = { 0 };
// Since we could have full-width characters, we have to "allow" the console to write up to the entire A string length (up to double the W length)
srWriteRegion.Right = gsl::narrow<SHORT>(dbcsInput.size()) - 1;
srWriteRegion.Right = til::safe_cast<SHORT>(dbcsInput.size()) - 1;
// Save the expected written rectangle for comparison after the call
srWrittenExpected = { 0 };
@@ -359,12 +359,12 @@ void DbcsWriteRead::SendOutput(const HANDLE hOut,
if (fIsUnicode)
{
dwWrittenExpected = gsl::narrow<DWORD>(unicodeInput.size());
dwWrittenExpected = til::safe_cast<DWORD>(unicodeInput.size());
WriteConsoleOutputCharacterW(hOut, unicodeInput.data(), dwWrittenExpected, coordBufferTarget, &dwWritten);
}
else
{
dwWrittenExpected = gsl::narrow<DWORD>(dbcsInput.size());
dwWrittenExpected = til::safe_cast<DWORD>(dbcsInput.size());
WriteConsoleOutputCharacterA(hOut, dbcsInput.data(), dwWrittenExpected, coordBufferTarget, &dwWritten);
}
@@ -375,12 +375,12 @@ void DbcsWriteRead::SendOutput(const HANDLE hOut,
{
if (fIsUnicode)
{
dwWrittenExpected = gsl::narrow<DWORD>(unicodeInput.size());
dwWrittenExpected = til::safe_cast<DWORD>(unicodeInput.size());
WriteConsoleW(hOut, unicodeInput.data(), dwWrittenExpected, &dwWritten, nullptr);
}
else
{
dwWrittenExpected = gsl::narrow<DWORD>(dbcsInput.size());
dwWrittenExpected = til::safe_cast<DWORD>(dbcsInput.size());
WriteConsoleA(hOut, dbcsInput.data(), dwWrittenExpected, &dwWritten, nullptr);
}
@@ -1247,7 +1247,7 @@ void DbcsWriteRead::RetrieveOutput(const HANDLE hOut,
// Since we wrote (in SendOutput function) to the 0,0 line, we need to read back the same width from that line.
COORD coordBufferSize = { 0 };
coordBufferSize.Y = 1;
coordBufferSize.X = gsl::narrow<SHORT>(rgChars.size());
coordBufferSize.X = til::safe_cast<SHORT>(rgChars.size());
SMALL_RECT srReadRegion = { 0 }; // inclusive rectangle (bottom and right are INSIDE the read area. usually are exclusive.)
srReadRegion.Right = coordBufferSize.X - 1;
@@ -1270,7 +1270,7 @@ void DbcsWriteRead::RetrieveOutput(const HANDLE hOut,
}
case DbcsWriteRead::ReadMode::ReadConsoleOutputCharacterFunc:
{
const auto cChars = gsl::narrow<DWORD>(rgChars.size());
const auto cChars = til::safe_cast<DWORD>(rgChars.size());
DWORD dwRead = 0;
if (!fReadUnicode)
{

View File

@@ -315,7 +315,7 @@ void ApiRoutines::GetNumberOfConsoleMouseButtonsImpl(ULONG& buttons) noexcept
RETURN_IF_FAILED(StringCchCopyW(FaceName, ARRAYSIZE(FaceName), consoleFontInfoEx.FaceName));
FontInfo fi(FaceName,
gsl::narrow_cast<unsigned char>(consoleFontInfoEx.FontFamily),
til::safe_cast_nothrow<unsigned char>(consoleFontInfoEx.FontFamily),
consoleFontInfoEx.FontWeight,
til::wrap_coord_size(consoleFontInfoEx.dwFontSize),
gci.OutputCP);
@@ -1281,7 +1281,7 @@ void ApiRoutines::GetConsoleDisplayModeImpl(ULONG& flags) noexcept
// - isOriginal - If true, gets the title when we booted up. If false, gets whatever it is set to right now.
// Return Value:
// - S_OK, E_INVALIDARG, or failure code from thrown exception
[[nodiscard]] HRESULT GetConsoleTitleWImplHelper(std::optional<gsl::span<wchar_t>> title,
[[nodiscard]] HRESULT GetConsoleTitleWImplHelper(std::optional<std::span<wchar_t>> title,
size_t& written,
size_t& needed,
const bool isOriginal) noexcept
@@ -1332,7 +1332,7 @@ void ApiRoutines::GetConsoleDisplayModeImpl(ULONG& flags) noexcept
// Return Value:
// - S_OK, E_INVALIDARG, or failure code from thrown exception
[[nodiscard]] HRESULT GetConsoleTitleAImplHelper(gsl::span<char> title,
[[nodiscard]] HRESULT GetConsoleTitleAImplHelper(std::span<char> title,
size_t& written,
size_t& needed,
const bool isOriginal) noexcept
@@ -1362,7 +1362,7 @@ void ApiRoutines::GetConsoleDisplayModeImpl(ULONG& flags) noexcept
auto unicodeBuffer = std::make_unique<wchar_t[]>(unicodeSize);
RETURN_IF_NULL_ALLOC(unicodeBuffer);
const gsl::span<wchar_t> unicodeSpan(unicodeBuffer.get(), unicodeSize);
const std::span<wchar_t> unicodeSpan(unicodeBuffer.get(), unicodeSize);
// Retrieve the title in Unicode.
RETURN_IF_FAILED(GetConsoleTitleWImplHelper(unicodeSpan, unicodeWritten, unicodeNeeded, isOriginal));
@@ -1420,7 +1420,7 @@ void ApiRoutines::GetConsoleDisplayModeImpl(ULONG& flags) noexcept
// - needed - The number of characters we would need to completely write out the title.
// Return Value:
// - S_OK, E_INVALIDARG, or failure code from thrown exception
[[nodiscard]] HRESULT ApiRoutines::GetConsoleTitleAImpl(gsl::span<char> title,
[[nodiscard]] HRESULT ApiRoutines::GetConsoleTitleAImpl(std::span<char> title,
size_t& written,
size_t& needed) noexcept
{
@@ -1443,7 +1443,7 @@ void ApiRoutines::GetConsoleDisplayModeImpl(ULONG& flags) noexcept
// - needed - The number of characters we would need to completely write out the title.
// Return Value:
// - S_OK, E_INVALIDARG, or failure code from thrown exception
[[nodiscard]] HRESULT ApiRoutines::GetConsoleTitleWImpl(gsl::span<wchar_t> title,
[[nodiscard]] HRESULT ApiRoutines::GetConsoleTitleWImpl(std::span<wchar_t> title,
size_t& written,
size_t& needed) noexcept
{
@@ -1466,7 +1466,7 @@ void ApiRoutines::GetConsoleDisplayModeImpl(ULONG& flags) noexcept
// - needed - The number of characters we would need to completely write out the title.
// Return Value:
// - S_OK, E_INVALIDARG, or failure code from thrown exception
[[nodiscard]] HRESULT ApiRoutines::GetConsoleOriginalTitleAImpl(gsl::span<char> title,
[[nodiscard]] HRESULT ApiRoutines::GetConsoleOriginalTitleAImpl(std::span<char> title,
size_t& written,
size_t& needed) noexcept
{
@@ -1489,7 +1489,7 @@ void ApiRoutines::GetConsoleDisplayModeImpl(ULONG& flags) noexcept
// - needed - The number of characters we would need to completely write out the title.
// Return Value:
// - S_OK, E_INVALIDARG, or failure code from thrown exception
[[nodiscard]] HRESULT ApiRoutines::GetConsoleOriginalTitleWImpl(gsl::span<wchar_t> title,
[[nodiscard]] HRESULT ApiRoutines::GetConsoleOriginalTitleWImpl(std::span<wchar_t> title,
size_t& written,
size_t& needed) noexcept
{

View File

@@ -64,7 +64,7 @@ void CommandHistory::s_ResizeAll(const size_t commands)
{
auto& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
FAIL_FAST_IF(commands > SHORT_MAX);
gci.SetHistoryBufferSize(gsl::narrow<UINT>(commands));
gci.SetHistoryBufferSize(til::safe_cast<UINT>(commands));
for (auto& historyList : s_historyLists)
{
@@ -74,14 +74,14 @@ void CommandHistory::s_ResizeAll(const size_t commands)
bool CommandHistory::IsAppNameMatch(const std::wstring_view other) const
{
return CompareStringOrdinal(_appName.data(), gsl::narrow<int>(_appName.size()), other.data(), gsl::narrow<int>(other.size()), TRUE) == CSTR_EQUAL;
return CompareStringOrdinal(_appName.data(), til::safe_cast<int>(_appName.size()), other.data(), til::safe_cast<int>(other.size()), TRUE) == CSTR_EQUAL;
}
// Routine Description:
// - This routine is called when escape is entered or a command is added.
void CommandHistory::_Reset()
{
LastDisplayed = gsl::narrow<SHORT>(_commands.size()) - 1;
LastDisplayed = til::safe_cast<SHORT>(_commands.size()) - 1;
WI_SetFlag(Flags, CLE_RESET);
}
@@ -164,7 +164,7 @@ std::wstring_view CommandHistory::GetNth(const SHORT index) const
}
[[nodiscard]] HRESULT CommandHistory::RetrieveNth(const SHORT index,
gsl::span<wchar_t> buffer,
std::span<wchar_t> buffer,
size_t& commandSize)
{
LastDisplayed = index;
@@ -191,7 +191,7 @@ std::wstring_view CommandHistory::GetNth(const SHORT index) const
}
[[nodiscard]] HRESULT CommandHistory::Retrieve(const SearchDirection searchDirection,
const gsl::span<wchar_t> buffer,
const std::span<wchar_t> buffer,
size_t& commandSize)
{
FAIL_FAST_IF(!(WI_IsFlagSet(Flags, CLE_ALLOCATED)));
@@ -278,7 +278,7 @@ void CommandHistory::Realloc(const size_t commands)
}
const auto oldCommands = _commands;
const auto newNumberOfCommands = gsl::narrow<SHORT>(std::min(_commands.size(), commands));
const auto newNumberOfCommands = til::safe_cast<SHORT>(std::min(_commands.size(), commands));
_commands.clear();
for (SHORT i = 0; i < newNumberOfCommands; i++)
@@ -287,7 +287,7 @@ void CommandHistory::Realloc(const size_t commands)
}
WI_SetFlag(Flags, CLE_RESET);
LastDisplayed = gsl::narrow<SHORT>(_commands.size()) - 1;
LastDisplayed = til::safe_cast<SHORT>(_commands.size()) - 1;
_maxCommands = (SHORT)commands;
}
@@ -363,7 +363,7 @@ CommandHistory* CommandHistory::s_Allocate(const std::wstring_view appName, cons
History._appName = appName;
History.Flags = CLE_ALLOCATED;
History.LastDisplayed = -1;
History._maxCommands = gsl::narrow<SHORT>(gci.GetHistoryBufferSize());
History._maxCommands = til::safe_cast<SHORT>(gci.GetHistoryBufferSize());
History._processHandle = processHandle;
return &s_historyLists.emplace_front(History);
}
@@ -419,7 +419,7 @@ void CommandHistory::_Prev(SHORT& ind) const
{
if (ind <= 0)
{
ind = gsl::narrow<SHORT>(_commands.size());
ind = til::safe_cast<SHORT>(_commands.size());
}
ind--;
}
@@ -454,7 +454,7 @@ void CommandHistory::_Inc(SHORT& ind) const
std::wstring CommandHistory::Remove(const SHORT iDel)
{
SHORT iFirst = 0;
auto iLast = gsl::narrow<SHORT>(_commands.size() - 1);
auto iLast = til::safe_cast<SHORT>(_commands.size() - 1);
auto iDisp = LastDisplayed;
if (_commands.size() == 0)
@@ -689,7 +689,7 @@ HRESULT GetConsoleCommandHistoryLengthImplHelper(const std::wstring_view exeName
// Every command history item is made of a string length followed by 1 null character.
const size_t cchNull = 1;
for (SHORT i = 0; i < gsl::narrow<SHORT>(pCommandHistory->GetNumberOfCommands()); i++)
for (SHORT i = 0; i < til::safe_cast<SHORT>(pCommandHistory->GetNumberOfCommands()); i++)
{
const auto command = pCommandHistory->GetNth(i);
auto cchCommand = command.size();
@@ -776,7 +776,7 @@ HRESULT ApiRoutines::GetConsoleCommandHistoryLengthWImpl(const std::wstring_view
// Return Value:
// - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors.
HRESULT GetConsoleCommandHistoryWImplHelper(const std::wstring_view exeName,
gsl::span<wchar_t> historyBuffer,
std::span<wchar_t> historyBuffer,
size_t& writtenOrNeeded)
{
// Ensure output variables are initialized
@@ -796,7 +796,7 @@ HRESULT GetConsoleCommandHistoryWImplHelper(const std::wstring_view exeName,
const size_t cchNull = 1;
for (SHORT i = 0; i < gsl::narrow<SHORT>(CommandHistory->GetNumberOfCommands()); i++)
for (SHORT i = 0; i < til::safe_cast<SHORT>(CommandHistory->GetNumberOfCommands()); i++)
{
const auto command = CommandHistory->GetNth(i);
@@ -847,7 +847,7 @@ HRESULT GetConsoleCommandHistoryWImplHelper(const std::wstring_view exeName,
// Return Value:
// - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors.
HRESULT ApiRoutines::GetConsoleCommandHistoryAImpl(const std::string_view exeName,
gsl::span<char> commandHistory,
std::span<char> commandHistory,
size_t& written) noexcept
{
const auto& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
@@ -882,7 +882,7 @@ HRESULT ApiRoutines::GetConsoleCommandHistoryAImpl(const std::string_view exeNam
// Call the Unicode version of this method
size_t bufferWritten;
RETURN_IF_FAILED(GetConsoleCommandHistoryWImplHelper(exeNameW, gsl::span<wchar_t>(buffer.get(), bufferNeeded), bufferWritten));
RETURN_IF_FAILED(GetConsoleCommandHistoryWImplHelper(exeNameW, std::span<wchar_t>(buffer.get(), bufferNeeded), bufferWritten));
// Convert result to A
const auto converted = ConvertToA(codepage, { buffer.get(), bufferWritten });
@@ -911,7 +911,7 @@ HRESULT ApiRoutines::GetConsoleCommandHistoryAImpl(const std::string_view exeNam
// Return Value:
// - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors.
HRESULT ApiRoutines::GetConsoleCommandHistoryWImpl(const std::wstring_view exeName,
gsl::span<wchar_t> commandHistory,
std::span<wchar_t> commandHistory,
size_t& written) noexcept
{
LockConsole();

View File

@@ -50,11 +50,11 @@ public:
const bool suppressDuplicates);
[[nodiscard]] HRESULT Retrieve(const SearchDirection searchDirection,
const gsl::span<wchar_t> buffer,
const std::span<wchar_t> buffer,
size_t& commandSize);
[[nodiscard]] HRESULT RetrieveNth(const SHORT index,
const gsl::span<wchar_t> buffer,
const std::span<wchar_t> buffer,
size_t& commandSize);
size_t GetNumberOfCommands() const;

View File

@@ -26,7 +26,7 @@ using namespace Microsoft::Console::Interactivity;
auto& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
FontInfo fiFont(gci.GetFaceName(),
gsl::narrow_cast<unsigned char>(gci.GetFontFamily()),
til::safe_cast_nothrow<unsigned char>(gci.GetFontFamily()),
gci.GetFontWeight(),
gci.GetFontSize(),
gci.GetCodePage());

View File

@@ -385,7 +385,7 @@ void ConhostInternalGetSet::PlayMidiNote(const int noteNumber, const int velocit
// - True if handled successfully. False otherwise.
bool ConhostInternalGetSet::ResizeWindow(const til::CoordType sColumns, const til::CoordType sRows)
{
// Ensure we can safely use gsl::narrow_cast<short>(...).
// Ensure we can safely use til::safe_cast_nothrow<short>(...).
if (sColumns <= 0 || sRows <= 0 || sColumns > SHRT_MAX || sRows > SHRT_MAX)
{
return false;
@@ -401,12 +401,12 @@ bool ConhostInternalGetSet::ResizeWindow(const til::CoordType sColumns, const ti
const auto oldViewport = screenInfo.GetVirtualViewport();
auto newViewport = Viewport::FromDimensions(oldViewport.Origin(), sColumns, sRows);
// Always resize the width of the console
csbiex.dwSize.X = gsl::narrow_cast<short>(sColumns);
csbiex.dwSize.X = til::safe_cast_nothrow<short>(sColumns);
// Only set the screen buffer's height if it's currently less than
// what we're requesting.
if (sRows > csbiex.dwSize.Y)
{
csbiex.dwSize.Y = gsl::narrow_cast<short>(sRows);
csbiex.dwSize.Y = til::safe_cast_nothrow<short>(sRows);
}
// If the cursor row is now past the bottom of the viewport, we'll have to

View File

@@ -162,7 +162,7 @@ void Popup::_DrawPrompt(const UINT id)
WriteCoord.y = _region.top + 1;
// write prompt to screen
lStringLength = gsl::narrow<til::CoordType>(text.size());
lStringLength = til::safe_cast<til::CoordType>(text.size());
if (lStringLength > Width())
{
text = text.substr(0, Width());

View File

@@ -128,12 +128,12 @@ COOKED_READ_DATA::~COOKED_READ_DATA()
CommandLine::Instance().EndAllPopups();
}
gsl::span<wchar_t> COOKED_READ_DATA::SpanWholeBuffer()
std::span<wchar_t> COOKED_READ_DATA::SpanWholeBuffer()
{
return gsl::make_span(_backupLimit, (_bufferSize / sizeof(wchar_t)));
return std::span{ _backupLimit, (_bufferSize / sizeof(wchar_t)) };
}
gsl::span<wchar_t> COOKED_READ_DATA::SpanAtPointer()
std::span<wchar_t> COOKED_READ_DATA::SpanAtPointer()
{
auto wholeSpan = SpanWholeBuffer();
return wholeSpan.subspan(_bufPtr - _backupLimit);
@@ -1179,9 +1179,9 @@ void COOKED_READ_DATA::SavePendingInput(const size_t index, const bool multiline
std::unique_ptr<IInputEvent> partialEvent;
numBytes = TranslateUnicodeToOem(_userBuffer,
gsl::narrow<ULONG>(numBytes / sizeof(wchar_t)),
til::safe_cast<ULONG>(numBytes / sizeof(wchar_t)),
tempBuffer.get(),
gsl::narrow<ULONG>(NumBytes),
til::safe_cast<ULONG>(NumBytes),
partialEvent);
if (partialEvent.get())

View File

@@ -57,8 +57,8 @@ public:
_Out_ DWORD* const pControlKeyState,
_Out_ void* const pOutputData) override;
gsl::span<wchar_t> SpanAtPointer();
gsl::span<wchar_t> SpanWholeBuffer();
std::span<wchar_t> SpanAtPointer();
std::span<wchar_t> SpanWholeBuffer();
size_t Write(const std::wstring_view wstr);

View File

@@ -199,9 +199,9 @@ bool RAW_READ_DATA::Notify(const WaitTerminationReason TerminationReason,
std::unique_ptr<IInputEvent> partialEvent;
*pNumBytes = TranslateUnicodeToOem(lpBuffer,
gsl::narrow<ULONG>(*pNumBytes / sizeof(wchar_t)),
til::safe_cast<ULONG>(*pNumBytes / sizeof(wchar_t)),
tempBuffer.get(),
gsl::narrow<ULONG>(NumBytes),
til::safe_cast<ULONG>(NumBytes),
partialEvent);
if (partialEvent.get())
{

View File

@@ -2274,10 +2274,10 @@ void SCREEN_INFORMATION::SetViewport(const Viewport& newViewport,
// MSFT-33471786, GH#13193:
// newViewport may reside anywhere outside of the valid coordScreenBufferSize.
// For instance it might be scrolled down more than our text buffer allows to be scrolled.
const auto cx = gsl::narrow_cast<SHORT>(std::clamp(viewportRect.width(), 1, coordScreenBufferSize.width));
const auto cy = gsl::narrow_cast<SHORT>(std::clamp(viewportRect.height(), 1, coordScreenBufferSize.height));
const auto x = gsl::narrow_cast<SHORT>(std::clamp(viewportRect.left, 0, coordScreenBufferSize.width - cx));
const auto y = gsl::narrow_cast<SHORT>(std::clamp(viewportRect.top, 0, coordScreenBufferSize.height - cy));
const auto cx = til::safe_cast_nothrow<SHORT>(std::clamp(viewportRect.width(), 1, coordScreenBufferSize.width));
const auto cy = til::safe_cast_nothrow<SHORT>(std::clamp(viewportRect.height(), 1, coordScreenBufferSize.height));
const auto x = til::safe_cast_nothrow<SHORT>(std::clamp(viewportRect.left, 0, coordScreenBufferSize.width - cx));
const auto y = til::safe_cast_nothrow<SHORT>(std::clamp(viewportRect.top, 0, coordScreenBufferSize.height - cy));
_viewport = Viewport::FromExclusive({ x, y, x + cx, y + cy });
@@ -2329,7 +2329,7 @@ void SCREEN_INFORMATION::SetViewport(const Viewport& newViewport,
// +1 on the y coord because we don't want to clear the attributes of the
// cursor row, the one we saved.
til::point fillPosition{ 0, _viewport.Top() + 1 };
auto fillLength = gsl::narrow<size_t>(_viewport.Height() * GetBufferSize().Width());
auto fillLength = til::safe_cast<size_t>(_viewport.Height() * GetBufferSize().Width());
auto fillData = OutputCellIterator{ fillAttributes, fillLength };
Write(fillData, fillPosition, false);

View File

@@ -406,7 +406,7 @@ void Selection::ColorSelection(const til::inclusive_rect& srRect, const TextAttr
// Now color the selection a line at a time.
for (; (coordTarget.y < srRect.top + coordTargetSize.y); ++coordTarget.y)
{
const auto cchWrite = gsl::narrow<size_t>(coordTargetSize.x);
const auto cchWrite = til::safe_cast<size_t>(coordTargetSize.x);
try
{

View File

@@ -974,7 +974,7 @@ bool Selection::_HandleMarkModeSelectionNav(const INPUT_KEY_INFO* const pInputKe
else
{
// otherwise, we need to add the number of characters in the input line to the original cursor position
bufferSize.MoveInBounds(gsl::narrow<til::CoordType>(cookedRead.VisibleCharCount()), coordEnd);
bufferSize.MoveInBounds(til::safe_cast<til::CoordType>(cookedRead.VisibleCharCount()), coordEnd);
}
// - 1 so the coordinate is on top of the last position of the text, not one past it.

View File

@@ -281,7 +281,7 @@ til::CoordType RetrieveNumberOfSpaces(_In_ til::CoordType sOriginalCursorPositio
// - STATUS_NO_MEMORY in low memory situation
// - other relevant NTSTATUS codes
[[nodiscard]] static NTSTATUS _ReadPendingInput(InputBuffer& inputBuffer,
gsl::span<char> buffer,
std::span<char> buffer,
size_t& bytesRead,
INPUT_READ_HANDLE_DATA& readHandleState,
const bool unicode)
@@ -407,9 +407,9 @@ til::CoordType RetrieveNumberOfSpaces(_In_ til::CoordType sOriginalCursorPositio
std::unique_ptr<IInputEvent> partialEvent;
NumToWrite = TranslateUnicodeToOem(pBuffer,
gsl::narrow<ULONG>(NumToWrite / sizeof(wchar_t)),
til::safe_cast<ULONG>(NumToWrite / sizeof(wchar_t)),
tempBuffer.get(),
gsl::narrow<ULONG>(NumToBytes),
til::safe_cast<ULONG>(NumToBytes),
partialEvent);
if (partialEvent.get())
{
@@ -457,7 +457,7 @@ til::CoordType RetrieveNumberOfSpaces(_In_ til::CoordType sOriginalCursorPositio
// - other relevant HRESULT codes
[[nodiscard]] static HRESULT _ReadLineInput(InputBuffer& inputBuffer,
const HANDLE processData,
gsl::span<char> buffer,
std::span<char> buffer,
size_t& bytesRead,
DWORD& controlKeyState,
const std::string_view initialData,
@@ -522,7 +522,7 @@ til::CoordType RetrieveNumberOfSpaces(_In_ til::CoordType sOriginalCursorPositio
// - STATUS_SUCCESS on success
// - Other NTSTATUS codes as necessary
[[nodiscard]] static NTSTATUS _ReadCharacterInput(InputBuffer& inputBuffer,
gsl::span<char> buffer,
std::span<char> buffer,
size_t& bytesRead,
INPUT_READ_HANDLE_DATA& readHandleState,
const bool unicode,
@@ -575,7 +575,7 @@ til::CoordType RetrieveNumberOfSpaces(_In_ til::CoordType sOriginalCursorPositio
{
waiter = std::make_unique<RAW_READ_DATA>(&inputBuffer,
&readHandleState,
gsl::narrow<ULONG>(buffer.size_bytes()),
til::safe_cast<ULONG>(buffer.size_bytes()),
reinterpret_cast<wchar_t*>(buffer.data()));
}
@@ -626,9 +626,9 @@ til::CoordType RetrieveNumberOfSpaces(_In_ til::CoordType sOriginalCursorPositio
std::unique_ptr<IInputEvent> partialEvent;
bytesRead = TranslateUnicodeToOem(pBuffer,
gsl::narrow<ULONG>(NumToWrite / sizeof(wchar_t)),
til::safe_cast<ULONG>(NumToWrite / sizeof(wchar_t)),
tempBuffer.get(),
gsl::narrow<ULONG>(bytesRead),
til::safe_cast<ULONG>(bytesRead),
partialEvent);
if (partialEvent.get())
@@ -682,7 +682,7 @@ til::CoordType RetrieveNumberOfSpaces(_In_ til::CoordType sOriginalCursorPositio
// - Other NSTATUS codes as necessary
[[nodiscard]] NTSTATUS DoReadConsole(InputBuffer& inputBuffer,
const HANDLE processData,
gsl::span<char> buffer,
std::span<char> buffer,
size_t& bytesRead,
ULONG& controlKeyState,
const std::string_view initialData,
@@ -742,7 +742,7 @@ til::CoordType RetrieveNumberOfSpaces(_In_ til::CoordType sOriginalCursorPositio
}
[[nodiscard]] HRESULT ApiRoutines::ReadConsoleAImpl(IConsoleInputObject& context,
gsl::span<char> buffer,
std::span<char> buffer,
size_t& written,
std::unique_ptr<IWaitRoutine>& waiter,
const std::string_view initialData,
@@ -770,7 +770,7 @@ til::CoordType RetrieveNumberOfSpaces(_In_ til::CoordType sOriginalCursorPositio
}
[[nodiscard]] HRESULT ApiRoutines::ReadConsoleWImpl(IConsoleInputObject& context,
gsl::span<char> buffer,
std::span<char> buffer,
size_t& written,
std::unique_ptr<IWaitRoutine>& waiter,
const std::string_view initialData,

View File

@@ -230,7 +230,7 @@ void Tracing::s_TraceApi(const CONSOLE_MODE_MSG* const a, const std::wstring_vie
g_hConhostV2EventTraceProvider,
"API_GetConsoleMode",
TraceLoggingHexUInt32(a->Mode, "Mode"),
TraceLoggingCountedWideString(handleType.data(), gsl::narrow_cast<ULONG>(handleType.size()), "Handle type"),
TraceLoggingCountedWideString(handleType.data(), til::safe_cast_nothrow<ULONG>(handleType.size()), "Handle type"),
TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE),
TraceLoggingKeyword(TIL_KEYWORD_TRACE),
TraceLoggingKeyword(TraceKeywords::API));

View File

@@ -187,7 +187,7 @@ class AliasTests
rgwchTarget[cbTargetUsed] = L'\0';
VERIFY_ARE_EQUAL(cbTargetExpected, cbTargetUsed, L"Target bytes should be filled with target size.");
VERIFY_ARE_EQUAL(String(targetExpected.data()), String(rgwchTarget.get(), gsl::narrow<int>(cbTargetUsed / sizeof(wchar_t))), L"Target string should be filled with target data.");
VERIFY_ARE_EQUAL(String(targetExpected.data()), String(rgwchTarget.get(), til::safe_cast<int>(cbTargetUsed / sizeof(wchar_t))), L"Target string should be filled with target data.");
VERIFY_ARE_EQUAL(1u, dwLines, L"Line count should be 1.");
}

View File

@@ -222,7 +222,7 @@ class ApiRoutinesTests
char pszTitle[MAX_PATH]; // most applications use MAX_PATH
size_t cchWritten = 0;
size_t cchNeeded = 0;
VERIFY_SUCCEEDED(_pApiRoutines->GetConsoleTitleAImpl(gsl::span<char>(pszTitle, ARRAYSIZE(pszTitle)), cchWritten, cchNeeded));
VERIFY_SUCCEEDED(_pApiRoutines->GetConsoleTitleAImpl(std::span<char>(pszTitle, ARRAYSIZE(pszTitle)), cchWritten, cchNeeded));
VERIFY_ARE_NOT_EQUAL(0u, cchWritten);
// NOTE: W version of API returns string length. A version of API returns buffer length (string + null).
@@ -239,7 +239,7 @@ class ApiRoutinesTests
wchar_t pwszTitle[MAX_PATH]; // most applications use MAX_PATH
size_t cchWritten = 0;
size_t cchNeeded = 0;
VERIFY_SUCCEEDED(_pApiRoutines->GetConsoleTitleWImpl(gsl::span<wchar_t>(pwszTitle, ARRAYSIZE(pwszTitle)), cchWritten, cchNeeded));
VERIFY_SUCCEEDED(_pApiRoutines->GetConsoleTitleWImpl(std::span<wchar_t>(pwszTitle, ARRAYSIZE(pwszTitle)), cchWritten, cchNeeded));
VERIFY_ARE_NOT_EQUAL(0u, cchWritten);
@@ -248,7 +248,7 @@ class ApiRoutinesTests
// NOTE: W version of API returns string length. A version of API returns buffer length (string + null).
VERIFY_ARE_EQUAL(title.length(), cchWritten);
VERIFY_ARE_EQUAL(title.length(), cchNeeded);
VERIFY_ARE_EQUAL(WEX::Common::String(title.data(), gsl::narrow_cast<int>(title.size())), WEX::Common::String(pwszTitle));
VERIFY_ARE_EQUAL(WEX::Common::String(title.data(), til::safe_cast_nothrow<int>(title.size())), WEX::Common::String(pwszTitle));
}
TEST_METHOD(ApiGetConsoleOriginalTitleA)
@@ -261,7 +261,7 @@ class ApiRoutinesTests
const auto iBytesNeeded = WideCharToMultiByte(gci.OutputCP,
0,
originalTitle.data(),
gsl::narrow_cast<int>(originalTitle.size()),
til::safe_cast_nothrow<int>(originalTitle.size()),
nullptr,
0,
nullptr,
@@ -273,7 +273,7 @@ class ApiRoutinesTests
VERIFY_WIN32_BOOL_SUCCEEDED(WideCharToMultiByte(gci.OutputCP,
0,
originalTitle.data(),
gsl::narrow_cast<int>(originalTitle.size()),
til::safe_cast_nothrow<int>(originalTitle.size()),
pszExpected.get(),
iBytesNeeded,
nullptr,
@@ -285,7 +285,7 @@ class ApiRoutinesTests
char pszTitle[MAX_PATH]; // most applications use MAX_PATH
size_t cchWritten = 0;
size_t cchNeeded = 0;
VERIFY_SUCCEEDED(_pApiRoutines->GetConsoleOriginalTitleAImpl(gsl::span<char>(pszTitle, ARRAYSIZE(pszTitle)), cchWritten, cchNeeded));
VERIFY_SUCCEEDED(_pApiRoutines->GetConsoleOriginalTitleAImpl(std::span<char>(pszTitle, ARRAYSIZE(pszTitle)), cchWritten, cchNeeded));
VERIFY_ARE_NOT_EQUAL(0u, cchWritten);
// NOTE: W version of API returns string length. A version of API returns buffer length (string + null).
@@ -302,7 +302,7 @@ class ApiRoutinesTests
wchar_t pwszTitle[MAX_PATH]; // most applications use MAX_PATH
size_t cchWritten = 0;
size_t cchNeeded = 0;
VERIFY_SUCCEEDED(_pApiRoutines->GetConsoleOriginalTitleWImpl(gsl::span<wchar_t>(pwszTitle, ARRAYSIZE(pwszTitle)), cchWritten, cchNeeded));
VERIFY_SUCCEEDED(_pApiRoutines->GetConsoleOriginalTitleWImpl(std::span<wchar_t>(pwszTitle, ARRAYSIZE(pwszTitle)), cchWritten, cchNeeded));
VERIFY_ARE_NOT_EQUAL(0u, cchWritten);
@@ -310,7 +310,7 @@ class ApiRoutinesTests
// NOTE: W version of API returns string length. A version of API returns buffer length (string + null).
VERIFY_ARE_EQUAL(originalTitle.length(), cchWritten);
VERIFY_ARE_EQUAL(originalTitle.length(), cchNeeded);
VERIFY_ARE_EQUAL(WEX::Common::String(originalTitle.data(), gsl::narrow_cast<int>(originalTitle.size())), WEX::Common::String(pwszTitle));
VERIFY_ARE_EQUAL(WEX::Common::String(originalTitle.data(), til::safe_cast_nothrow<int>(originalTitle.size())), WEX::Common::String(pwszTitle));
}
static void s_AdjustOutputWait(const bool fShouldBlock)

Some files were not shown because too many files have changed in this diff Show More