1/*
2 * Copyright (c) 2017, Matias Fontanini
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met:
8 *
9 * * Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * * Redistributions in binary form must reproduce the above
12 * copyright notice, this list of conditions and the following disclaimer
13 * in the documentation and/or other materials provided with the
14 * distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 *
28 */
29
30#ifndef CPPKAFKA_MESSAGE_INTERNAL_H
31#define CPPKAFKA_MESSAGE_INTERNAL_H
32
33#include <memory>
34#include "macros.h"
35
36namespace cppkafka {
37
38class Message;
39
40class Internal {
41public:
42 virtual ~Internal() = default;
43};
44using InternalPtr = std::shared_ptr<Internal>;
45
46/**
47 * \brief Private message data structure
48 */
49class CPPKAFKA_API MessageInternal {
50public:
51 MessageInternal(void* user_data, std::shared_ptr<Internal> internal);
52 static std::unique_ptr<MessageInternal> load(Message& message);
53 void* get_user_data() const;
54 InternalPtr get_internal() const;
55private:
56 void* user_data_;
57 InternalPtr internal_;
58};
59
60template <typename BuilderType>
61class MessageInternalGuard {
62public:
63 MessageInternalGuard(BuilderType& builder)
64 : builder_(builder),
65 user_data_(builder.user_data()) {
66 if (builder_.internal()) {
67 // Swap contents with user_data
68 ptr_.reset(new MessageInternal(user_data_, builder_.internal()));
69 builder_.user_data(ptr_.get()); //overwrite user data
70 }
71 }
72 ~MessageInternalGuard() {
73 //Restore user data
74 builder_.user_data(user_data_);
75 }
76 void release() {
77 ptr_.release();
78 }
79private:
80 BuilderType& builder_;
81 std::unique_ptr<MessageInternal> ptr_;
82 void* user_data_;
83};
84
85}
86
87#endif //CPPKAFKA_MESSAGE_INTERNAL_H
88