Roll src/third_party/WebKit d9c6159:8139f33 (svn 201974:201975)
[chromium-blink-merge.git] / chrome / utility / safe_browsing / mac / read_stream.h
blob507a33c0914d8dfaa80cf6e2f5df29f879de2f8c
1 // Copyright 2015 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 CHROME_UTILITY_SAFE_BROWSING_MAC_READ_STREAM_H_
6 #define CHROME_UTILITY_SAFE_BROWSING_MAC_READ_STREAM_H_
8 #include <stdint.h>
9 #include <unistd.h>
11 #include "base/macros.h"
13 namespace safe_browsing {
14 namespace dmg {
16 // An interface for reading and seeking over a byte stream.
17 class ReadStream {
18 public:
19 virtual ~ReadStream() {}
21 // Copies up to |size| bytes into |data|. Returns |true| on success with the
22 // actual number of bytes written stored in |size|. Returns |false| on error.
23 // At end-of-stream, returns |true| with |bytes_read| set to 0.
24 virtual bool Read(uint8_t* data, size_t size, size_t* bytes_read) = 0;
26 // Calls |Read| but only returns true if the number of bytes read equals
27 // |size|.
28 bool ReadExact(uint8_t* data, size_t size);
30 template <typename T>
31 bool ReadType(T* t) {
32 return ReadExact(reinterpret_cast<uint8_t*>(t), sizeof(T));
35 // Seeks the read stream to |offset| from |whence|. |whence| is a POSIX-style
36 // SEEK_ constant. Returns the resulting offset location, or a negative value
37 // on failure.
38 virtual off_t Seek(off_t offset, int whence) = 0;
41 // An implementation of ReadStream backed by a file descriptor. This does not
42 // take ownership of the file descriptor.
43 class FileReadStream : public ReadStream {
44 public:
45 explicit FileReadStream(int fd);
46 ~FileReadStream() override;
48 // ReadStream:
49 bool Read(uint8_t* data, size_t size, size_t* bytes_read) override;
50 off_t Seek(off_t offset, int whence) override;
52 private:
53 int fd_;
55 DISALLOW_COPY_AND_ASSIGN(FileReadStream);
58 // An implementation of ReadStream that operates on a byte buffer. This class
59 // does not take ownership of the underlying byte array.
60 class MemoryReadStream : public ReadStream {
61 public:
62 MemoryReadStream(const uint8_t* data, size_t size);
63 ~MemoryReadStream() override;
65 // ReadStream:
66 bool Read(uint8_t* data, size_t size, size_t* bytes_read) override;
67 off_t Seek(off_t offset, int whence) override;
69 const uint8_t* data() const { return data_; }
70 size_t size() const { return size_; }
72 protected:
73 const uint8_t* data_;
74 size_t size_;
75 off_t offset_;
77 private:
78 DISALLOW_COPY_AND_ASSIGN(MemoryReadStream);
81 } // namespace dmg
82 } // namespace safe_browsing
84 #endif // CHROME_UTILITY_SAFE_BROWSING_MAC_READ_STREAM_H_