jutil.hpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #ifndef JUTIL_HPP
  14. #define JUTIL_HPP
  15. #include "jlib.hpp"
  16. #include "jstring.hpp"
  17. #include "jarray.hpp"
  18. #include "jbuff.hpp"
  19. #if defined (__APPLE__)
  20. #include <mach-o/dyld.h>
  21. #include <mach/mach_time.h>
  22. extern mach_timebase_info_data_t timebase_info; // Calibration for nanosecond timer
  23. #endif
  24. //#define NAMEDCOUNTS
  25. interface IPropertyTree;
  26. void jlib_decl MilliSleep(unsigned milli);
  27. long jlib_decl atolong_l(const char * s,int l);
  28. int jlib_decl atoi_l(const char * s,int l);
  29. __int64 jlib_decl atoi64_l(const char * s,int l);
  30. inline __int64 atoi64(const char* s) { return atoi64_l(s, (int)strlen(s)); }
  31. #ifndef _WIN32
  32. extern jlib_decl char * itoa(int n, char *str, int b);
  33. extern jlib_decl char * ltoa(long n, char *str, int b);
  34. extern jlib_decl char * ultoa(unsigned long n, char *str, int b);
  35. #define Sleep(milli) MilliSleep(milli)
  36. #endif
  37. bool jlib_decl j_isnan(double x);
  38. bool jlib_decl j_isinf(double x);
  39. void jlib_decl packNumber(char * target, const char * source, unsigned slen);
  40. void jlib_decl unpackNumber(char * target, const char * source, unsigned tlen);
  41. int jlib_decl numtostr(char *dst, char _value);
  42. int jlib_decl numtostr(char *dst, short _value);
  43. int jlib_decl numtostr(char *dst, int _value);
  44. int jlib_decl numtostr(char *dst, long _value);
  45. int jlib_decl numtostr(char *dst, __int64 _value);
  46. int jlib_decl numtostr(char *dst, unsigned char value);
  47. int jlib_decl numtostr(char *dst, unsigned short value);
  48. int jlib_decl numtostr(char *dst, unsigned int value);
  49. int jlib_decl numtostr(char *dst, unsigned long value);
  50. int jlib_decl numtostr(char *dst, unsigned __int64 _value);
  51. extern jlib_decl HINSTANCE LoadSharedObject(const char *name, bool isGlobal, bool raiseOnError);
  52. extern jlib_decl void FreeSharedObject(HINSTANCE h);
  53. class jlib_decl SharedObject : public CInterfaceOf<IInterface>
  54. {
  55. public:
  56. SharedObject() { h = 0; bRefCounted = false; }
  57. ~SharedObject() { unload(); }
  58. bool load(const char * dllName, bool isGlobal, bool raiseOnError=false);
  59. bool loadCurrentExecutable();
  60. bool loadResources(const char * dllName);
  61. bool loaded() const { return h != 0; }
  62. void unload();
  63. HINSTANCE getInstanceHandle() const { return h; }
  64. void *getEntry(const char * name) const;
  65. public:
  66. HINSTANCE h;
  67. bool bRefCounted;
  68. };
  69. // Interface for dynamically-loadable plugins
  70. interface IPluggableFactory : extends IInterface
  71. {
  72. virtual bool initializeStore() = 0;
  73. };
  74. typedef IPluggableFactory * (* IPluggableFactoryFactory)(const SharedObject *dll, const IPropertyTree *);
  75. extern jlib_decl IPluggableFactory *loadPlugin(const IPropertyTree* pluginInfo);
  76. //---------------------------------------------------------------------------
  77. //functions for generating unique identifiers consisting of 0..9,A..V
  78. typedef unsigned __int64 unique_id_t;
  79. extern jlib_decl StringBuffer & appendUniqueId(StringBuffer & target, unique_id_t value);
  80. extern jlib_decl unique_id_t getUniqueId();
  81. extern jlib_decl StringBuffer & getUniqueId(StringBuffer & target);
  82. extern jlib_decl void resetUniqueId();
  83. extern jlib_decl unsigned getRandom(); // global
  84. extern jlib_decl void seedRandom(unsigned seed);
  85. interface IRandomNumberGenerator: public IInterface
  86. {
  87. virtual void seed(unsigned seedval)=0;
  88. virtual unsigned next()=0;
  89. };
  90. extern jlib_decl IRandomNumberGenerator *createRandomNumberGenerator();
  91. #ifdef WIN32
  92. // Reentrant version of the rand() function for use with multithreaded applications.
  93. // rand_r return value between 0 and RAND_R_MAX (exclusive). Not that RAND_MAX is
  94. // implementation dependent: SHORT_MAX on Windows, INT_MAX on Linux.
  95. jlib_decl int rand_r(unsigned int *seed);
  96. #define RAND_R_MAX INT_MAX
  97. #else
  98. #define RAND_R_MAX RAND_MAX
  99. #endif
  100. interface IShuffledIterator: extends IInterface
  101. {
  102. virtual void seed(unsigned seedval)=0; // ony required for repeatability
  103. virtual bool first()=0;
  104. virtual bool isValid() = 0;
  105. virtual bool next() = 0;
  106. virtual unsigned get() = 0;
  107. virtual unsigned lookup(unsigned idx) = 0; // looks up idx'th entry
  108. };
  109. extern jlib_decl IShuffledIterator *createShuffledIterator(unsigned n); // returns iterator that returns 0..n-1 in shuffled order
  110. /* misc */
  111. extern jlib_decl bool isCIdentifier(const char* id);
  112. /* base64 encoder/decoder */
  113. extern jlib_decl void JBASE64_Encode(const void *data, long length, StringBuffer &out, bool addLineBreaks=true);
  114. extern jlib_decl void JBASE64_Encode(const void *data, long length, IIOStream &out, bool addLineBreaks=true);
  115. extern jlib_decl StringBuffer &JBASE64_Decode(const char *in, StringBuffer &out);
  116. extern jlib_decl MemoryBuffer &JBASE64_Decode(const char *in, MemoryBuffer &out);
  117. extern jlib_decl StringBuffer &JBASE64_Decode(ISimpleReadStream &in, StringBuffer &out);
  118. extern jlib_decl MemoryBuffer &JBASE64_Decode(ISimpleReadStream &in, MemoryBuffer &out);
  119. /**
  120. * Decode base 64 encoded string.
  121. * It handles forbidden printable and non-printable chars. Space(s) inserted among the valid chars,
  122. * missing pad chars and invalid length.
  123. *
  124. * @param length Length of the input string.
  125. * @param in Pointer to base64 encoded string
  126. * @param out Decoded string if the input is valid
  127. * @return True when success
  128. */
  129. extern jlib_decl bool JBASE64_Decode(size32_t length, const char *in, StringBuffer &out);
  130. extern jlib_decl void JBASE32_Encode(const char *in,StringBuffer &out); // result all lower
  131. extern jlib_decl void JBASE32_Decode(const char *in,StringBuffer &out);
  132. /* URL: http://user:passwd@host:port/path */
  133. extern jlib_decl StringBuffer& encodeUrlUseridPassword(StringBuffer& out, const char* in);
  134. extern jlib_decl StringBuffer& decodeUrlUseridPassword(StringBuffer& out, const char* in);
  135. //--------------------------------------------------------------------------------------------------------------------
  136. class StringPointerArrayMapper : public SimpleArrayMapper<const char *>
  137. {
  138. typedef const char * MEMBER;
  139. public:
  140. static void construct(const char * & member, const char * newValue)
  141. {
  142. member = strdup(newValue);
  143. }
  144. static void destruct(MEMBER & member)
  145. {
  146. free(const_cast<char *>(member));
  147. }
  148. static inline bool matches(MEMBER const & member, const char * param)
  149. {
  150. return strcmp(member, param) == 0;
  151. }
  152. };
  153. class jlib_decl StringArray : public ArrayOf<const char *, const char *, StringPointerArrayMapper>
  154. {
  155. struct CCmp
  156. {
  157. static int compare(char const * const *l, char const * const *r) { return strcmp(*l, *r); }
  158. static int compareNC(char const * const *l, char const * const *r) { return stricmp(*l, *r); }
  159. static int revCompare(char const * const *l, char const * const *r) { return strcmp(*r, *l); }
  160. static int revCompareNC(char const * const *l, char const * const *r) { return stricmp(*r, *l); }
  161. };
  162. typedef ArrayOf<const char *, const char *, StringPointerArrayMapper> PARENT;
  163. public:
  164. // Appends a list in a string delimited by 'delim'
  165. void appendList(const char *list, const char *delim);
  166. // Appends a list in a string delimited by 'delim' without duplicates
  167. void appendListUniq(const char *list, const char *delim);
  168. void sortAscii(bool nocase=false);
  169. void sortAsciiReverse(bool nocase=false);
  170. void sortCompare(int (*compare)(const char * const * l, const char * const * r));
  171. private:
  172. using PARENT::sort; // prevent access to this function - to avoid ambiguity
  173. };
  174. class CIStringArray : public StringArray, public CInterface
  175. {
  176. };
  177. extern jlib_decl unsigned msTick();
  178. extern jlib_decl unsigned usTick();
  179. extern jlib_decl int make_daemon(bool printpid=false); // outputs pid to stdout if printpid true
  180. extern jlib_decl void doStackProbe();
  181. #ifndef arraysize
  182. #define arraysize(T) (sizeof(T)/sizeof(*T))
  183. #endif
  184. extern jlib_decl unsigned runExternalCommand(StringBuffer &output, StringBuffer &error, const char *cmd, const char *input);
  185. extern jlib_decl unsigned __int64 greatestCommonDivisor(unsigned __int64 left, unsigned __int64 right);
  186. inline unsigned hex2num(char next)
  187. {
  188. if ((next >= '0') && (next <= '9'))
  189. return next - '0';
  190. if ((next >= 'a') && (next <= 'f'))
  191. return next - 'a' + 10;
  192. if ((next >= 'A') && (next <= 'F'))
  193. return next - 'A' + 10;
  194. return 0;
  195. }
  196. extern jlib_decl void initThreadLocal(int len, void* val);
  197. extern jlib_decl void* getThreadLocalVal();
  198. extern jlib_decl void clearThreadLocal();
  199. extern jlib_decl bool matchesMask(const char *fn, const char *mask, unsigned p, unsigned n);
  200. extern jlib_decl StringBuffer &expandMask(StringBuffer &buf, const char *mask, unsigned p, unsigned n);
  201. extern jlib_decl bool constructMask(StringAttr &attr, const char *fn, unsigned p, unsigned n);
  202. extern jlib_decl bool deduceMask(const char *fn, bool expandN, StringAttr &mask, unsigned &p, unsigned &n); // p is 0 based in these routines
  203. class HashKeyElement;
  204. class jlib_decl NamedCount
  205. {
  206. HashKeyElement *ht;
  207. public:
  208. NamedCount();
  209. ~NamedCount();
  210. void set(const char *name);
  211. };
  212. #ifdef NAMEDCOUNTS
  213. #define DECL_NAMEDCOUNT NamedCount namedCount
  214. #define INIT_NAMEDCOUNT namedCount.set(typeid(*this).name())
  215. #else
  216. #define DECL_NAMEDCOUNT
  217. #define INIT_NAMEDCOUNT {}
  218. #endif
  219. extern jlib_decl StringBuffer &dumpNamedCounts(StringBuffer &str);
  220. interface IAuthenticatedUser: extends IInterface
  221. {
  222. virtual bool login(const char *user, const char *passwd) = 0;
  223. virtual void impersonate()=0;
  224. virtual void revert()=0;
  225. virtual const char *username()=0;
  226. };
  227. interface IAtom;
  228. extern jlib_decl IAuthenticatedUser *createAuthenticatedUser();
  229. extern jlib_decl void serializeAtom(MemoryBuffer & target, IAtom * name);
  230. extern jlib_decl IAtom * deserializeAtom(MemoryBuffer & source);
  231. template <class KEY, class VALUE, class COMPARE>
  232. VALUE * binsearch(KEY key, VALUE * * values, unsigned num, COMPARE * cmp)
  233. {
  234. unsigned l = 0;
  235. unsigned u = num;
  236. while(l<u)
  237. {
  238. unsigned i = l+(u-l)/2;
  239. int c = cmp->compare(key, values[i]);
  240. if(c == 0)
  241. {
  242. return values[i];
  243. }
  244. else if(c < 0)
  245. {
  246. u = i;
  247. }
  248. else
  249. {
  250. l = i+1;
  251. }
  252. }
  253. return NULL;
  254. }
  255. extern jlib_decl StringBuffer &genUUID(StringBuffer &in, bool nocase=false);
  256. // Convert offset_t to string
  257. // Note that offset_t can be 32, 64 bit integers or a structure
  258. class jlib_decl OffsetToString
  259. {
  260. StringBuffer m_buffer;
  261. public:
  262. OffsetToString(offset_t offset);
  263. const char* str() { return m_buffer.str(); }
  264. };
  265. extern jlib_decl StringBuffer passwordInput(const char* prompt, StringBuffer& passwd);
  266. extern jlib_decl IPropertyTree *getHPCCEnvironment(const char *configFileName=NULL);
  267. extern jlib_decl bool getConfigurationDirectory(const IPropertyTree *dirtree, // NULL to use HPCC config
  268. const char *category,
  269. const char *component,
  270. const char *instance,
  271. StringBuffer &dirout);
  272. extern jlib_decl bool querySecuritySettings(bool * _useSSL,
  273. unsigned short *_port,
  274. const char * * _certificate,
  275. const char * * _privateKey);
  276. extern jlib_decl const char * matchConfigurationDirectoryEntry(const char *path,const char *mask,StringBuffer &name, StringBuffer &component, StringBuffer &instance);
  277. extern jlib_decl bool replaceConfigurationDirectoryEntry(const char *path,const char *frommask,const char *tomask,StringBuffer &out);
  278. extern jlib_decl const char *queryCurrentProcessPath();
  279. extern jlib_decl int parseCommandLine(const char * cmdline, MemoryBuffer &mb, const char** &argvout); // parses cmdline into argvout returning arg count (mb used as buffer)
  280. extern jlib_decl bool safe_ecvt(size_t len, char * buffer, double value, int numDigits, int * decimal, int * sign);
  281. extern jlib_decl bool safe_fcvt(size_t len, char * buffer, double value, int numPlaces, int * decimal, int * sign);
  282. extern jlib_decl StringBuffer &getTempFilePath(StringBuffer & target, const char * component, IPropertyTree * pTree);
  283. interface jlib_thrown_decl ICorruptDllException: extends IException
  284. {
  285. };
  286. struct mapEnums { int val; const char *str; };
  287. extern jlib_decl const char *getEnumText(int value, const mapEnums *map);
  288. class jlib_decl QuantilePositionIterator
  289. {
  290. public:
  291. QuantilePositionIterator(size_t _numRows, unsigned _numDivisions, bool roundUp)
  292. : numRows(_numRows), numDivisions(_numDivisions)
  293. {
  294. assertex(numDivisions);
  295. step = numRows / numDivisions;
  296. stepDelta = (unsigned)(numRows % numDivisions);
  297. initialDelta = roundUp ? (numDivisions)/2 : (numDivisions-1)/2;
  298. first();
  299. }
  300. bool first()
  301. {
  302. curRow = 0;
  303. curDelta = initialDelta;
  304. curQuantile = 0;
  305. return true;
  306. }
  307. bool next()
  308. {
  309. if (curQuantile >= numDivisions)
  310. return false;
  311. curQuantile++;
  312. curRow += step;
  313. curDelta += stepDelta;
  314. if (curDelta >= numDivisions)
  315. {
  316. curRow++;
  317. curDelta -= numDivisions;
  318. }
  319. assertex(curRow <= numRows);
  320. return true;
  321. }
  322. size_t get() { return curRow; }
  323. protected:
  324. size_t numRows;
  325. size_t curRow;
  326. size_t step;
  327. unsigned numDivisions;
  328. unsigned stepDelta;
  329. unsigned curQuantile;
  330. unsigned curDelta;
  331. unsigned initialDelta;
  332. };
  333. class jlib_decl QuantileFilterIterator
  334. {
  335. public:
  336. QuantileFilterIterator(size_t _numRows, unsigned _numDivisions, bool roundUp)
  337. : numRows(_numRows), numDivisions(_numDivisions)
  338. {
  339. assertex(numDivisions);
  340. initialDelta = roundUp ? (numDivisions-1)/2 : (numDivisions)/2;
  341. first();
  342. }
  343. bool first()
  344. {
  345. curRow = 0;
  346. curDelta = initialDelta;
  347. curQuantile = 0;
  348. isQuantile = true;
  349. return true;
  350. }
  351. bool next()
  352. {
  353. if (curRow > numRows)
  354. return false;
  355. curRow++;
  356. curDelta += numDivisions;
  357. isQuantile = false;
  358. if (curDelta >= numRows)
  359. {
  360. curDelta -= numRows;
  361. isQuantile = true;
  362. }
  363. return true;
  364. }
  365. size_t get() { return isQuantile; }
  366. protected:
  367. size_t numRows;
  368. size_t curRow;
  369. size_t step;
  370. size_t curDelta;
  371. unsigned numDivisions;
  372. unsigned curQuantile;
  373. unsigned initialDelta;
  374. bool isQuantile;
  375. };
  376. #endif