Use std::span where possible without much effort

This commit is contained in:
Tamás Bálint Misius
2024-12-16 17:11:50 +01:00
parent 5739170f20
commit 9fa0fc45bc
25 changed files with 69 additions and 51 deletions

View File

@@ -20,15 +20,30 @@ bytes_str = ', '.join([ str(ch) for ch in data ])
with open(output_cpp_path, 'w') as output_cpp_f:
output_cpp_f.write(f'''
#include "{output_h_path}"
const unsigned char {symbol_name}[] = {{ {bytes_str} }};
const unsigned int {symbol_name}_size = {data_size};
const struct {symbol_name}Resource {symbol_name} = {{{{{{ {bytes_str} }}}}}};
''')
with open(output_h_path, 'w') as output_h_f:
output_h_f.write(f'''
#pragma once
extern const unsigned char {symbol_name}[];
extern const unsigned int {symbol_name}_size;
#include <array>
#include <span>
extern const struct {symbol_name}Resource
{{
std::array<unsigned char, {data_size}> data;
std::span<const char> AsCharSpan() const
{{
return std::span(reinterpret_cast<const char *>(data.data()), data.size());
}}
std::span<const unsigned char> AsUcharSpan() const
{{
return std::span(data.data(), data.size());
}}
}} {symbol_name};
''')
def dep_escape(s):

View File

@@ -123,7 +123,7 @@ std::vector<char> format::PixelsToPPM(PlaneAdapter<std::vector<pixel>> const &in
}
static std::unique_ptr<PlaneAdapter<std::vector<uint32_t>>> readPNG(
std::vector<char> const &data,
std::span<const char> data,
// If omitted,
// RGB data is returned with A=0xFF
// RGBA data is returned as itself
@@ -218,12 +218,12 @@ static std::unique_ptr<PlaneAdapter<std::vector<uint32_t>>> readPNG(
return output;
}
std::unique_ptr<PlaneAdapter<std::vector<pixel_rgba>>> format::PixelsFromPNG(std::vector<char> const &data)
std::unique_ptr<PlaneAdapter<std::vector<pixel_rgba>>> format::PixelsFromPNG(std::span<const char> data)
{
return readPNG(data, std::nullopt);
}
std::unique_ptr<PlaneAdapter<std::vector<pixel>>> format::PixelsFromPNG(std::vector<char> const &data, RGB<uint8_t> background)
std::unique_ptr<PlaneAdapter<std::vector<pixel>>> format::PixelsFromPNG(std::span<const char> data, RGB<uint8_t> background)
{
return readPNG(data, background);
}

View File

@@ -1,5 +1,6 @@
#pragma once
#include <memory>
#include <span>
#include <vector>
#include "common/String.h"
#include "common/Plane.h"
@@ -16,8 +17,8 @@ namespace format
String CleanString(String dirtyString, bool ascii, bool color, bool newlines, bool numeric = false);
std::vector<char> PixelsToPPM(PlaneAdapter<std::vector<pixel>> const &);
std::unique_ptr<std::vector<char>> PixelsToPNG(PlaneAdapter<std::vector<pixel>> const &);
std::unique_ptr<PlaneAdapter<std::vector<pixel_rgba>>> PixelsFromPNG(std::vector<char> const &);
std::unique_ptr<PlaneAdapter<std::vector<pixel>>> PixelsFromPNG(std::vector<char> const &, RGB<uint8_t> background);
std::unique_ptr<PlaneAdapter<std::vector<pixel_rgba>>> PixelsFromPNG(std::span<const char> data);
std::unique_ptr<PlaneAdapter<std::vector<pixel>>> PixelsFromPNG(std::span<const char> data, RGB<uint8_t> background);
void RenderTemperature(StringBuilder &sb, float temp, int scale);
float StringToTemperature(String str, int defaultScale);
}

View File

