Bare Metal Programming Tool Kit
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Pages
channels.h
Go to the documentation of this file.
1 //***************************************************************************
2 //
3 // file : bmptk/core/channels.h
4 //
5 // LICENSE (MIT expat license, copy of bmptk/license.txt)
6 //
7 // Copyright (c) 2012 Wouter van Ooijen (wouter@voti.nl)
8 //
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
16 //
17 // The above copyright notice and this permission notice shall be included
18 // in all copies or substantial portions of the Software.
19 //
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
23 // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
24 // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
25 // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
26 // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE..
27 //
28 //***************************************************************************
29 
30 // document everything in this file
33 namespace bmptk {
34 
36 template< class t >
38 public:
39 
41  virtual bool put_will_not_block() = 0;
42 
44  //
49  virtual void put( t ) = 0;
50 };
51 
53 template< class t >
55 public:
56 
58  virtual bool get_will_not_block() = 0;
59 
61  //
66  virtual t get() = 0;
67 };
68 
70 template< class t >
72  public output_channel_polled< t >, input_channel_polled< t >{};
73 
75 //
79 template< class t, int buffer_size>
81 private:
83  t buffer[ buffer_size ];
84  int read_index;
85  int write_index;
86  int overflows;
87  int n_buffered;
88 public:
89 
93  ):
94  output( output ),
95  read_index( 0 ),
96  write_index( 0 ),
97  overflows( 0 ),
98  n_buffered( 0 )
99  {}
100 
102  void put( t c ){
103  if( n_buffered < buffer_size ){
104  buffer[ write_index ] = c;
105  if( ++write_index == buffer_size ){
106  write_index = 0;
107  }
108  n_buffered++;
109  } else {
110  overflows++;
111  }
112  }
113 
116  return true;
117  }
118 
120  //
123  void poll(){
124  if( ( n_buffered > 0 ) && output.put_will_not_block() ){
125  output.put( buffer[ read_index ] );
126  if( ++read_index == buffer_size ){
127  read_index = 0;
128  }
129  n_buffered--;
130  }
131  }
132 };
133 
134 
135 }; // namespace bmptk;