AERA
submodules/CoreLibrary/CoreLibrary/utils.h
1 //_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
2 //_/_/
3 //_/_/ AERA
4 //_/_/ Autocatalytic Endogenous Reflective Architecture
5 //_/_/
6 //_/_/ Copyright (c) 2018-2021 Jeff Thompson
7 //_/_/ Copyright (c) 2018-2021 Kristinn R. Thorisson
8 //_/_/ Copyright (c) 2018-2021 Icelandic Institute for Intelligent Machines
9 //_/_/ http://www.iiim.is
10 //_/_/
11 //_/_/ Copyright (c) 2010-2012 Eric Nivel, Thor List
12 //_/_/ Center for Analysis and Design of Intelligent Agents
13 //_/_/ Reykjavik University, Menntavegur 1, 102 Reykjavik, Iceland
14 //_/_/ http://cadia.ru.is
15 //_/_/
16 //_/_/ Part of this software was developed by Eric Nivel
17 //_/_/ in the HUMANOBS EU research project, which included
18 //_/_/ the following parties:
19 //_/_/
20 //_/_/ Autonomous Systems Laboratory
21 //_/_/ Technical University of Madrid, Spain
22 //_/_/ http://www.aslab.org/
23 //_/_/
24 //_/_/ Communicative Machines
25 //_/_/ Edinburgh, United Kingdom
26 //_/_/ http://www.cmlabs.com/
27 //_/_/
28 //_/_/ Istituto Dalle Molle di Studi sull'Intelligenza Artificiale
29 //_/_/ University of Lugano and SUPSI, Switzerland
30 //_/_/ http://www.idsia.ch/
31 //_/_/
32 //_/_/ Institute of Cognitive Sciences and Technologies
33 //_/_/ Consiglio Nazionale delle Ricerche, Italy
34 //_/_/ http://www.istc.cnr.it/
35 //_/_/
36 //_/_/ Dipartimento di Ingegneria Informatica
37 //_/_/ University of Palermo, Italy
38 //_/_/ http://diid.unipa.it/roboticslab/
39 //_/_/
40 //_/_/
41 //_/_/ --- HUMANOBS Open-Source BSD License, with CADIA Clause v 1.0 ---
42 //_/_/
43 //_/_/ Redistribution and use in source and binary forms, with or without
44 //_/_/ modification, is permitted provided that the following conditions
45 //_/_/ are met:
46 //_/_/ - Redistributions of source code must retain the above copyright
47 //_/_/ and collaboration notice, this list of conditions and the
48 //_/_/ following disclaimer.
49 //_/_/ - Redistributions in binary form must reproduce the above copyright
50 //_/_/ notice, this list of conditions and the following disclaimer
51 //_/_/ in the documentation and/or other materials provided with
52 //_/_/ the distribution.
53 //_/_/
54 //_/_/ - Neither the name of its copyright holders nor the names of its
55 //_/_/ contributors may be used to endorse or promote products
56 //_/_/ derived from this software without specific prior
57 //_/_/ written permission.
58 //_/_/
59 //_/_/ - CADIA Clause: The license granted in and to the software
60 //_/_/ under this agreement is a limited-use license.
61 //_/_/ The software may not be used in furtherance of:
62 //_/_/ (i) intentionally causing bodily injury or severe emotional
63 //_/_/ distress to any person;
64 //_/_/ (ii) invading the personal privacy or violating the human
65 //_/_/ rights of any person; or
66 //_/_/ (iii) committing or preparing for any act of war.
67 //_/_/
68 //_/_/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
69 //_/_/ CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
70 //_/_/ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
71 //_/_/ MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
72 //_/_/ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
73 //_/_/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
74 //_/_/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
75 //_/_/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
76 //_/_/ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
77 //_/_/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
78 //_/_/ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
79 //_/_/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
80 //_/_/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
81 //_/_/ OF SUCH DAMAGE.
82 //_/_/
83 //_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
84 
85 #ifndef core_utils_h
86 #define core_utils_h
87 
88 #include "types.h"
89 #include <stdio.h>
90 
91 #include <iostream>
92 #include <string>
93 
94 #if defined WINDOWS
95 #include <sys/timeb.h>
96 #include <time.h>
97 #elif defined LINUX
98 #include <dlfcn.h>
99 #include <errno.h>
100 #include <sys/utsname.h>
101 #include <sys/time.h>
102 #include <cstring>
103 #include <cstdlib>
104 #include <pthread.h>
105 #include <signal.h>
106 #include <sys/time.h>
107 #include <unistd.h>
108 #include <time.h>
109 // #undef HANDLE
110 // #define HANDLE pthread_cond_t*
111 #endif
112 
113 #ifdef WINDOWS
114 #define SOCKETWOULDBLOCK WSAEWOULDBLOCK
115 #else
116 #define SOCKETWOULDBLOCK EWOULDBLOCK
117 #endif
118 
119 #ifndef SD_BOTH
120 #define SD_BOTH 2
121 #endif
122 
123 #define R250_LEN 250
124 #define R521_LEN 521
125 
126 // Wrapping of OS-dependent functions
127 namespace core {
128 
129 bool core_dll WaitForSocketReadability(socket s, int32 timeout);
130 bool core_dll WaitForSocketWriteability(socket s, int32 timeout);
131 
132 class core_dll Error {
133 public:
134  static int32 GetLastOSErrorNumber();
135  static bool GetOSErrorMessage(char* buffer, uint32 buflen, int32 err = -1);
136  static bool PrintLastOSErrorMessage(const char* title);
137  static void PrintBinary(void* p, uint32 size, bool asInt, const char* title = NULL);
138 };
139 
140 #if defined WINDOWS
141 #elif defined LINUX
142 struct SemaTex {
143  pthread_mutex_t mutex;
144  pthread_cond_t semaphore;
145 };
146 #endif
147 
148 class core_dll SharedLibrary {
149 private:
150  shared_object library_;
151 public:
152  static SharedLibrary *New(const char *fileName);
153  SharedLibrary();
154  ~SharedLibrary();
155  SharedLibrary *load(const char *fileName);
156  template<typename T> T getFunction(const char *functionName);
157 };
158 
159 class core_dll Thread {
160 private:
161  thread thread_;
162  bool is_meaningful_;
163 protected:
164  Thread();
165 public:
166  template<class T> static T *New(thread_function f, void *args);
167  static void TerminateAndWait(Thread **threads, uint32 threadCount);
168  static void TerminateAndWait(Thread *thread);
169  static void Wait(Thread **threads, uint32 threadCount);
170  static void Wait(Thread *thread);
171  static void Sleep(std::chrono::milliseconds ms);
172  static void Sleep(std::chrono::system_clock::duration ms) { Sleep(std::chrono::duration_cast<std::chrono::milliseconds>(ms)); }
173  static void Sleep(); // inifnite
174  virtual ~Thread();
175  void start(thread_function f);
176  void suspend();
177  void resume();
178  void terminate();
179 };
180 
181 class core_dll TimeProbe { // requires Time::Init()
182 private:
183  int64 cpu_counts_;
184  int64 getCounts();
185 public:
186  void set(); // initialize
187  void check(); // gets the cpu count elapsed between set() and check()
188 };
189 
190 class core_dll Time { // TODO: make sure time stamps are consistent when computed by different cores
191  friend class TimeProbe;
192 private:
193  static float64 Period_;
194  static Timestamp InitTime_;
195 public:
196  static void Init(uint32 r); // detects the hardware timing capabilities; r: time resolution in us (on windows xp: max ~1000; use 1000, 2000, 5000 or 10000)
197  static Timestamp Get(); // timestamp since 01/01/1970
198 
199  static std::string ToString_seconds(Timestamp::duration duration); // seconds:milliseconds:microseconds.
200  static std::string ToString_year(Timestamp timestamp); // day_name day_number month year hour:minutes:seconds:milliseconds:microseconds GMT since 01/01/1970.
201 };
202 
203 class core_dll Host {
204 public:
205  typedef char host_name[255];
206  static uint8 Name(char *name); // name size=255; return the actual size
207 };
208 
209 class core_dll Semaphore {
210 private:
211  semaphore s_;
212 protected:
213  static const uint32 Infinite;
214 public:
215  Semaphore(uint32 initialCount, uint32 maxCount);
216  ~Semaphore();
217  bool acquire(uint32 timeout = Infinite); // returns true if timedout
218  void release(uint32 count = 1);
219  void reset();
220 };
221 
222 class core_dll Mutex {
223 private:
224  mutex m_;
225 protected:
226  static const uint32 Infinite;
227 public:
228  Mutex();
229  ~Mutex();
230  bool acquire(uint32 timeout = Infinite); // returns true if timedout
231  void release();
232 };
233 
234 class core_dll CriticalSection {
235 private:
236  critical_section cs_;
237 public:
238  CriticalSection();
239  ~CriticalSection();
240  void enter();
241  void leave();
242 };
243 
244 class core_dll Timer {
245 private:
246 #if defined WINDOWS
247  timer t_;
248 #elif defined LINUX
249  timer_t timer;
250  struct SemaTex sematex;
251 #endif
252 protected:
253  static const uint32 Infinite;
254 public:
255  Timer();
256  ~Timer();
257  void start(std::chrono::microseconds deadline, std::chrono::milliseconds period = std::chrono::seconds(0)); // deadline in us, period in ms.
258  bool wait(uint32 timeout = Infinite); // timeout in ms; returns true if timedout.
259 };
260 
261 class core_dll Event {
262 private:
263 #if defined WINDOWS
264  event e_;
265 #elif defined LINUX
266  // TODO.
267 #endif
268 public:
269  Event();
270  ~Event();
271  void wait();
272  void fire();
273  void reset();
274 };
275 
276 class core_dll SignalHandler {
277 public:
278  static void Add(signal_handler h);
279  static void Remove(signal_handler h);
280 };
281 
282 class core_dll Atomic {
283 public:
284  static int32 Increment32(int32 volatile *v); // return the final value of *v
285  static int32 Decrement32(int32 volatile *v); // return the final value of *v
286  static int32 CompareAndSwap32(int32 volatile *target, int32 v1, int32 v2); // compares *target with v1, if equal, replace it with v2; return the initial value of *target
287  static int64 CompareAndSwap64(int64 volatile *target, int64 v1, int64 v2);
288  // static word CompareAndSwap(word volatile *target,word v1,word v2); // uses the right version according to ARCH_xx
289  static int32 Swap32(int32 volatile *target, int32 v); // writes v at target; return the initial value of *target
290  static int64 Swap64(int64 volatile *target, int64 v); // ifndef ARCH_64, calls CompareAndSwap64(target,v,v)
291 // static word Swap(word volatile *target,word v); // uses the right version according to ARCH_xx
292 #if defined ARCH_64
293  static int64 Increment64(int64 volatile *v);
294  static int64 Decrement64(int64 volatile *v);
295  static int32 Add32(int32 volatile *target, int32 v); // adds v to *target; return the final value of *target
296  static int64 Add64(int64 volatile *target, int64 v);
297 #endif
298 };
299 
300 uint8 core_dll BSR(word data); // BitScanReverse
301 
302 class core_dll FastSemaphore : // lock-free under no contention
303  public Semaphore {
304 private:
305  int32 volatile count_; // minus the number of waiting threads
306  const int32 maxCount_; // max number of threads allowed to run
307 public:
308  FastSemaphore(uint32 initialCount, uint32 maxCount); // initialCount >=0
309  ~FastSemaphore();
310  void acquire();
311  void release();
312 };
313 
314 class core_dll String {
315 public:
316  static int32 StartsWith(const std::string &s, const std::string &str);
317  static int32 EndsWith(const std::string &s, const std::string &str);
318  static void MakeUpper(std::string &str);
319  static void MakeLower(std::string &str);
320  static void Trim(std::string& str, const char* chars2remove = " ");
321  static void TrimLeft(std::string& str, const char* chars2remove = " ");
322  static void TrimRight(std::string& str, const char* chars2remove = " ");
323  static void ReplaceLeading(std::string& str, const char* chars2replace, char c);
324 };
325 
326 class core_dll Random {
327 private:
328  static int32 r250_index_;
329  static int32 r521_index_;
330  static uint32 r250_buffer_[R250_LEN];
331  static uint32 r521_buffer_[R521_LEN];
332 public:
333  static void Init();
334 
335  float32 operator ()(uint32 range); // returns a value in [0,range].
336 };
337 }
338 
339 #include "utils.tpl.cpp"
340 
341 
342 #endif
core::Error
Definition: submodules/CoreLibrary/CoreLibrary/utils.h:132
core::TimeProbe
Definition: submodules/CoreLibrary/CoreLibrary/utils.h:181
core::Random
Definition: submodules/CoreLibrary/CoreLibrary/utils.h:326
core::Timer
Definition: submodules/CoreLibrary/CoreLibrary/utils.h:244
core::Time
Definition: submodules/CoreLibrary/CoreLibrary/utils.h:190
core::SharedLibrary
Definition: submodules/CoreLibrary/CoreLibrary/utils.h:148
core::SignalHandler
Definition: submodules/CoreLibrary/CoreLibrary/utils.h:276
core::Thread
Definition: submodules/CoreLibrary/CoreLibrary/utils.h:159
core::FastSemaphore
Definition: submodules/CoreLibrary/CoreLibrary/utils.h:303
core::Mutex
Definition: submodules/CoreLibrary/CoreLibrary/utils.h:222
core::CriticalSection
Definition: submodules/CoreLibrary/CoreLibrary/utils.h:234
core::Event
Definition: submodules/CoreLibrary/CoreLibrary/utils.h:261
core::String
Definition: submodules/CoreLibrary/CoreLibrary/utils.h:314
core::Host
Definition: submodules/CoreLibrary/CoreLibrary/utils.h:203
core::Semaphore
Definition: submodules/CoreLibrary/CoreLibrary/utils.h:209
core::Atomic
Definition: submodules/CoreLibrary/CoreLibrary/utils.h:282