@@ -137,7 +137,7 @@ static void BlueScreen(String detailMessage, std::optional<std::vector<String>>
auto crashLogData = errorText.ToUtf8();
std::cerr << crashLogData << std::endl;
Platform::WriteFile(std::vector<char>(crashLogData.begin(), crashLogData.end()), crashLogPath);
Platform::WriteFile(crashLogData, crashLogPath);
//Death loop
SDL_Event event;

View File

@@ -6,7 +6,7 @@
void WindowIcon(SDL_Window *window)
{
if (auto image = format::PixelsFromPNG(std::vector<char>(icon_exe_png, icon_exe_png + icon_exe_png_size)))
if (auto image = format::PixelsFromPNG(icon_exe_png.AsCharSpan()))
{
SDL_Surface *icon = SDL_CreateRGBSurfaceFrom(image->data(), image->Size().X, image->Size().Y, 32, image->Size().Y * sizeof(pixel), 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000);
SDL_SetWindowIcon(window, icon);

View File

@@ -7,7 +7,7 @@
static size_t outputSizeIncrement = 0x100000U;
BZ2WCompressResult BZ2WCompress(std::vector<char> &dest, const char *srcData, size_t srcSize, size_t maxSize)
BZ2WCompressResult BZ2WCompress(std::vector<char> &dest, std::span<const char> srcData, size_t maxSize)
{
bz_stream stream;
stream.bzalloc = NULL;
@@ -18,8 +18,8 @@ BZ2WCompressResult BZ2WCompress(std::vector<char> &dest, const char *srcData, si
return BZ2WCompressNomem;
}
std::unique_ptr<bz_stream, std::function<int (bz_stream *)>> bz2Data(&stream, BZ2_bzCompressEnd);
stream.next_in = const_cast<char *>(srcData); // I hope bz2 doesn't actually write anything here...
stream.avail_in = srcSize;
stream.next_in = const_cast<char *>(srcData.data()); // I hope bz2 doesn't actually write anything here...
stream.avail_in = srcData.size();
dest.resize(0);
bool done = false;
while (!done)
@@ -53,7 +53,7 @@ BZ2WCompressResult BZ2WCompress(std::vector<char> &dest, const char *srcData, si
return BZ2WCompressOk;
}
BZ2WDecompressResult BZ2WDecompress(std::vector<char> &dest, const char *srcData, size_t srcSize, size_t maxSize)
BZ2WDecompressResult BZ2WDecompress(std::vector<char> &dest, std::span<const char> srcData, size_t maxSize)
{
bz_stream stream;
stream.bzalloc = NULL;
@@ -64,8 +64,8 @@ BZ2WDecompressResult BZ2WDecompress(std::vector<char> &dest, const char *srcData
return BZ2WDecompressNomem;
}
std::unique_ptr<bz_stream, std::function<int (bz_stream *)>> bz2Data(&stream, BZ2_bzDecompressEnd);
stream.next_in = const_cast<char *>(srcData); // I hope bz2 doesn't actually write anything here...
stream.avail_in = srcSize;
stream.next_in = const_cast<char *>(srcData.data()); // I hope bz2 doesn't actually write anything here...
stream.avail_in = srcData.size();
dest.resize(0);
bool done = false;
while (!done)

View File

@@ -1,5 +1,6 @@
#pragma once
#include <cstddef>
#include <span>
#include <vector>
enum BZ2WCompressResult
@@ -8,7 +9,7 @@ enum BZ2WCompressResult
BZ2WCompressNomem,
BZ2WCompressLimit,
};
BZ2WCompressResult BZ2WCompress(std::vector<char> &dest, const char *srcData, size_t srcSize, size_t maxSize = 0);
BZ2WCompressResult BZ2WCompress(std::vector<char> &dest, std::span<const char> srcData, size_t maxSize = 0);
enum BZ2WDecompressResult
{
@@ -19,4 +20,4 @@ enum BZ2WDecompressResult
BZ2WDecompressBad,
BZ2WDecompressEof,
};
BZ2WDecompressResult BZ2WDecompress(std::vector<char> &dest, const char *srcData, size_t srcSize, size_t maxSize = 0);
BZ2WDecompressResult BZ2WDecompress(std::vector<char> &dest, std::span<const char> srcData, size_t maxSize = 0);

View File

@@ -500,7 +500,7 @@ void GameSave::readOPS(const std::vector<char> &data)
{
std::vector<char> bsonData;
switch (auto status = BZ2WDecompress(bsonData, (char *)(inputData + 12), inputDataLen - 12, toAlloc))
switch (auto status = BZ2WDecompress(bsonData, std::span(reinterpret_cast<const char *>(inputData + 12), inputDataLen - 12), toAlloc))
{
case BZ2WDecompressOk: break;
case BZ2WDecompressNomem: throw ParseException(ParseException::Corrupt, "Cannot allocate memory");
@@ -1393,7 +1393,7 @@ void GameSave::readPSv(const std::vector<char> &dataVec)
throw ParseException(ParseException::InvalidDimensions, "Save data too large");
std::vector<char> bsonData;
switch (auto status = BZ2WDecompress(bsonData, (char *)(saveData + 12), dataLength - 12, size))
switch (auto status = BZ2WDecompress(bsonData, std::span(reinterpret_cast<const char *>(saveData + 12), dataLength - 12), size))
{
case BZ2WDecompressOk: break;
case BZ2WDecompressNomem: throw ParseException(ParseException::Corrupt, "Cannot allocate memory");
@@ -2632,7 +2632,7 @@ std::pair<bool, std::vector<char>> GameSave::serialiseOPS() const
std::vector<char> outputData;
switch (auto status = BZ2WCompress(outputData, (char *)finalData, finalDataLen))
switch (auto status = BZ2WCompress(outputData, std::span(reinterpret_cast<const char *>(finalData), finalDataLen)))
{
case BZ2WCompressOk: break;
case BZ2WCompressNomem: throw BuildException(String::Build("Save error, out of memory"));

View File

@@ -13,7 +13,7 @@ namespace http
{
auto [ status, data ] = Request::Finish();
ParseResponse(data, status, responseData);
auto vb = VideoBuffer::FromPNG(std::vector<char>(data.begin(), data.end()));
auto vb = VideoBuffer::FromPNG(data);
if (vb)
{
vb->Resize(requestedSize, true);

View File

@@ -67,7 +67,7 @@ bool ReadFile(std::vector<char> &fileData, ByteString filename)
return true;
}
bool WriteFile(const std::vector<char> &fileData, ByteString filename)
bool WriteFile(std::span<const char> fileData, ByteString filename)
{
auto replace = FileExists(filename);
auto writeFileName = filename;

View File

@@ -106,7 +106,7 @@ ByteString ExecutableName()
return DefaultDdir() + "/" + ExecutableNameFirstApprox(); // bogus
}
bool UpdateStart(const std::vector<char> &data)
bool UpdateStart(std::span<const char> data)
{
return false;
}

View File

@@ -92,13 +92,14 @@ bool Install()
if (ok)
{
ByteString desktopData(powder_desktop, powder_desktop + powder_desktop_size);
auto data = powder_desktop.AsCharSpan();
ByteString desktopData(data.begin(), data.end());
auto exe = Platform::ExecutableName();
auto path = exe.SplitFromEndBy('/').Before();
desktopData = desktopData.Substitute("Exec=" + ByteString(APPEXE), "Exec=" + desktopEscapeString(desktopEscapeExec(exe)));
desktopData += ByteString::Build("Path=", desktopEscapeString(path), "\n");
ByteString file = ByteString::Build(APPVENDOR, "-", APPID, ".desktop");
ok = ok && Platform::WriteFile(std::vector<char>(desktopData.begin(), desktopData.end()), file);
ok = ok && Platform::WriteFile(desktopData, file);
ok = ok && !system(ByteString::Build("xdg-desktop-menu install ", file).c_str());
ok = ok && !system(ByteString::Build("xdg-mime default ", file, " application/vnd.powdertoy.save").c_str());
ok = ok && !system(ByteString::Build("xdg-mime default ", file, " x-scheme-handler/ptsave").c_str());
@@ -107,21 +108,21 @@ bool Install()
if (ok)
{
ByteString file = ByteString(APPVENDOR) + "-save.xml";
ok = ok && Platform::WriteFile(std::vector<char>(save_xml, save_xml + save_xml_size), file);
ok = ok && Platform::WriteFile(save_xml.AsCharSpan(), file);
ok = ok && !system(ByteString::Build("xdg-mime install ", file).c_str());
Platform::RemoveFile(file);
}
if (ok)
{
ByteString file = ByteString(APPVENDOR) + "-cps.png";
ok = ok && Platform::WriteFile(std::vector<char>(icon_cps_png, icon_cps_png + icon_cps_png_size), file);
ok = ok && Platform::WriteFile(icon_cps_png.AsCharSpan(), file);
ok = ok && !system(ByteString::Build("xdg-icon-resource install --noupdate --context mimetypes --size 64 ", file, " application-vnd.powdertoy.save").c_str());
Platform::RemoveFile(file);
}
if (ok)
{
ByteString file = ByteString(APPVENDOR) + "-exe.png";
ok = ok && Platform::WriteFile(std::vector<char>(icon_exe_png, icon_exe_png + icon_exe_png_size), file);
ok = ok && Platform::WriteFile(icon_exe_png.AsCharSpan(), file);
ok = ok && !system(ByteString::Build("xdg-icon-resource install --noupdate --size 64 ", file, " ", APPVENDOR, "-", APPEXE).c_str());
Platform::RemoveFile(file);
}

View File

@@ -1,6 +1,7 @@
#pragma once
#include "common/String.h"
#include <cstdint>
#include <span>
#include <string>
#include <vector>
#include <optional>
@@ -40,7 +41,7 @@ namespace Platform
std::vector<ByteString> DirectorySearch(ByteString directory, ByteString search, std::vector<ByteString> extensions);
bool ReadFile(std::vector<char> &fileData, ByteString filename);
bool WriteFile(const std::vector<char> &fileData, ByteString filename);
bool WriteFile(std::span<const char> fileData, ByteString filename);
// TODO: Remove these and switch to *A Win32 API variants when we stop fully supporting windows
// versions older than win10 1903, for example when win10 reaches EOL, see 18084d5aa0e5.
@@ -56,7 +57,7 @@ namespace Platform
bool ChangeDir(ByteString toDir);
bool UpdateStart(const std::vector<char> &data);
bool UpdateStart(std::span<const char> data);
bool UpdateFinish();
void UpdateCleanup();

View File

@@ -37,7 +37,7 @@ ByteString ExecutableName()
return rp.get();
}
bool UpdateStart(const std::vector<char> &data)
bool UpdateStart(std::span<const char> data)
{
ByteString exeName = Platform::ExecutableName();

View File

@@ -309,7 +309,7 @@ bool Install()
return ok;
}
bool UpdateStart(const std::vector<char> &data)
bool UpdateStart(std::span<const char> data)
{
ByteString exeName = Platform::ExecutableName(), updName;

View File

@@ -23,7 +23,7 @@ static bool InitFontData()
static std::vector<char> fontDataBuf;
static std::vector<int> fontPtrsBuf;
static std::vector< std::array<int, 2> > fontRangesBuf;
if (BZ2WDecompress(fontDataBuf, reinterpret_cast<const char *>(compressed_font_data), compressed_font_data_size) != BZ2WDecompressOk)
if (BZ2WDecompress(fontDataBuf, compressed_font_data.AsCharSpan()) != BZ2WDecompressOk)
{
return false;
}

View File

@@ -142,7 +142,7 @@ void VideoBuffer::ResizeToFit(Vec2<int> bound, bool resample)
Resize(size, resample);
}
std::unique_ptr<VideoBuffer> VideoBuffer::FromPNG(std::vector<char> const &data)
std::unique_ptr<VideoBuffer> VideoBuffer::FromPNG(std::span<const char> data)
{
auto video = format::PixelsFromPNG(data, 0x000000_rgb);
if (video)

View File

@@ -1,6 +1,7 @@
#pragma once
#include <array>
#include <memory>
#include <span>
#include <vector>
#include "common/Plane.h"
#include "common/String.h"
@@ -53,7 +54,7 @@ public:
// Automatically choose a size to fit within the given box, keeping aspect ratio
void ResizeToFit(Vec2<int> bound, bool resample = false);
static std::unique_ptr<VideoBuffer> FromPNG(std::vector<char> const &);
static std::unique_ptr<VideoBuffer> FromPNG(std::span<const char> data);
std::unique_ptr<std::vector<char>> ToPNG() const;
std::vector<char> ToPPM() const;
};

View File

@@ -34,7 +34,7 @@ void FontEditor::ReadDataFile(ByteString dataFile)
std::vector<char> fontDataBuf;
std::vector<int> fontPtrsBuf;
std::vector< std::array<int, 2> > fontRangesBuf;
if (BZ2WDecompress(fontDataBuf, fileData.data(), fileData.size()) != BZ2WDecompressOk)
if (BZ2WDecompress(fontDataBuf, fileData) != BZ2WDecompressOk)
{
throw std::runtime_error("Could not decompress font data");
}
@@ -131,7 +131,7 @@ void FontEditor::WriteDataFile(ByteString dataFile, std::vector<unsigned char> c
}
std::vector<char> compressed;
if (BZ2WCompress(compressed, uncompressed.data(), uncompressed.size()) != BZ2WCompressOk)
if (BZ2WCompress(compressed, uncompressed) != BZ2WCompressOk)
{
throw std::runtime_error("Could not compress font data");
}

View File

@@ -23,9 +23,7 @@ class ThumbnailRendererTask;
class LocalSaveActivity: public WindowActivity
{
using OnSaved = std::function<void (std::unique_ptr<SaveFile>)>;
std::unique_ptr<PlaneAdapter<std::vector<pixel_rgba>>> saveToDiskImage = format::PixelsFromPNG(
std::vector<char>(save_local_png, save_local_png + save_local_png_size)
);
std::unique_ptr<PlaneAdapter<std::vector<pixel_rgba>>> saveToDiskImage = format::PixelsFromPNG(save_local_png.AsCharSpan());
std::unique_ptr<SaveFile> save;
ThumbnailRendererTask *thumbnailRenderer;

View File

@@ -33,9 +33,7 @@ class ServerSaveActivity: public WindowActivity, public TaskListener
std::unique_ptr<http::UploadSaveRequest> uploadSaveRequest;
using OnUploaded = std::function<void (std::unique_ptr<SaveInfo>)>;
std::unique_ptr<PlaneAdapter<std::vector<pixel_rgba>>> saveToServerImage = format::PixelsFromPNG(
std::vector<char>(save_online_png, save_online_png + save_online_png_size)
);
std::unique_ptr<PlaneAdapter<std::vector<pixel_rgba>>> saveToServerImage = format::PixelsFromPNG(save_online_png.AsCharSpan());
public:
ServerSaveActivity(std::unique_ptr<SaveInfo> newSave, OnUploaded onUploaded);

View File

@@ -6,7 +6,7 @@ static int compress(lua_State *L)
auto src = tpt_lua_checkByteString(L, 1);
auto maxSize = size_t(luaL_optinteger(L, 2, 0));
std::vector<char> dest;
auto result = BZ2WCompress(dest, src.data(), src.size(), maxSize);
auto result = BZ2WCompress(dest, src, maxSize);
#define RETURN_ERR(str) lua_pushnil(L); lua_pushinteger(L, int(result)); lua_pushliteral(L, str); return 3
switch (result)
{
@@ -24,7 +24,7 @@ static int decompress(lua_State *L)
auto src = tpt_lua_checkByteString(L, 1);
auto maxSize = size_t(luaL_optinteger(L, 2, 0));
std::vector<char> dest;
auto result = BZ2WDecompress(dest, src.data(), src.size(), maxSize);
auto result = BZ2WDecompress(dest, src, maxSize);
#define RETURN_ERR(str) lua_pushnil(L); lua_pushinteger(L, int(result)); lua_pushliteral(L, str); return 3
switch (result)
{

View File

@@ -96,7 +96,7 @@ void LuaMisc::Tick(lua_State *L)
return;
}
ByteString filename = "autorun.lua";
if (!Platform::WriteFile(std::vector<char>(scriptData.begin(), scriptData.end()), filename))
if (!Platform::WriteFile(scriptData, filename))
{
complete({ Status::GetFailed{ String::Build("Unable to write to ", filename.FromUtf8()) } });
return;
@@ -177,7 +177,8 @@ static int record(lua_State *L)
static int compatChunk(lua_State *L)
{
lua_pushlstring(L, reinterpret_cast<const char *>(compat_lua), compat_lua_size);
auto data = compat_lua.AsCharSpan();
lua_pushlstring(L, data.data(), data.size());
return 1;
}
static int debug(lua_State *L)

View File

@@ -176,7 +176,8 @@ LuaScriptInterface::LuaScriptInterface(GameController *newGameController, GameMo
ref.Assign(L, -1);
lua_pop(L, 1);
}
if (luaL_loadbuffer(L, (const char *)compat_lua, compat_lua_size, "@[built-in compat.lua]") || tpt_lua_pcall(L, 0, 0, 0, eventTraitNone))
auto compatSpan = compat_lua.AsCharSpan();
if (luaL_loadbuffer(L, compatSpan.data(), compatSpan.size(), "@[built-in compat.lua]") || tpt_lua_pcall(L, 0, 0, 0, eventTraitNone))
{
throw std::runtime_error(ByteString("failed to load built-in compat: ") + tpt_lua_toByteString(L, -1));
}

View File

@@ -53,7 +53,7 @@ void Prefs::Write()
Json::StreamWriterBuilder wbuilder;
wbuilder["indentation"] = "\t";
ByteString data = Json::writeString(wbuilder, root);
if (!Platform::WriteFile(std::vector<char>(data.begin(), data.end()), path))
if (!Platform::WriteFile(data, path))
{
return;
}