PageRenderTime 44ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/indra/llcommon/llsdutil.h

https://bitbucket.org/lindenlab/viewer-beta/
C Header | 422 lines | 161 code | 44 blank | 217 comment | 3 complexity | 450801a6835e487e4c3e457e21daaf91 MD5 | raw file
Possible License(s): LGPL-2.1
  1. /**
  2. * @file llsdutil.h
  3. * @author Phoenix
  4. * @date 2006-05-24
  5. * @brief Utility classes, functions, etc, for using structured data.
  6. *
  7. * $LicenseInfo:firstyear=2006&license=viewerlgpl$
  8. * Second Life Viewer Source Code
  9. * Copyright (C) 2010, Linden Research, Inc.
  10. *
  11. * This library is free software; you can redistribute it and/or
  12. * modify it under the terms of the GNU Lesser General Public
  13. * License as published by the Free Software Foundation;
  14. * version 2.1 of the License only.
  15. *
  16. * This library is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  19. * Lesser General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU Lesser General Public
  22. * License along with this library; if not, write to the Free Software
  23. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  24. *
  25. * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
  26. * $/LicenseInfo$
  27. */
  28. #ifndef LL_LLSDUTIL_H
  29. #define LL_LLSDUTIL_H
  30. class LLSD;
  31. // U32
  32. LL_COMMON_API LLSD ll_sd_from_U32(const U32);
  33. LL_COMMON_API U32 ll_U32_from_sd(const LLSD& sd);
  34. // U64
  35. LL_COMMON_API LLSD ll_sd_from_U64(const U64);
  36. LL_COMMON_API U64 ll_U64_from_sd(const LLSD& sd);
  37. // IP Address
  38. LL_COMMON_API LLSD ll_sd_from_ipaddr(const U32);
  39. LL_COMMON_API U32 ll_ipaddr_from_sd(const LLSD& sd);
  40. // Binary to string
  41. LL_COMMON_API LLSD ll_string_from_binary(const LLSD& sd);
  42. //String to binary
  43. LL_COMMON_API LLSD ll_binary_from_string(const LLSD& sd);
  44. // Serializes sd to static buffer and returns pointer, useful for gdb debugging.
  45. LL_COMMON_API char* ll_print_sd(const LLSD& sd);
  46. // Serializes sd to static buffer and returns pointer, using "pretty printing" mode.
  47. LL_COMMON_API char* ll_pretty_print_sd_ptr(const LLSD* sd);
  48. LL_COMMON_API char* ll_pretty_print_sd(const LLSD& sd);
  49. //compares the structure of an LLSD to a template LLSD and stores the
  50. //"valid" values in a 3rd LLSD. Default values
  51. //are pulled from the template. Extra keys/values in the test
  52. //are ignored in the resultant LLSD. Ordering of arrays matters
  53. //Returns false if the test is of same type but values differ in type
  54. //Otherwise, returns true
  55. LL_COMMON_API BOOL compare_llsd_with_template(
  56. const LLSD& llsd_to_test,
  57. const LLSD& template_llsd,
  58. LLSD& resultant_llsd);
  59. /**
  60. * Recursively determine whether a given LLSD data block "matches" another
  61. * LLSD prototype. The returned string is empty() on success, non-empty() on
  62. * mismatch.
  63. *
  64. * This function tests structure (types) rather than data values. It is
  65. * intended for when a consumer expects an LLSD block with a particular
  66. * structure, and must succinctly detect whether the arriving block is
  67. * well-formed. For instance, a test of the form:
  68. * @code
  69. * if (! (data.has("request") && data.has("target") && data.has("modifier") ...))
  70. * @endcode
  71. * could instead be expressed by initializing a prototype LLSD map with the
  72. * required keys and writing:
  73. * @code
  74. * if (! llsd_matches(prototype, data).empty())
  75. * @endcode
  76. *
  77. * A non-empty return value is an error-message fragment intended to indicate
  78. * to (English-speaking) developers where in the prototype structure the
  79. * mismatch occurred.
  80. *
  81. * * If a slot in the prototype isUndefined(), then anything is valid at that
  82. * place in the real object. (Passing prototype == LLSD() matches anything
  83. * at all.)
  84. * * An array in the prototype must match a data array at least that large.
  85. * (Additional entries in the data array are ignored.) Every isDefined()
  86. * entry in the prototype array must match the corresponding entry in the
  87. * data array.
  88. * * A map in the prototype must match a map in the data. Every key in the
  89. * prototype map must match a corresponding key in the data map. (Additional
  90. * keys in the data map are ignored.) Every isDefined() value in the
  91. * prototype map must match the corresponding key's value in the data map.
  92. * * Scalar values in the prototype are tested for @em type rather than value.
  93. * For instance, a String in the prototype matches any String at all. In
  94. * effect, storing an Integer at a particular place in the prototype asserts
  95. * that the caller intends to apply asInteger() to the corresponding slot in
  96. * the data.
  97. * * A String in the prototype matches String, Boolean, Integer, Real, UUID,
  98. * Date and URI, because asString() applied to any of these produces a
  99. * meaningful result.
  100. * * Similarly, a Boolean, Integer or Real in the prototype can match any of
  101. * Boolean, Integer or Real in the data -- or even String.
  102. * * UUID matches UUID or String.
  103. * * Date matches Date or String.
  104. * * URI matches URI or String.
  105. * * Binary in the prototype matches only Binary in the data.
  106. *
  107. * @TODO: when a Boolean, Integer or Real in the prototype matches a String in
  108. * the data, we should examine the String @em value to ensure it can be
  109. * meaningfully converted to the requested type. The same goes for UUID, Date
  110. * and URI.
  111. */
  112. LL_COMMON_API std::string llsd_matches(const LLSD& prototype, const LLSD& data, const std::string& pfx="");
  113. /// Deep equality. If you want to compare LLSD::Real values for approximate
  114. /// equality rather than bitwise equality, pass @a bits as for
  115. /// is_approx_equal_fraction().
  116. LL_COMMON_API bool llsd_equals(const LLSD& lhs, const LLSD& rhs, unsigned bits=-1);
  117. // Simple function to copy data out of input & output iterators if
  118. // there is no need for casting.
  119. template<typename Input> LLSD llsd_copy_array(Input iter, Input end)
  120. {
  121. LLSD dest;
  122. for (; iter != end; ++iter)
  123. {
  124. dest.append(*iter);
  125. }
  126. return dest;
  127. }
  128. /*****************************************************************************
  129. * LLSDArray
  130. *****************************************************************************/
  131. /**
  132. * Construct an LLSD::Array inline, with implicit conversion to LLSD. Usage:
  133. *
  134. * @code
  135. * void somefunc(const LLSD&);
  136. * ...
  137. * somefunc(LLSDArray("text")(17)(3.14));
  138. * @endcode
  139. *
  140. * For completeness, LLSDArray() with no args constructs an empty array, so
  141. * <tt>LLSDArray()("text")(17)(3.14)</tt> produces an array equivalent to the
  142. * above. But for most purposes, LLSD() is already equivalent to an empty
  143. * array, and if you explicitly want an empty isArray(), there's
  144. * LLSD::emptyArray(). However, supporting a no-args LLSDArray() constructor
  145. * follows the principle of least astonishment.
  146. */
  147. class LLSDArray
  148. {
  149. public:
  150. LLSDArray():
  151. _data(LLSD::emptyArray())
  152. {}
  153. /**
  154. * Need an explicit copy constructor. Consider the following:
  155. *
  156. * @code
  157. * LLSD array_of_arrays(LLSDArray(LLSDArray(17)(34))
  158. * (LLSDArray("x")("y")));
  159. * @endcode
  160. *
  161. * The coder intends to construct [[17, 34], ["x", "y"]].
  162. *
  163. * With the compiler's implicit copy constructor, s/he gets instead
  164. * [17, 34, ["x", "y"]].
  165. *
  166. * The expression LLSDArray(17)(34) constructs an LLSDArray with those two
  167. * values. The reader assumes it should be converted to LLSD, as we always
  168. * want with LLSDArray, before passing it to the @em outer LLSDArray
  169. * constructor! This copy constructor makes that happen.
  170. */
  171. LLSDArray(const LLSDArray& inner):
  172. _data(LLSD::emptyArray())
  173. {
  174. _data.append(inner);
  175. }
  176. LLSDArray(const LLSD& value):
  177. _data(LLSD::emptyArray())
  178. {
  179. _data.append(value);
  180. }
  181. LLSDArray& operator()(const LLSD& value)
  182. {
  183. _data.append(value);
  184. return *this;
  185. }
  186. operator LLSD() const { return _data; }
  187. LLSD get() const { return _data; }
  188. private:
  189. LLSD _data;
  190. };
  191. /*****************************************************************************
  192. * LLSDMap
  193. *****************************************************************************/
  194. /**
  195. * Construct an LLSD::Map inline, with implicit conversion to LLSD. Usage:
  196. *
  197. * @code
  198. * void somefunc(const LLSD&);
  199. * ...
  200. * somefunc(LLSDMap("alpha", "abc")("number", 17)("pi", 3.14));
  201. * @endcode
  202. *
  203. * For completeness, LLSDMap() with no args constructs an empty map, so
  204. * <tt>LLSDMap()("alpha", "abc")("number", 17)("pi", 3.14)</tt> produces a map
  205. * equivalent to the above. But for most purposes, LLSD() is already
  206. * equivalent to an empty map, and if you explicitly want an empty isMap(),
  207. * there's LLSD::emptyMap(). However, supporting a no-args LLSDMap()
  208. * constructor follows the principle of least astonishment.
  209. */
  210. class LLSDMap
  211. {
  212. public:
  213. LLSDMap():
  214. _data(LLSD::emptyMap())
  215. {}
  216. LLSDMap(const LLSD::String& key, const LLSD& value):
  217. _data(LLSD::emptyMap())
  218. {
  219. _data[key] = value;
  220. }
  221. LLSDMap& operator()(const LLSD::String& key, const LLSD& value)
  222. {
  223. _data[key] = value;
  224. return *this;
  225. }
  226. operator LLSD() const { return _data; }
  227. LLSD get() const { return _data; }
  228. private:
  229. LLSD _data;
  230. };
  231. /*****************************************************************************
  232. * LLSDParam
  233. *****************************************************************************/
  234. /**
  235. * LLSDParam is a customization point for passing LLSD values to function
  236. * parameters of more or less arbitrary type. LLSD provides a small set of
  237. * native conversions; but if a generic algorithm explicitly constructs an
  238. * LLSDParam object in the function's argument list, a consumer can provide
  239. * LLSDParam specializations to support more different parameter types than
  240. * LLSD's native conversions.
  241. *
  242. * Usage:
  243. *
  244. * @code
  245. * void somefunc(const paramtype&);
  246. * ...
  247. * somefunc(..., LLSDParam<paramtype>(someLLSD), ...);
  248. * @endcode
  249. */
  250. template <typename T>
  251. class LLSDParam
  252. {
  253. public:
  254. /**
  255. * Default implementation converts to T on construction, saves converted
  256. * value for later retrieval
  257. */
  258. LLSDParam(const LLSD& value):
  259. _value(value)
  260. {}
  261. operator T() const { return _value; }
  262. private:
  263. T _value;
  264. };
  265. /**
  266. * Turns out that several target types could accept an LLSD param using any of
  267. * a few different conversions, e.g. LLUUID's constructor can accept LLUUID or
  268. * std::string. Therefore, the compiler can't decide which LLSD conversion
  269. * operator to choose, even though to us it seems obvious. But that's okay, we
  270. * can specialize LLSDParam for such target types, explicitly specifying the
  271. * desired conversion -- that's part of what LLSDParam is all about. Turns out
  272. * we have to do that enough to make it worthwhile generalizing. Use a macro
  273. * because I need to specify one of the asReal, etc., explicit conversion
  274. * methods as well as a type. If I'm overlooking a clever way to implement
  275. * that using a template instead, feel free to reimplement.
  276. */
  277. #define LLSDParam_for(T, AS) \
  278. template <> \
  279. class LLSDParam<T> \
  280. { \
  281. public: \
  282. LLSDParam(const LLSD& value): \
  283. _value(value.AS()) \
  284. {} \
  285. \
  286. operator T() const { return _value; } \
  287. \
  288. private: \
  289. T _value; \
  290. }
  291. LLSDParam_for(float, asReal);
  292. LLSDParam_for(LLUUID, asUUID);
  293. LLSDParam_for(LLDate, asDate);
  294. LLSDParam_for(LLURI, asURI);
  295. LLSDParam_for(LLSD::Binary, asBinary);
  296. /**
  297. * LLSDParam<const char*> is an example of the kind of conversion you can
  298. * support with LLSDParam beyond native LLSD conversions. Normally you can't
  299. * pass an LLSD object to a function accepting const char* -- but you can
  300. * safely pass an LLSDParam<const char*>(yourLLSD).
  301. */
  302. template <>
  303. class LLSDParam<const char*>
  304. {
  305. private:
  306. // The difference here is that we store a std::string rather than a const
  307. // char*. It's important that the LLSDParam object own the std::string.
  308. std::string _value;
  309. // We don't bother storing the incoming LLSD object, but we do have to
  310. // distinguish whether _value is an empty string because the LLSD object
  311. // contains an empty string or because it's isUndefined().
  312. bool _undefined;
  313. public:
  314. LLSDParam(const LLSD& value):
  315. _value(value),
  316. _undefined(value.isUndefined())
  317. {}
  318. // The const char* we retrieve is for storage owned by our _value member.
  319. // That's how we guarantee that the const char* is valid for the lifetime
  320. // of this LLSDParam object. Constructing your LLSDParam in the argument
  321. // list should ensure that the LLSDParam object will persist for the
  322. // duration of the function call.
  323. operator const char*() const
  324. {
  325. if (_undefined)
  326. {
  327. // By default, an isUndefined() LLSD object's asString() method
  328. // will produce an empty string. But for a function accepting
  329. // const char*, it's often important to be able to pass NULL, and
  330. // isUndefined() seems like the best way. If you want to pass an
  331. // empty string, you can still pass LLSD(""). Without this special
  332. // case, though, no LLSD value could pass NULL.
  333. return NULL;
  334. }
  335. return _value.c_str();
  336. }
  337. };
  338. namespace llsd
  339. {
  340. /*****************************************************************************
  341. * BOOST_FOREACH() helpers for LLSD
  342. *****************************************************************************/
  343. /// Usage: BOOST_FOREACH(LLSD item, inArray(someLLSDarray)) { ... }
  344. class inArray
  345. {
  346. public:
  347. inArray(const LLSD& array):
  348. _array(array)
  349. {}
  350. typedef LLSD::array_const_iterator const_iterator;
  351. typedef LLSD::array_iterator iterator;
  352. iterator begin() { return _array.beginArray(); }
  353. iterator end() { return _array.endArray(); }
  354. const_iterator begin() const { return _array.beginArray(); }
  355. const_iterator end() const { return _array.endArray(); }
  356. private:
  357. LLSD _array;
  358. };
  359. /// MapEntry is what you get from dereferencing an LLSD::map_[const_]iterator.
  360. typedef std::map<LLSD::String, LLSD>::value_type MapEntry;
  361. /// Usage: BOOST_FOREACH([const] MapEntry& e, inMap(someLLSDmap)) { ... }
  362. class inMap
  363. {
  364. public:
  365. inMap(const LLSD& map):
  366. _map(map)
  367. {}
  368. typedef LLSD::map_const_iterator const_iterator;
  369. typedef LLSD::map_iterator iterator;
  370. iterator begin() { return _map.beginMap(); }
  371. iterator end() { return _map.endMap(); }
  372. const_iterator begin() const { return _map.beginMap(); }
  373. const_iterator end() const { return _map.endMap(); }
  374. private:
  375. LLSD _map;
  376. };
  377. } // namespace llsd
  378. #endif // LL_LLSDUTIL_H