libos: Add File::read_all() and File::read_all_as_string()
This commit is contained in:
parent
5b69ce554c
commit
fb09eb97ce
@ -34,8 +34,10 @@ namespace os
|
||||
Result<void> write(const Buffer& buf);
|
||||
|
||||
Result<String> read_line();
|
||||
Result<String> read_all_as_string();
|
||||
|
||||
Result<void> read(Buffer& buf, usize size);
|
||||
Result<Buffer> read_all();
|
||||
|
||||
Result<int> getchar();
|
||||
|
||||
|
@ -131,6 +131,36 @@ namespace os
|
||||
return String::from_cstring(data.data());
|
||||
}
|
||||
|
||||
Result<String> File::read_all_as_string()
|
||||
{
|
||||
StringBuilder sb;
|
||||
|
||||
while (true)
|
||||
{
|
||||
auto line = TRY(read_line());
|
||||
if (line.is_empty()) break;
|
||||
TRY(sb.add(line));
|
||||
}
|
||||
|
||||
return sb.string();
|
||||
}
|
||||
|
||||
Result<Buffer> File::read_all()
|
||||
{
|
||||
Vector<u8> data;
|
||||
|
||||
while (true)
|
||||
{
|
||||
int c = TRY(getchar());
|
||||
if (c == -1) break;
|
||||
TRY(data.try_append((u8)c));
|
||||
}
|
||||
|
||||
Buffer buf;
|
||||
TRY(buf.append_data(data.data(), data.size()));
|
||||
return buf;
|
||||
}
|
||||
|
||||
Result<void> File::read(Buffer& buf, usize size)
|
||||
{
|
||||
u8* slice = TRY(buf.slice(0, size));
|
||||
@ -144,9 +174,9 @@ namespace os
|
||||
|
||||
Result<int> File::getchar()
|
||||
{
|
||||
char value;
|
||||
u8 value;
|
||||
|
||||
usize nread = TRY(raw_read((u8*)&value, 1));
|
||||
usize nread = TRY(raw_read(&value, 1));
|
||||
if (!nread) return -1;
|
||||
|
||||
return value;
|
||||
|
Loading…
Reference in New Issue
Block a user