|
| 1 | +/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. |
| 2 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +you may not use this file except in compliance with the License. |
| 4 | +You may obtain a copy of the License at |
| 5 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | +Unless required by applicable law or agreed to in writing, software |
| 7 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 8 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 9 | +See the License for the specific language governing permissions and |
| 10 | +limitations under the License. */ |
| 11 | + |
| 12 | +#pragma once |
| 13 | +#include <paddle/string/printf.h> |
| 14 | +#include <exception> |
| 15 | +#include <sstream> |
| 16 | + |
| 17 | +namespace paddle { |
| 18 | +namespace framework { |
| 19 | + |
| 20 | +/** |
| 21 | + * @brief Enforce exception. Inherits std::exception |
| 22 | + * |
| 23 | + * All enforce condition not met, will throw an EnforceNotMet exception. |
| 24 | + */ |
| 25 | +class EnforceNotMet : public std::exception { |
| 26 | + public: |
| 27 | + EnforceNotMet(const std::string& msg, const char* file, int fileline) { |
| 28 | + std::ostringstream sout; |
| 29 | + sout << msg << " at [" << file << ":" << fileline << "];"; |
| 30 | + all_msg_ = sout.str(); |
| 31 | + } |
| 32 | + |
| 33 | + const char* what() const noexcept override { return all_msg_.c_str(); } |
| 34 | + |
| 35 | + private: |
| 36 | + std::string all_msg_; |
| 37 | +}; |
| 38 | + |
| 39 | +// From https://stackoverflow.com/questions/30130930/ |
| 40 | +// __buildin_expect is in C++ 11 standard. Since the condition which enforced |
| 41 | +// should be true in most situation, it will make the compiler generate faster |
| 42 | +// code by adding `UNLIKELY` macro. |
| 43 | +#define UNLIKELY(condition) __builtin_expect(static_cast<bool>(condition), 0) |
| 44 | + |
| 45 | +/** |
| 46 | + * @brief Throw a EnforceNotMet exception, automatically filled __FILE__ & |
| 47 | + * __LINE__ |
| 48 | + * |
| 49 | + * This macro take __VA_ARGS__, user can pass any type if that type can |
| 50 | + * serialize to std::ostream |
| 51 | + */ |
| 52 | +#define PADDLE_THROW(...) \ |
| 53 | + do { \ |
| 54 | + throw ::paddle::framework::EnforceNotMet( \ |
| 55 | + ::paddle::string::Sprintf(__VA_ARGS__), __FILE__, __LINE__); \ |
| 56 | + } while (0) |
| 57 | + |
| 58 | +/** |
| 59 | + * @brief Enforce a condition, otherwise throw an EnforceNotMet |
| 60 | + */ |
| 61 | +#define PADDLE_ENFORCE(condition, ...) \ |
| 62 | + do { \ |
| 63 | + if (UNLIKELY(!(condition))) { \ |
| 64 | + PADDLE_THROW(__VA_ARGS__); \ |
| 65 | + } \ |
| 66 | + } while (0) |
| 67 | + |
| 68 | +} // namespace framework |
| 69 | +} // namespace paddle |
0 commit comments