bson.h 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /*
  2. * Copyright (C) 2021 Duowan Inc. All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing,
  11. * software distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #ifndef __X_PACK_BSON_H
  17. #define __X_PACK_BSON_H
  18. #include "bson_decoder.h"
  19. #include "bson_encoder.h"
  20. #include "bson_builder.h"
  21. #include "xpack/xpack.h"
  22. namespace xpack {
  23. class bson {
  24. public:
  25. template <class T>
  26. // if copy is false, decode will parse bson in data. data's life time must >= call of decode
  27. static void decode(const std::string &data, T &val, bool copy=false) {
  28. BsonDecoder doc(data, copy);
  29. doc.decode(NULL, val, NULL);
  30. }
  31. template <class T>
  32. // if copy is false, decode will parse bson in data. data's life time must >= call of decode
  33. static void decode(const uint8_t* data, size_t len, T &val, bool copy=false) {
  34. BsonDecoder doc(data, len, copy);
  35. doc.decode(NULL, val, NULL);
  36. }
  37. template <class T>
  38. static std::string encode(const T &val) {
  39. BsonEncoder doc;
  40. doc.encode(NULL, val, NULL);
  41. return doc.String();
  42. }
  43. };
  44. }
  45. #endif