Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
emscripten-core
GitHub Repository: emscripten-core/emscripten
Path: blob/main/system/lib/wasmfs/pipe_backend.h
6174 views
1
// Copyright 2022 The Emscripten Authors. All rights reserved.
2
// Emscripten is available under two separate licenses, the MIT license and the
3
// University of Illinois/NCSA Open Source License. Both these licenses can be
4
// found in the LICENSE file.
5
6
#pragma once
7
8
#include <queue>
9
10
#include "file.h"
11
#include "support.h"
12
13
namespace wasmfs {
14
15
// The data shared between the two sides of a pipe.
16
// TODO: Consider switching to a ring buffer for performance and code size if we
17
// don't need unbounded pipes.
18
using PipeData = std::queue<uint8_t>;
19
20
// A PipeFile is a simple file that has a reference to a PipeData that it
21
// either reads from or writes to. A pair of PipeFiles comprise the two ends of
22
// a pipe.
23
class PipeFile : public DataFile {
24
std::shared_ptr<PipeData> data;
25
26
int open(oflags_t) override { return 0; }
27
int close() override { return 0; }
28
29
ssize_t write(const uint8_t* buf, size_t len, off_t offset) override {
30
for (size_t i = 0; i < len; i++) {
31
data->push(buf[i]);
32
}
33
return len;
34
}
35
36
ssize_t read(uint8_t* buf, size_t len, off_t offset) override {
37
for (size_t i = 0; i < len; i++) {
38
if (data->empty()) {
39
return i;
40
}
41
buf[i] = data->front();
42
data->pop();
43
}
44
return len;
45
}
46
47
int flush() override { return 0; }
48
49
off_t getSize() override { return data->size(); }
50
51
// TODO: Should this return an error?
52
int setSize(off_t size) override { return 0; }
53
54
public:
55
// PipeFiles do not have or need a backend. Pass NullBackend to the parent for
56
// that.
57
PipeFile(mode_t mode, std::shared_ptr<PipeData> data)
58
: DataFile(mode, NullBackend), data(data) {
59
// Reads are always from the front; writes always to the end.
60
seekable = false;
61
}
62
};
63
} // namespace wasmfs
64
65