1 /******************************************************************************
2  *
3  *  Copyright (C) 2014 Google, Inc.
4  *
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at:
8  *
9  *  http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  ******************************************************************************/
18 
19 #pragma once
20 
21 #include <stdbool.h>
22 #include <stddef.h>
23 #include <stdint.h>
24 
25 #include "allocator.h"
26 
27 typedef struct eager_reader_t eager_reader_t;
28 typedef struct reactor_t reactor_t;
29 
30 typedef void (*eager_reader_cb)(eager_reader_t *reader, void *context);
31 
32 // Creates a new eager reader object, which pulls data from |fd_to_read| into
33 // buffers of size |buffer_size| allocated using |allocator|, and has an
34 // internal read thread named |thread_name|. The returned object must be freed using
35 // |eager_reader_free|. |fd_to_read| must be valid, |buffer_size| and |max_buffer_count|
36 // must be greater than zero. |allocator| and |thread_name| may not be NULL.
37 eager_reader_t *eager_reader_new(
38   int fd_to_read,
39   const allocator_t *allocator,
40   size_t buffer_size,
41   size_t max_buffer_count,
42   const char *thread_name
43 );
44 
45 // Frees an eager reader object, and associated internal resources.
46 // |reader| may be NULL.
47 void eager_reader_free(eager_reader_t *reader);
48 
49 // Registers |reader| with the |reactor|. When the reader has data
50 // |read_cb| will be called. The |context| parameter is passed, untouched, to |read_cb|.
51 // Neither |reader|, nor |reactor|, nor |read_cb| may be NULL. |context| may be NULL.
52 void eager_reader_register(eager_reader_t *reader, reactor_t *reactor, eager_reader_cb read_cb, void *context);
53 
54 // Unregisters |reader| from whichever reactor it is registered with, if any. This
55 // function is idempotent.
56 void eager_reader_unregister(eager_reader_t *reader);
57 
58 // Reads up to |max_size| bytes into |buffer|. If |block| is true, blocks until
59 // |max_size| bytes are read. Otherwise only reads from currently available bytes.
60 // NOT SAFE FOR READING FROM MULTIPLE THREADS
61 // but you should probably only be reading from one thread anyway,
62 // otherwise the byte stream probably doesn't make sense.
63 size_t eager_reader_read(eager_reader_t *reader, uint8_t *buffer, size_t max_size, bool block);
64