Skip to content

Commit a62a07c

Browse files
committed
Avoid copying in ZipReader::readFileToString()
Resolves: #290
1 parent 8a33224 commit a62a07c

File tree

4 files changed

+11
-10
lines changed

4 files changed

+11
-10
lines changed

src/internal/scratch3reader.cpp

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -558,7 +558,9 @@ void Scratch3Reader::read()
558558
if (m_zipReader->open()) {
559559
// Parse the JSON
560560
try {
561-
m_json = json::parse(m_zipReader->readFileToString("project.json"));
561+
std::string jsonStr;
562+
m_zipReader->readFileToString("project.json", jsonStr);
563+
m_json = json::parse(jsonStr);
562564
} catch (std::exception &e) {
563565
printErr("invalid JSON file", e.what());
564566
}

src/internal/zipreader.cpp

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -48,17 +48,14 @@ size_t ZipReader::readFile(const std::string &fileName, void **buf)
4848
return bufsize;
4949
}
5050

51-
std::string ZipReader::readFileToString(const std::string &fileName)
51+
void ZipReader::readFileToString(const std::string &fileName, std::string &dst)
5252
{
5353
void *buf = nullptr;
5454
size_t bufsize = readFile(fileName, &buf);
5555

5656
if (buf) {
57-
std::string ret(reinterpret_cast<char *>(buf), bufsize);
57+
dst.assign(reinterpret_cast<char *>(buf), bufsize);
5858
free(buf);
59-
60-
return ret;
61-
}
62-
63-
return "";
59+
} else
60+
dst = "";
6461
}

src/internal/zipreader.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ class ZipReader
2020
void close();
2121

2222
size_t readFile(const std::string &fileName, void **buf);
23-
std::string readFileToString(const std::string &fileName);
23+
void readFileToString(const std::string &fileName, std::string &dst);
2424

2525
private:
2626
std::string m_fileName;

test/zip/zip_test.cpp

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@ inline std::string readSb3Json(const std::string &fileName)
88
ZipReader reader(fileName);
99
reader.open();
1010

11-
return reader.readFileToString("project.json");
11+
std::string ret;
12+
reader.readFileToString("project.json", ret);
13+
return ret;
1214
}
1315

1416
TEST(ZipTest, NonexistentProject)

0 commit comments

Comments
 (0)