1 : // Copyright 2015 Google Inc. All Rights Reserved.
2 : //
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 : //
7 : // http://www.apache.org/licenses/LICENSE-2.0
8 : //
9 : // Unless required by applicable law or agreed to in writing, software
10 : // distributed under the License is distributed on an "AS IS" BASIS,
11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 : // See the License for the specific language governing permissions and
13 : // limitations under the License.
14 : //
15 : // Declares RawArgumentConverter, a utility class for wrapping up generic
16 : // function arguments of different sizes and retrieving them in the necessary
17 : // types.
18 : #ifndef SYZYGY_BARD_RAW_ARGUMENT_CONVERTER_H_
19 : #define SYZYGY_BARD_RAW_ARGUMENT_CONVERTER_H_
20 :
21 : #include <stdint.h>
22 :
23 : #include "base/logging.h"
24 : #include "base/memory/scoped_ptr.h"
25 :
26 : namespace bard {
27 :
28 : // A simple class for wrapping function arguments of different sizes and safely
29 : // retrieving them in the desired type.
30 : class RawArgumentConverter {
31 : public:
32 : // Initializes a new raw argument.
33 : // @param arg_data a pointer to the argument to be saved.
34 : // @param arg_size the size in bytes of the argument.
35 : RawArgumentConverter(const void* const arg_data, const uint32_t arg_size);
36 :
37 : // Explicitly allow copy and assign for use with STL containers.
38 : RawArgumentConverter(const RawArgumentConverter&) = default;
39 : RawArgumentConverter& operator=(const RawArgumentConverter&) = default;
40 :
41 : // Retrieve this argument in the desired type.
42 : // @tparam Type The type that this argument should to be retrieved as.
43 : // @param value The value to be populated.
44 : // @returns true on success, false otherwise.
45 : template <typename Type>
46 : bool RetrieveAs(Type* value) const;
47 :
48 : private:
49 : static const size_t kMaxArgSize = 8;
50 : uint8_t arg_[kMaxArgSize];
51 : uint32_t arg_size_;
52 : };
53 :
54 : template <typename Type>
55 E : bool RawArgumentConverter::RetrieveAs(Type* value) const {
56 E : DCHECK_NE(static_cast<Type*>(nullptr), value);
57 E : if (sizeof(Type) != arg_size_)
58 E : return false;
59 E : ::memcpy(value, arg_, arg_size_);
60 E : return true;
61 E : }
62 :
63 : } // namespace bard
64 :
65 : #endif // SYZYGY_BARD_RAW_ARGUMENT_CONVERTER_H_
|