1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef DEVICE_SERIAL_BUFFER_H_
6 #define DEVICE_SERIAL_BUFFER_H_
10 #include "base/callback.h"
11 #include "net/base/io_buffer.h"
12 #include "services/device/public/mojom/serial.mojom.h"
16 // A fixed-size read-only buffer. The data-reader should call Done() when it is
17 // finished reading bytes from the buffer. Alternatively, the reader can report
18 // an error by calling DoneWithError() with the number of bytes read and the
19 // error it wishes to report.
20 class ReadOnlyBuffer {
22 virtual ~ReadOnlyBuffer();
23 virtual const uint8_t* GetData() = 0;
24 virtual uint32_t GetSize() = 0;
25 virtual void Done(uint32_t bytes_read) = 0;
26 virtual void DoneWithError(uint32_t bytes_read, int32_t error) = 0;
29 // A fixed-size writable buffer. The data-writer should call Done() when it is
30 // finished writing bytes to the buffer. Alternatively, the writer can report
31 // an error by calling DoneWithError() with the number of bytes written and the
32 // error it wishes to report.
33 class WritableBuffer {
35 virtual ~WritableBuffer();
36 virtual char* GetData() = 0;
37 virtual uint32_t GetSize() = 0;
38 virtual void Done(uint32_t bytes_written) = 0;
39 virtual void DoneWithError(uint32_t bytes_written, int32_t error) = 0;
42 // A useful basic implementation of a ReadOnlyBuffer in which the data is
43 // initialized via a character vector.
44 class SendBuffer : public device::ReadOnlyBuffer {
46 using SendCompleteCallback =
47 base::OnceCallback<void(int, device::mojom::SerialSendError)>;
48 SendBuffer(const std::vector<uint8_t>& data, SendCompleteCallback callback);
49 ~SendBuffer() override;
51 const uint8_t* GetData() override;
52 uint32_t GetSize() override;
53 void Done(uint32_t bytes_read) override;
54 void DoneWithError(uint32_t bytes_read, int32_t error) override;
57 const std::vector<uint8_t> data_;
58 SendCompleteCallback callback_;
61 // A useful basic implementation of a WritableBuffer in which the data is
62 // stored in a net::IOBuffer.
63 class ReceiveBuffer : public device::WritableBuffer {
65 using ReceiveCompleteCallback =
66 base::OnceCallback<void(int, device::mojom::SerialReceiveError)>;
67 ReceiveBuffer(scoped_refptr<net::IOBuffer> buffer,
69 ReceiveCompleteCallback callback);
70 ~ReceiveBuffer() override;
72 char* GetData() override;
73 uint32_t GetSize() override;
74 void Done(uint32_t bytes_written) override;
75 void DoneWithError(uint32_t bytes_written, int32_t error) override;
78 scoped_refptr<net::IOBuffer> buffer_;
80 ReceiveCompleteCallback callback_;
85 #endif // DEVICE_SERIAL_BUFFER_H_