xref: /openbmc/libbej/src/bej_encoder_json.cpp (revision da6e5573)
1 #include "bej_encoder_json.hpp"
2 
3 namespace libbej
4 {
5 
stackEmpty(void * dataPtr)6 bool stackEmpty(void* dataPtr)
7 {
8     return (reinterpret_cast<std::vector<void*>*>(dataPtr))->empty();
9 }
10 
stackPeek(void * dataPtr)11 void* stackPeek(void* dataPtr)
12 {
13     auto stack = reinterpret_cast<std::vector<void*>*>(dataPtr);
14     if (stack->empty())
15     {
16         return nullptr;
17     }
18     return stack->back();
19 }
20 
stackPop(void * dataPtr)21 void* stackPop(void* dataPtr)
22 {
23     auto stack = reinterpret_cast<std::vector<void*>*>(dataPtr);
24     if (stack->empty())
25     {
26         return nullptr;
27     }
28     void* value = stack->back();
29     stack->pop_back();
30     return value;
31 }
32 
stackPush(void * property,void * dataPtr)33 int stackPush(void* property, void* dataPtr)
34 {
35     auto stack = reinterpret_cast<std::vector<void*>*>(dataPtr);
36     stack->emplace_back(property);
37     return 0;
38 }
39 
getBejEncodedBuffer(const void * data,size_t dataSize,void * handlerContext)40 int getBejEncodedBuffer(const void* data, size_t dataSize, void* handlerContext)
41 {
42     auto stack = reinterpret_cast<std::vector<uint8_t>*>(handlerContext);
43     const uint8_t* dataBuf = reinterpret_cast<const uint8_t*>(data);
44     stack->insert(stack->end(), dataBuf, dataBuf + dataSize);
45     return 0;
46 }
47 
getOutput()48 std::vector<uint8_t> BejEncoderJson::getOutput()
49 {
50     std::vector<uint8_t> currentEncodedPayload = std::move(encodedPayload);
51     // Re-Initialize encodedPayload with empty vector to be used again for
52     // next encoding
53     encodedPayload = {};
54 
55     return currentEncodedPayload;
56 }
57 
encode(const struct BejDictionaries * dictionaries,enum BejSchemaClass schemaClass,struct RedfishPropertyParent * root)58 int BejEncoderJson::encode(const struct BejDictionaries* dictionaries,
59                            enum BejSchemaClass schemaClass,
60                            struct RedfishPropertyParent* root)
61 {
62     struct BejEncoderOutputHandler output = {
63         .handlerContext = &encodedPayload,
64         .recvOutput = &getBejEncodedBuffer,
65     };
66 
67     struct BejPointerStackCallback stackCallbacks = {
68         .stackContext = &stack,
69         .stackEmpty = stackEmpty,
70         .stackPeek = stackPeek,
71         .stackPop = stackPop,
72         .stackPush = stackPush,
73         .deleteStack = nullptr,
74     };
75 
76     return bejEncode(dictionaries, BEJ_DICTIONARY_START_AT_HEAD, schemaClass,
77                      root, &output, &stackCallbacks);
78 }
79 
80 } // namespace libbej
81