blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
b8aaec94add9cfe94d3a558994f2b30b39456c58
0b2980d9858f60c0dac99ca69689110dc0e8ebd4
/loss_multiattr.hpp
b359fcad0a1f8679117d1044491f2cfd152e1eac
[]
no_license
ufownl/ai_challenger_zsl
c1659f6628e7594691e4e7ec2dda220bca0848e1
5a49fd7756d76fd0d8f910c4b0348b42f6fe3c01
refs/heads/master
2020-03-13T10:33:32.156333
2018-05-18T11:57:01
2018-05-18T11:57:33
131,085,675
2
0
null
null
null
null
UTF-8
C++
false
false
3,151
hpp
#ifndef AI_CHALLENGER_ZSL_LOSS_MULTIATTR_HPP #define AI_CHALLENGER_ZSL_LOSS_MULTIATTR_HPP #include <dlib/dnn/core.h> #include <dlib/cuda/tensor_tools.h> #include <dlib/matrix.h> #include <iostream> #include <string> class loss_multiattr_ { public: using training_label_type = dlib::matrix<float, 0, 1>; using output_label_type = dlib::matrix<float, 0, 1>; template <class Subnet, class LabelIterator> void to_label(const dlib::tensor& input_tensor, const Subnet& sub, LabelIterator iter) const { auto& output_tensor = sub.get_output(); DLIB_CASSERT(sub.sample_expansion_factor() == 1); DLIB_CASSERT(output_tensor.nr() == 1 && output_tensor.nc() == 1); DLIB_CASSERT(input_tensor.num_samples() == output_tensor.num_samples()); auto out_data = output_tensor.host(); for (auto i = 0ll; i < output_tensor.num_samples(); ++i) { *iter++ = dlib::mat(out_data, output_tensor.k(), 1); out_data += output_tensor.k(); } } template <class ConstLabelIterator, class Subnet> double compute_loss_value_and_gradient(const dlib::tensor& input_tensor, ConstLabelIterator truth, Subnet& sub) const { auto& output_tensor = sub.get_output(); auto& grad = sub.get_gradient_input(); DLIB_CASSERT(sub.sample_expansion_factor() == 1); DLIB_CASSERT(input_tensor.num_samples() != 0); DLIB_CASSERT(input_tensor.num_samples() % sub.sample_expansion_factor() == 0); DLIB_CASSERT(input_tensor.num_samples() == grad.num_samples()); DLIB_CASSERT(input_tensor.num_samples() == output_tensor.num_samples()); DLIB_CASSERT(output_tensor.nr() == 1 && output_tensor.nc() == 1); DLIB_CASSERT(grad.nr() == 1 && grad.nc() == 1); // The loss we output is the average loss over the mini-batch. auto scale = 1.0f / output_tensor.num_samples(); auto loss = 0.0; auto out_data = output_tensor.host(); auto g = grad.host(); for (auto i = 0ll; i < output_tensor.num_samples(); ++i) { auto& y = *truth++; for (auto k = 0ll; k < output_tensor.k(); ++k) { auto idx = i * output_tensor.k() + k; auto d = out_data[idx] - y(k); loss += scale * d * d; g[idx] = scale * d * out_data[idx] * (1.0f - out_data[idx]); } } return loss; } friend void serialize(const loss_multiattr_& , std::ostream& out) { dlib::serialize("loss_multiattr_", out); } friend void deserialize(loss_multiattr_& , std::istream& in) { std::string version; dlib::deserialize(version, in); if (version != "loss_multiattr_") { throw dlib::serialization_error("Unexpected version found while deserializing loss_multiattr_."); } } friend std::ostream& operator<<(std::ostream& out, const loss_multiattr_&) { out << "loss_multiattr"; return out; } friend void to_xml(const loss_multiattr_&, std::ostream& out) { out << "<loss_multiattr/>"; } }; template <typename Subnet> using loss_multiattr = dlib::add_loss_layer<loss_multiattr_, Subnet>; #endif // AI_CHALLENGER_ZSL_LOSS_MULTIATTR_HPP
[ "ufownl@gmail.com" ]
ufownl@gmail.com
6e02132b0c97f9696d61f6025bb610a3d8b7fb43
2a1d6dd834c7090301f181e2c63ed95cac1433da
/Assignment5/Hash.h
252ea57d0bebc7c566bc349ad4a180ab8602615e
[]
no_license
gusfowler/cse-310-is-super-sporky
c0d1dbcd9c0f84a96e6a6ecbe66aa5218ae6f0e7
a3be1efecde1fbecee11776031fd59a36b1cbbae
refs/heads/master
2023-01-24T13:03:00.842853
2020-12-04T20:07:48
2020-12-04T20:07:48
292,693,140
0
0
null
null
null
null
UTF-8
C++
false
false
4,846
h
// ASU CSE310 Assignment #5 // Name of Author: August Fowler // ASU ID: 1214774210 // Description: this is where you need to design functions on Hash hashTable, // such as hashInsert, hashDelete, hashSearch and hashDisplay #include "LinkedList.h" #include <iostream> #include <iomanip> #include <string> #include <cstring> #include <math.h> using namespace std; class Hash { private: LinkedList* hashTable; //hashTable is a one-dimensional array of LinkedList int m; //slots number of the hash table public: Hash(int size); ~Hash(); bool hashInsert(string foodID, string name, string supplierID, double price); bool hashDelete(string foodID, string name, string supplierID); bool hashSearch(string foodID, string name, string supplierID); void hashDisplay(); int hashFunction(string key); //add any other auxiliary functions here //---- }; //constructor Hash::Hash(int size) { hashTable = new LinkedList[size]; m = size; } //Destructor Hash::~Hash() { //---- delete[] hashTable; } //hashInsert inserts a Food with the relevant info. into the hashTable. //it returns true if the data is inserted successfully and false otherwise bool Hash::hashInsert(string foodID, string name, string supplierID, double price) { //---- int hash = hashFunction(foodID + name + supplierID); //hash = 0; printf("slot index = %i", hash); cout << endl; return hashTable[hash].insertFood(foodID, name, supplierID, price); } //hashDelete deletes a Food with the relevant key from the hashTable. //it returns true if it is deleted successfully and false otherwise //Note: key is the combination of foodID, name and supplierID bool Hash::hashDelete(string foodID, string name, string supplierID) { //---- if (hashSearch(foodID, name, supplierID)) { bool deleted = hashTable[hashFunction(foodID + name + supplierID)].deleteFood(foodID); if (deleted) { cout << "\n"; cout << setw(4) << foodID << setw(30) << name << setw(12) << supplierID << " is deleted from hash table.\n" << endl; } else { cout << "\n"; cout << setw(4) << foodID << setw(30) << name << setw(12) << supplierID << " is NOT deleted from hash table.\n" << endl; } return deleted; } else { cout << "\n"; cout << setw(4) << foodID << setw(30) << name << setw(12) << supplierID << " is NOT deleted from hash table.\n" << endl; return false; } } //This function searches for a key inside the hash table and //return true if it is found and false otherwise //Note: key is the combination of foodID, name and supplierID bool Hash::hashSearch(string foodID, string name, string supplierID) { //---- bool found = hashTable[hashFunction(foodID + name + supplierID)].searchFood(foodID); if (found) cout << "\n" << left << setw(4) << foodID << setw(30) << name << setw(12) << supplierID << " is found inside the hash table." << endl; if(!found) cout << "\n" << left << setw(4) << foodID << setw(30) << name << setw(12) << supplierID << " is NOT found inside the hash table." << endl; return found; } //This function prints all the elements from the hash hashTable. void Hash::hashDisplay() { //---- for (int i = 0; i < m; i++) { if (hashTable[i].getSize() == 0) { printf("\nhashTable[%i] is empty, size=%i", i, hashTable[i].getSize()); } else { printf("\nhashTable[%i], size=%i", i, hashTable[i].getSize()); hashTable[i].displayList(); } } //---- } //This is the hash function you will need to design, test and refine //Given a Food key, the function should return the slot index where it //will be hashed to int Hash::hashFunction(string key) { //---- int hash = 0; //Create total of all ASCII values in key int ASCII_total = 0; int keyLength = key.length(); char* char_array = new char[keyLength + 1]; strcpy(char_array, key.c_str()); for (int i = 0; i < keyLength; i++) { ASCII_total += char_array[i]; } // hash by multiplication float A = 2 / (sqrt(5) + 1); //inverse fibonacci hash = floor(m * (fmod((ASCII_total * A), 1))); return hash; }
[ "gus.fowler12@gmail.com" ]
gus.fowler12@gmail.com
5439696865d93ddb2ba42b2953ad056e0c15fb6d
46f53e9a564192eed2f40dc927af6448f8608d13
/extensions/browser/app_window/app_window.h
6c0e1358f6c152aeb39a6d9c3d0043efb04f921a
[ "BSD-3-Clause" ]
permissive
sgraham/nope
deb2d106a090d71ae882ac1e32e7c371f42eaca9
f974e0c234388a330aab71a3e5bbf33c4dcfc33c
refs/heads/master
2022-12-21T01:44:15.776329
2015-03-23T17:25:47
2015-03-23T17:25:47
32,344,868
2
2
null
null
null
null
UTF-8
C++
false
false
21,798
h
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef EXTENSIONS_BROWSER_APP_WINDOW_APP_WINDOW_H_ #define EXTENSIONS_BROWSER_APP_WINDOW_APP_WINDOW_H_ #include <string> #include <vector> #include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "components/sessions/session_id.h" #include "components/web_modal/popup_manager.h" #include "components/web_modal/web_contents_modal_dialog_manager_delegate.h" #include "content/public/browser/web_contents_delegate.h" #include "content/public/browser/web_contents_observer.h" #include "extensions/browser/extension_icon_image.h" #include "extensions/browser/extension_registry_observer.h" #include "ui/base/ui_base_types.h" // WindowShowState #include "ui/gfx/geometry/rect.h" #include "ui/gfx/image/image.h" class GURL; class SkRegion; namespace base { class DictionaryValue; } namespace content { class BrowserContext; class WebContents; } namespace ui { class BaseWindow; } namespace extensions { class AppDelegate; class AppWebContentsHelper; class Extension; class ExtensionRegistry; class NativeAppWindow; class PlatformAppBrowserTest; class WindowController; struct DraggableRegion; // Manages the web contents for app windows. The implementation for this // class should create and maintain the WebContents for the window, and handle // any message passing between the web contents and the extension system or // native window. class AppWindowContents { public: AppWindowContents() {} virtual ~AppWindowContents() {} // Called to initialize the WebContents, before the app window is created. virtual void Initialize(content::BrowserContext* context, const GURL& url) = 0; // Called to load the contents, after the app window is created. virtual void LoadContents(int32 creator_process_id) = 0; // Called when the native window changes. virtual void NativeWindowChanged(NativeAppWindow* native_app_window) = 0; // Called when the native window closes. virtual void NativeWindowClosed() = 0; // Called in tests when the window is shown virtual void DispatchWindowShownForTests() const = 0; virtual content::WebContents* GetWebContents() const = 0; private: DISALLOW_COPY_AND_ASSIGN(AppWindowContents); }; // AppWindow is the type of window used by platform apps. App windows // have a WebContents but none of the chrome of normal browser windows. class AppWindow : public content::WebContentsDelegate, public content::WebContentsObserver, public web_modal::WebContentsModalDialogManagerDelegate, public IconImage::Observer, public ExtensionRegistryObserver { public: enum WindowType { WINDOW_TYPE_DEFAULT = 1 << 0, // Default app window. WINDOW_TYPE_PANEL = 1 << 1, // OS controlled panel window (Ash only). WINDOW_TYPE_V1_PANEL = 1 << 2, // For apps v1 support in Ash; deprecate // with v1 apps. }; enum Frame { FRAME_CHROME, // Chrome-style window frame. FRAME_NONE, // Frameless window. }; enum FullscreenType { // Not fullscreen. FULLSCREEN_TYPE_NONE = 0, // Fullscreen entered by the app.window api. FULLSCREEN_TYPE_WINDOW_API = 1 << 0, // Fullscreen entered by HTML requestFullscreen(). FULLSCREEN_TYPE_HTML_API = 1 << 1, // Fullscreen entered by the OS. ChromeOS uses this type of fullscreen to // enter immersive fullscreen when the user hits the <F4> key. FULLSCREEN_TYPE_OS = 1 << 2, // Fullscreen mode that could not be exited by the user. ChromeOS uses // this type of fullscreen to run an app in kiosk mode. FULLSCREEN_TYPE_FORCED = 1 << 3, }; struct BoundsSpecification { // INT_MIN represents an unspecified position component. static const int kUnspecifiedPosition; BoundsSpecification(); ~BoundsSpecification(); // INT_MIN designates 'unspecified' for the position components, and 0 // designates 'unspecified' for the size components. When unspecified, // they should be replaced with a default value. gfx::Rect bounds; gfx::Size minimum_size; gfx::Size maximum_size; // Reset the bounds fields to their 'unspecified' values. The minimum and // maximum size constraints remain unchanged. void ResetBounds(); }; struct CreateParams { CreateParams(); ~CreateParams(); WindowType window_type; Frame frame; bool has_frame_color; SkColor active_frame_color; SkColor inactive_frame_color; bool alpha_enabled; bool is_ime_window; // The initial content/inner bounds specification (excluding any window // decorations). BoundsSpecification content_spec; // The initial window/outer bounds specification (including window // decorations). BoundsSpecification window_spec; std::string window_key; // The process ID of the process that requested the create. int32 creator_process_id; // Initial state of the window. ui::WindowShowState state; // If true, don't show the window after creation. bool hidden; // If true, the window will be resizable by the user. Defaults to true. bool resizable; // If true, the window will be focused on creation. Defaults to true. bool focused; // If true, the window will stay on top of other windows that are not // configured to be always on top. Defaults to false. bool always_on_top; // If true, the window will be visible on all workspaces. Defaults to false. bool visible_on_all_workspaces; // The API enables developers to specify content or window bounds. This // function combines them into a single, constrained window size. gfx::Rect GetInitialWindowBounds(const gfx::Insets& frame_insets) const; // The API enables developers to specify content or window size constraints. // These functions combine them so that we can work with one set of // constraints. gfx::Size GetContentMinimumSize(const gfx::Insets& frame_insets) const; gfx::Size GetContentMaximumSize(const gfx::Insets& frame_insets) const; gfx::Size GetWindowMinimumSize(const gfx::Insets& frame_insets) const; gfx::Size GetWindowMaximumSize(const gfx::Insets& frame_insets) const; }; // Convert draggable regions in raw format to SkRegion format. Caller is // responsible for deleting the returned SkRegion instance. static SkRegion* RawDraggableRegionsToSkRegion( const std::vector<DraggableRegion>& regions); // The constructor and Init methods are public for constructing a AppWindow // with a non-standard render interface (e.g. v1 apps using Ash Panels). // Normally AppWindow::Create should be used. // Takes ownership of |app_delegate| and |delegate|. AppWindow(content::BrowserContext* context, AppDelegate* app_delegate, const Extension* extension); // Initializes the render interface, web contents, and native window. // |app_window_contents| will become owned by AppWindow. void Init(const GURL& url, AppWindowContents* app_window_contents, const CreateParams& params); const std::string& window_key() const { return window_key_; } const SessionID& session_id() const { return session_id_; } const std::string& extension_id() const { return extension_id_; } content::WebContents* web_contents() const; WindowType window_type() const { return window_type_; } bool window_type_is_panel() const { return (window_type_ == WINDOW_TYPE_PANEL || window_type_ == WINDOW_TYPE_V1_PANEL); } content::BrowserContext* browser_context() const { return browser_context_; } const gfx::Image& app_icon() const { return app_icon_; } const GURL& app_icon_url() const { return app_icon_url_; } const gfx::Image& badge_icon() const { return badge_icon_; } const GURL& badge_icon_url() const { return badge_icon_url_; } bool is_hidden() const { return is_hidden_; } const Extension* GetExtension() const; NativeAppWindow* GetBaseWindow(); gfx::NativeWindow GetNativeWindow(); // Returns the bounds that should be reported to the renderer. gfx::Rect GetClientBounds() const; // NativeAppWindows should call this to determine what the window's title // is on startup and from within UpdateWindowTitle(). base::string16 GetTitle() const; // Call to notify ShellRegistry and delete the window. Subclasses should // invoke this method instead of using "delete this". void OnNativeClose(); // Should be called by native implementations when the window size, position, // or minimized/maximized state has changed. void OnNativeWindowChanged(); // Should be called by native implementations when the window is activated. void OnNativeWindowActivated(); // Specifies a url for the launcher icon. void SetAppIconUrl(const GURL& icon_url); // Specifies a url for the window badge. void SetBadgeIconUrl(const GURL& icon_url); // Clear the current badge. void ClearBadge(); // Set the window shape. Passing a NULL |region| sets the default shape. void UpdateShape(scoped_ptr<SkRegion> region); // Called from the render interface to modify the draggable regions. void UpdateDraggableRegions(const std::vector<DraggableRegion>& regions); // Updates the app image to |image|. Called internally from the image loader // callback. Also called externally for v1 apps using Ash Panels. void UpdateAppIcon(const gfx::Image& image); // Enable or disable fullscreen mode. |type| specifies which type of // fullscreen mode to change (note that disabling one type of fullscreen may // not exit fullscreen mode because a window may have a different type of // fullscreen enabled). If |type| is not FORCED, checks that the extension has // the required permission. void SetFullscreen(FullscreenType type, bool enable); // Returns true if the app window is in a fullscreen state. bool IsFullscreen() const; // Returns true if the app window is in a forced fullscreen state (one that // cannot be exited by the user). bool IsForcedFullscreen() const; // Returns true if the app window is in a fullscreen state entered from an // HTML API request. bool IsHtmlApiFullscreen() const; // Transitions window into fullscreen, maximized, minimized or restores based // on chrome.app.window API. void Fullscreen(); void Maximize(); void Minimize(); void Restore(); // Transitions to OS fullscreen. See FULLSCREEN_TYPE_OS for more details. void OSFullscreen(); // Transitions to forced fullscreen. See FULLSCREEN_TYPE_FORCED for more // details. void ForcedFullscreen(); // Set the minimum and maximum size of the content bounds. void SetContentSizeConstraints(const gfx::Size& min_size, const gfx::Size& max_size); enum ShowType { SHOW_ACTIVE, SHOW_INACTIVE }; // Shows the window if its contents have been painted; otherwise flags the // window to be shown as soon as its contents are painted for the first time. void Show(ShowType show_type); // Hides the window. If the window was previously flagged to be shown on // first paint, it will be unflagged. void Hide(); AppWindowContents* app_window_contents_for_test() { return app_window_contents_.get(); } int fullscreen_types_for_test() { return fullscreen_types_; } // Set whether the window should stay above other windows which are not // configured to be always-on-top. void SetAlwaysOnTop(bool always_on_top); // Whether the always-on-top property has been set by the chrome.app.window // API. Note that the actual value of this property in the native app window // may be false if the bit is silently switched off for security reasons. bool IsAlwaysOnTop() const; // Set whether the window should get even reserved keys (modulo platform // restrictions). void SetInterceptAllKeys(bool want_all_keys); // Retrieve the current state of the app window as a dictionary, to pass to // the renderer. void GetSerializedState(base::DictionaryValue* properties) const; // Called by the window API when events can be sent to the window for this // app. void WindowEventsReady(); // Whether the app window wants to be alpha enabled. bool requested_alpha_enabled() const { return requested_alpha_enabled_; } // Whether the app window is created by IME extensions. // TODO(bshe): rename to hide_app_window_in_launcher if it is not used // anywhere other than app_window_launcher_controller after M45. Otherwise, // remove this TODO. bool is_ime_window() const { return is_ime_window_; } void SetAppWindowContentsForTesting(scoped_ptr<AppWindowContents> contents) { app_window_contents_ = contents.Pass(); } protected: ~AppWindow() override; private: // PlatformAppBrowserTest needs access to web_contents() friend class PlatformAppBrowserTest; // content::WebContentsDelegate implementation. void CloseContents(content::WebContents* contents) override; bool ShouldSuppressDialogs(content::WebContents* source) override; content::ColorChooser* OpenColorChooser( content::WebContents* web_contents, SkColor color, const std::vector<content::ColorSuggestion>& suggestions) override; void RunFileChooser(content::WebContents* tab, const content::FileChooserParams& params) override; bool IsPopupOrPanel(const content::WebContents* source) const override; void MoveContents(content::WebContents* source, const gfx::Rect& pos) override; void NavigationStateChanged(content::WebContents* source, content::InvalidateTypes changed_flags) override; void EnterFullscreenModeForTab(content::WebContents* source, const GURL& origin) override; void ExitFullscreenModeForTab(content::WebContents* source) override; bool IsFullscreenForTabOrPending( const content::WebContents* source) const override; void RequestMediaAccessPermission( content::WebContents* web_contents, const content::MediaStreamRequest& request, const content::MediaResponseCallback& callback) override; bool CheckMediaAccessPermission(content::WebContents* web_contents, const GURL& security_origin, content::MediaStreamType type) override; content::WebContents* OpenURLFromTab( content::WebContents* source, const content::OpenURLParams& params) override; void AddNewContents(content::WebContents* source, content::WebContents* new_contents, WindowOpenDisposition disposition, const gfx::Rect& initial_rect, bool user_gesture, bool* was_blocked) override; bool PreHandleKeyboardEvent(content::WebContents* source, const content::NativeWebKeyboardEvent& event, bool* is_keyboard_shortcut) override; void HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) override; void RequestToLockMouse(content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target) override; bool PreHandleGestureEvent(content::WebContents* source, const blink::WebGestureEvent& event) override; // content::WebContentsObserver implementation. void RenderViewCreated(content::RenderViewHost* render_view_host) override; void DidFirstVisuallyNonEmptyPaint() override; // ExtensionRegistryObserver implementation. void OnExtensionUnloaded(content::BrowserContext* browser_context, const Extension* extension, UnloadedExtensionInfo::Reason reason) override; void OnExtensionWillBeInstalled(content::BrowserContext* browser_context, const Extension* extension, bool is_update, bool from_ephemeral, const std::string& old_name) override; // web_modal::WebContentsModalDialogManagerDelegate implementation. void SetWebContentsBlocked(content::WebContents* web_contents, bool blocked) override; bool IsWebContentsVisible(content::WebContents* web_contents) override; void ToggleFullscreenModeForTab(content::WebContents* source, bool enter_fullscreen); // Saves the window geometry/position/screen bounds. void SaveWindowPosition(); // Helper method to adjust the cached bounds so that we can make sure it can // be visible on the screen. See http://crbug.com/145752. void AdjustBoundsToBeVisibleOnScreen(const gfx::Rect& cached_bounds, const gfx::Rect& cached_screen_bounds, const gfx::Rect& current_screen_bounds, const gfx::Size& minimum_size, gfx::Rect* bounds) const; // Loads the appropriate default or cached window bounds. Returns a new // CreateParams that should be used to create the window. CreateParams LoadDefaults(CreateParams params) const; // Load the app's image, firing a load state change when loaded. void UpdateExtensionAppIcon(); // Set the fullscreen state in the native app window. void SetNativeWindowFullscreen(); // Returns true if there is any overlap between the window and the taskbar // (Windows only). bool IntersectsWithTaskbar() const; // Update the always-on-top bit in the native app window. void UpdateNativeAlwaysOnTop(); // Sends the onWindowShown event to the app if the window has been shown. Only // has an effect in tests. void SendOnWindowShownIfShown(); // web_modal::WebContentsModalDialogManagerDelegate implementation. web_modal::WebContentsModalDialogHost* GetWebContentsModalDialogHost() override; // Updates the badge to |image|. Called internally from the image loader // callback. void UpdateBadgeIcon(const gfx::Image& image); // Callback from web_contents()->DownloadFavicon. void DidDownloadFavicon(int id, int http_status_code, const GURL& image_url, const std::vector<SkBitmap>& bitmaps, const std::vector<gfx::Size>& original_bitmap_sizes); // IconImage::Observer implementation. void OnExtensionIconImageChanged(IconImage* image) override; // The browser context with which this window is associated. AppWindow does // not own this object. content::BrowserContext* browser_context_; const std::string extension_id_; // Identifier that is used when saving and restoring geometry for this // window. std::string window_key_; const SessionID session_id_; WindowType window_type_; // Icon shown in the task bar. gfx::Image app_icon_; // Icon URL to be used for setting the app icon. If not empty, app_icon_ will // be fetched and set using this URL. GURL app_icon_url_; // An object to load the app's icon as an extension resource. scoped_ptr<IconImage> app_icon_image_; // Badge for icon shown in the task bar. gfx::Image badge_icon_; // URL to be used for setting the badge on the app icon. GURL badge_icon_url_; // An object to load the badge as an extension resource. scoped_ptr<IconImage> badge_icon_image_; scoped_ptr<NativeAppWindow> native_app_window_; scoped_ptr<AppWindowContents> app_window_contents_; scoped_ptr<AppDelegate> app_delegate_; scoped_ptr<AppWebContentsHelper> helper_; // Manages popup windows (bubbles, tab-modals) visible overlapping the // app window. scoped_ptr<web_modal::PopupManager> popup_manager_; // Bit field of FullscreenType. int fullscreen_types_; // Show has been called, so the window should be shown once the first visually // non-empty paint occurs. bool show_on_first_paint_; // The first visually non-empty paint has completed. bool first_paint_complete_; // Whether the window has been shown or not. bool has_been_shown_; // Whether events can be sent to the window. bool can_send_events_; // Whether the window is hidden or not. Hidden in this context means actively // by the chrome.app.window API, not in an operating system context. For // example windows which are minimized are not hidden, and windows which are // part of a hidden app on OS X are not hidden. Windows which were created // with the |hidden| flag set to true, or which have been programmatically // hidden, are considered hidden. bool is_hidden_; // Whether the delayed Show() call was for an active or inactive window. ShowType delayed_show_type_; // Cache the desired value of the always-on-top property. When windows enter // fullscreen or overlap the Windows taskbar, this property will be // automatically and silently switched off for security reasons. It is // reinstated when the window exits fullscreen and moves away from the // taskbar. bool cached_always_on_top_; // Whether |alpha_enabled| was set in the CreateParams. bool requested_alpha_enabled_; // Whether |is_ime_window| was set in the CreateParams. bool is_ime_window_; base::WeakPtrFactory<AppWindow> image_loader_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(AppWindow); }; } // namespace extensions #endif // EXTENSIONS_BROWSER_APP_WINDOW_APP_WINDOW_H_
[ "scottmg@chromium.org" ]
scottmg@chromium.org
f8d74c35b11b3e4e216fff87aec1b845a840a30f
c4dffea7d5ce204b2a98d003bcb36058390cfa9f
/lib/win64_vc12/llvm/include/llvm/Config/config.h
f686cc484e8f14a0cefc1ded44d95ad66633b336
[]
no_license
yangzhengxing/blenderDev
4053f0ee46a40f357316e120b45474216f8f2614
0258b773be8cdac08286148fe6a7c2fb1cc54bd7
refs/heads/master
2022-12-25T01:24:22.295703
2016-06-05T01:23:57
2016-06-05T01:23:57
60,436,159
0
2
null
2022-12-17T00:00:24
2016-06-05T00:24:05
C++
UTF-8
C++
false
false
18,902
h
/* include/llvm/Config/config.h.cmake corresponding to config.h.in. */ #ifndef CONFIG_H #define CONFIG_H /* Bug report URL. */ #define BUG_REPORT_URL "http://llvm.org/bugs/" /* Define if we have libxml2 */ /* #undef CLANG_HAVE_LIBXML */ /* Relative directory for resource files */ #define CLANG_RESOURCE_DIR "" /* Directories clang will search for headers */ #define C_INCLUDE_DIRS "" /* Default <path> to all compiler invocations for --sysroot=<path>. */ #undef DEFAULT_SYSROOT /* Define if you want backtraces on crash */ #define ENABLE_BACKTRACES /* Define to enable crash overrides */ #define ENABLE_CRASH_OVERRIDES /* Define if position independent code is enabled */ #define ENABLE_PIC /* Define if timestamp information (e.g., __DATE__) is allowed */ #define ENABLE_TIMESTAMPS 1 /* Directory where gcc is installed. */ #undef GCC_INSTALL_PREFIX /* Define to 1 if you have the `arc4random' function. */ /* #undef HAVE_ARC4RANDOM */ /* Define to 1 if you have the `backtrace' function. */ /* #undef HAVE_BACKTRACE */ /* Define to 1 if you have the `bcopy' function. */ #undef HAVE_BCOPY /* Define to 1 if you have the `ceilf' function. */ #define HAVE_CEILF 1 /* Define if the neat program is available */ /* #undef HAVE_CIRCO */ /* Define to 1 if you have the `closedir' function. */ /* #undef HAVE_CLOSEDIR */ /* Define to 1 if you have the <cxxabi.h> header file. */ /* #undef HAVE_CXXABI_H */ /* Define to 1 if you have the <CrashReporterClient.h> header file. */ #undef HAVE_CRASHREPORTERCLIENT_H /* can use __crashreporter_info__ */ #undef HAVE_CRASHREPORTER_INFO /* Define to 1 if you have the declaration of `strerror_s', and to 0 if you don't. */ #define HAVE_DECL_STRERROR_S 1 /* Define to 1 if you have the <dirent.h> header file, and it defines `DIR'. */ /* #undef HAVE_DIRENT_H */ /* Define if you have the GNU dld library. */ #undef HAVE_DLD /* Define to 1 if you have the `dlerror' function. */ /* #undef HAVE_DLERROR */ /* Define to 1 if you have the <dlfcn.h> header file. */ /* #undef HAVE_DLFCN_H */ /* Define if dlopen() is available on this platform. */ /* #undef HAVE_DLOPEN */ /* Define if the dot program is available */ /* #undef HAVE_DOT */ /* Define if the dotty program is available */ /* #undef HAVE_DOTTY */ /* Define if you have the _dyld_func_lookup function. */ #undef HAVE_DYLD /* Define to 1 if you have the <errno.h> header file. */ #define HAVE_ERRNO_H 1 /* Define to 1 if you have the <execinfo.h> header file. */ /* #undef HAVE_EXECINFO_H */ /* Define to 1 if you have the <fcntl.h> header file. */ #define HAVE_FCNTL_H 1 /* Define if the neat program is available */ /* #undef HAVE_FDP */ /* Define to 1 if you have the <fenv.h> header file. */ #define HAVE_FENV_H 1 /* Define if libffi is available on this platform. */ /* #undef HAVE_FFI_CALL */ /* Define to 1 if you have the <ffi/ffi.h> header file. */ /* #undef HAVE_FFI_FFI_H */ /* Define to 1 if you have the <ffi.h> header file. */ /* #undef HAVE_FFI_H */ /* Set to 1 if the finite function is found in <ieeefp.h> */ /* #undef HAVE_FINITE_IN_IEEEFP_H */ /* Define to 1 if you have the `floorf' function. */ #define HAVE_FLOORF 1 /* Define to 1 if you have the `log' function. */ #define HAVE_LOG 1 /* Define to 1 if you have the `log2' function. */ #define HAVE_LOG2 1 /* Define to 1 if you have the `log10' function. */ #define HAVE_LOG10 1 /* Define to 1 if you have the `exp' function. */ #define HAVE_EXP 1 /* Define to 1 if you have the `exp2' function. */ #define HAVE_EXP2 1 /* Define to 1 if you have the `exp10' function. */ /* #undef HAVE_EXP10 */ /* Define to 1 if you have the `fmodf' function. */ #define HAVE_FMODF 1 /* Define to 1 if you have the `futimes' function. */ /* #undef HAVE_FUTIMES */ /* Define to 1 if you have the `futimens' function */ /* #undef HAVE_FUTIMENS */ /* Define to 1 if you have the `getcwd' function. */ /* #undef HAVE_GETCWD */ /* Define to 1 if you have the `getpagesize' function. */ /* #undef HAVE_GETPAGESIZE */ /* Define to 1 if you have the `getrlimit' function. */ /* #undef HAVE_GETRLIMIT */ /* Define to 1 if you have the `getrusage' function. */ /* #undef HAVE_GETRUSAGE */ /* Define to 1 if you have the `gettimeofday' function. */ /* #undef HAVE_GETTIMEOFDAY */ /* Define if the Graphviz program is available */ /* #undef HAVE_GRAPHVIZ */ /* Define if the gv program is available */ /* #undef HAVE_GV */ /* Define to 1 if the system has the type `int64_t'. */ #define HAVE_INT64_T 1 /* Define to 1 if you have the <inttypes.h> header file. */ #define HAVE_INTTYPES_H 1 /* Define to 1 if you have the `isatty' function. */ /* #undef HAVE_ISATTY */ /* Set to 1 if the isinf function is found in <cmath> */ /* #undef HAVE_ISINF_IN_CMATH */ /* Set to 1 if the isinf function is found in <math.h> */ #define HAVE_ISINF_IN_MATH_H 1 /* Set to 1 if the isnan function is found in <cmath> */ /* #undef HAVE_ISNAN_IN_CMATH */ /* Set to 1 if the isnan function is found in <math.h> */ #define HAVE_ISNAN_IN_MATH_H 1 /* Define if you have the libdl library or equivalent. */ /* #undef HAVE_LIBDL */ /* Define to 1 if you have the `imagehlp' library (-limagehlp). */ /* #undef HAVE_LIBIMAGEHLP */ /* Define to 1 if you have the `m' library (-lm). */ #undef HAVE_LIBM /* Define to 1 if you have the `psapi' library (-lpsapi). */ /* #undef HAVE_LIBPSAPI */ /* Define to 1 if you have the `pthread' library (-lpthread). */ /* #undef HAVE_LIBPTHREAD */ /* Define to 1 if you have the `shell32' library (-lshell32). */ /* #undef HAVE_LIBSHELL32 */ /* Define to 1 if you have the `udis86' library (-ludis86). */ #undef HAVE_LIBUDIS86 /* Define to 1 if you have the 'z' library (-lz). */ /* #undef HAVE_LIBZ */ /* Define to 1 if you have the <limits.h> header file. */ #define HAVE_LIMITS_H 1 /* Define if you can use -rdynamic. */ #define HAVE_LINK_EXPORT_DYNAMIC 1 /* Define if you can use -Wl,-R. to pass -R. to the linker, in order to add the current directory to the dynamic linker search path. */ #undef HAVE_LINK_R /* Define to 1 if you have the `longjmp' function. */ /* #undef HAVE_LONGJMP */ /* Define to 1 if you have the <mach/mach.h> header file. */ /* #undef HAVE_MACH_MACH_H */ /* Define to 1 if you have the <mach-o/dyld.h> header file. */ /* #undef HAVE_MACH_O_DYLD_H */ /* Define if mallinfo() is available on this platform. */ /* #undef HAVE_MALLINFO */ /* Define to 1 if you have the <malloc.h> header file. */ #define HAVE_MALLOC_H 1 /* Define to 1 if you have the <malloc/malloc.h> header file. */ /* #undef HAVE_MALLOC_MALLOC_H */ /* Define to 1 if you have the `malloc_zone_statistics' function. */ /* #undef HAVE_MALLOC_ZONE_STATISTICS */ /* Define to 1 if you have the `mkdtemp' function. */ /* #undef HAVE_MKDTEMP */ /* Define to 1 if you have the `mkstemp' function. */ /* #undef HAVE_MKSTEMP */ /* Define to 1 if you have the `mktemp' function. */ /* #undef HAVE_MKTEMP */ /* Define to 1 if you have a working `mmap' system call. */ #undef HAVE_MMAP /* Define if mmap() uses MAP_ANONYMOUS to map anonymous pages, or undefine if it uses MAP_ANON */ #undef HAVE_MMAP_ANONYMOUS /* Define if mmap() can map files into memory */ #undef HAVE_MMAP_FILE /* Define to 1 if you have the <ndir.h> header file, and it defines `DIR'. */ /* #undef HAVE_NDIR_H */ /* Define to 1 if you have the `nearbyintf' function. */ #define HAVE_NEARBYINTF 1 /* Define if the neat program is available */ /* #undef HAVE_NEATO */ /* Define to 1 if you have the `opendir' function. */ /* #undef HAVE_OPENDIR */ /* Define to 1 if you have the `posix_spawn' function. */ /* #undef HAVE_POSIX_SPAWN */ /* Define to 1 if you have the `powf' function. */ /* #undef HAVE_POWF */ /* Define to 1 if you have the `pread' function. */ /* #undef HAVE_PREAD */ /* Define if libtool can extract symbol lists from object files. */ #undef HAVE_PRELOADED_SYMBOLS /* Define to have the %a format string */ #undef HAVE_PRINTF_A /* Have pthread_getspecific */ /* #undef HAVE_PTHREAD_GETSPECIFIC */ /* Define to 1 if you have the <pthread.h> header file. */ /* #undef HAVE_PTHREAD_H */ /* Have pthread_mutex_lock */ /* #undef HAVE_PTHREAD_MUTEX_LOCK */ /* Have pthread_rwlock_init */ /* #undef HAVE_PTHREAD_RWLOCK_INIT */ /* Define to 1 if srand48/lrand48/drand48 exist in <stdlib.h> */ /* #undef HAVE_RAND48 */ /* Define to 1 if you have the `readdir' function. */ /* #undef HAVE_READDIR */ /* Define to 1 if you have the `realpath' function. */ /* #undef HAVE_REALPATH */ /* Define to 1 if you have the `rintf' function. */ #undef HAVE_RINTF /* Define to 1 if you have the `round' function. */ /* #undef HAVE_ROUND */ /* Define to 1 if you have the `roundf' function. */ #undef HAVE_ROUNDF /* Define to 1 if you have the `sbrk' function. */ /* #undef HAVE_SBRK */ /* Define to 1 if you have the `setenv' function. */ /* #undef HAVE_SETENV */ /* Define to 1 if you have the `setjmp' function. */ /* #undef HAVE_SETJMP */ /* Define to 1 if you have the `setrlimit' function. */ /* #undef HAVE_SETRLIMIT */ /* Define if you have the shl_load function. */ #undef HAVE_SHL_LOAD /* Define to 1 if you have the `siglongjmp' function. */ /* #undef HAVE_SIGLONGJMP */ /* Define to 1 if you have the <signal.h> header file. */ #define HAVE_SIGNAL_H 1 /* Define to 1 if you have the `sigsetjmp' function. */ /* #undef HAVE_SIGSETJMP */ /* Define to 1 if you have the <stdint.h> header file. */ #define HAVE_STDINT_H 1 /* Set to 1 if the std::isinf function is found in <cmath> */ #undef HAVE_STD_ISINF_IN_CMATH /* Set to 1 if the std::isnan function is found in <cmath> */ #undef HAVE_STD_ISNAN_IN_CMATH /* Define to 1 if you have the `strdup' function. */ /* #undef HAVE_STRDUP */ /* Define to 1 if you have the `strerror' function. */ #define HAVE_STRERROR 1 /* Define to 1 if you have the `strerror_r' function. */ /* #undef HAVE_STRERROR_R */ /* Define to 1 if you have the `strtof' function. */ /* #undef HAVE_STRTOF */ /* Define to 1 if you have the `strtoll' function. */ #define HAVE_STRTOLL 1 /* Define to 1 if you have the `strtoq' function. */ /* #undef HAVE_STRTOQ */ /* Define to 1 if you have the `sysconf' function. */ #undef HAVE_SYSCONF /* Define to 1 if you have the <sys/dir.h> header file, and it defines `DIR'. */ /* #undef HAVE_SYS_DIR_H */ /* Define to 1 if you have the <sys/ioctl.h> header file. */ /* #undef HAVE_SYS_IOCTL_H */ /* Define to 1 if you have the <sys/mman.h> header file. */ /* #undef HAVE_SYS_MMAN_H */ /* Define to 1 if you have the <sys/ndir.h> header file, and it defines `DIR'. */ /* #undef HAVE_SYS_NDIR_H */ /* Define to 1 if you have the <sys/param.h> header file. */ /* #undef HAVE_SYS_PARAM_H */ /* Define to 1 if you have the <sys/resource.h> header file. */ /* #undef HAVE_SYS_RESOURCE_H */ /* Define to 1 if you have the <sys/stat.h> header file. */ #define HAVE_SYS_STAT_H 1 /* Define to 1 if you have the <sys/time.h> header file. */ /* #undef HAVE_SYS_TIME_H */ /* Define to 1 if you have the <sys/types.h> header file. */ /* #undef HAVE_SYS_TYPES_H */ /* Define to 1 if you have the <sys/uio.h> header file. */ /* #undef HAVE_SYS_UIO_H */ /* Define to 1 if you have <sys/wait.h> that is POSIX.1 compatible. */ /* #undef HAVE_SYS_WAIT_H */ /* Define if the setupterm() function is supported this platform. */ /* #undef HAVE_TERMINFO */ /* Define to 1 if you have the <termios.h> header file. */ /* #undef HAVE_TERMIOS_H */ /* Define if the neat program is available */ /* #undef HAVE_TWOPI */ /* Define to 1 if the system has the type `uint64_t'. */ #define HAVE_UINT64_T 1 /* Define to 1 if you have the <unistd.h> header file. */ /* #undef HAVE_UNISTD_H */ /* Define to 1 if you have the <utime.h> header file. */ /* #undef HAVE_UTIME_H */ /* Define to 1 if the system has the type `u_int64_t'. */ /* #undef HAVE_U_INT64_T */ /* Define to 1 if you have the <valgrind/valgrind.h> header file. */ /* #undef HAVE_VALGRIND_VALGRIND_H */ /* Define to 1 if you have the `writev' function. */ /* #undef HAVE_WRITEV */ /* Define if the xdot.py program is available */ /* #undef HAVE_XDOT */ /* Define to 1 if you have the <zlib.h> header file. */ /* #undef HAVE_ZLIB_H */ /* Have host's _alloca */ /* #undef HAVE__ALLOCA */ /* Have host's __alloca */ /* #undef HAVE___ALLOCA */ /* Have host's __ashldi3 */ /* #undef HAVE___ASHLDI3 */ /* Have host's __ashrdi3 */ /* #undef HAVE___ASHRDI3 */ /* Have host's __chkstk */ #define HAVE___CHKSTK 1 /* Have host's __cmpdi2 */ /* #undef HAVE___CMPDI2 */ /* Have host's __divdi3 */ /* #undef HAVE___DIVDI3 */ /* Define to 1 if you have the `__dso_handle' function. */ #undef HAVE___DSO_HANDLE /* Have host's __fixdfdi */ /* #undef HAVE___FIXDFDI */ /* Have host's __fixsfdi */ /* #undef HAVE___FIXSFDI */ /* Have host's __floatdidf */ /* #undef HAVE___FLOATDIDF */ /* Have host's __lshrdi3 */ /* #undef HAVE___LSHRDI3 */ /* Have host's __main */ /* #undef HAVE___MAIN */ /* Have host's __moddi3 */ /* #undef HAVE___MODDI3 */ /* Have host's __udivdi3 */ /* #undef HAVE___UDIVDI3 */ /* Have host's __umoddi3 */ /* #undef HAVE___UMODDI3 */ /* Have host's ___chkstk */ /* #undef HAVE____CHKSTK */ /* Linker version detected at compile time. */ #undef HOST_LINK_VERSION /* Installation directory for binary executables */ /* #undef LLVM_BINDIR */ /* Time at which LLVM was configured */ /* #undef LLVM_CONFIGTIME */ /* Installation directory for data files */ /* #undef LLVM_DATADIR */ /* Target triple LLVM will generate code for by default */ #define LLVM_DEFAULT_TARGET_TRIPLE "x86_64-pc-win32" /* Installation directory for documentation */ /* #undef LLVM_DOCSDIR */ /* Define if threads enabled */ #define LLVM_ENABLE_THREADS 1 /* Define if zlib compression is available */ #define LLVM_ENABLE_ZLIB 0 /* Installation directory for config files */ /* #undef LLVM_ETCDIR */ /* Has gcc/MSVC atomic intrinsics */ #define LLVM_HAS_ATOMICS 1 /* Host triple LLVM will be executed on */ #define LLVM_HOST_TRIPLE "x86_64-pc-win32" /* Installation directory for include files */ /* #undef LLVM_INCLUDEDIR */ /* Installation directory for .info files */ /* #undef LLVM_INFODIR */ /* Installation directory for man pages */ /* #undef LLVM_MANDIR */ /* LLVM architecture name for the native architecture, if available */ #define LLVM_NATIVE_ARCH X86 /* LLVM name for the native AsmParser init function, if available */ #define LLVM_NATIVE_ASMPARSER LLVMInitializeX86AsmParser /* LLVM name for the native AsmPrinter init function, if available */ #define LLVM_NATIVE_ASMPRINTER LLVMInitializeX86AsmPrinter /* LLVM name for the native Disassembler init function, if available */ #define LLVM_NATIVE_DISASSEMBLER LLVMInitializeX86Disassembler /* LLVM name for the native Target init function, if available */ #define LLVM_NATIVE_TARGET LLVMInitializeX86Target /* LLVM name for the native TargetInfo init function, if available */ #define LLVM_NATIVE_TARGETINFO LLVMInitializeX86TargetInfo /* LLVM name for the native target MC init function, if available */ #define LLVM_NATIVE_TARGETMC LLVMInitializeX86TargetMC /* Define if this is Unixish platform */ /* #undef LLVM_ON_UNIX */ /* Define if this is Win32ish platform */ #define LLVM_ON_WIN32 1 /* Define to path to circo program if found or 'echo circo' otherwise */ /* #undef LLVM_PATH_CIRCO */ /* Define to path to dot program if found or 'echo dot' otherwise */ /* #undef LLVM_PATH_DOT */ /* Define to path to dotty program if found or 'echo dotty' otherwise */ /* #undef LLVM_PATH_DOTTY */ /* Define to path to fdp program if found or 'echo fdp' otherwise */ /* #undef LLVM_PATH_FDP */ /* Define to path to Graphviz program if found or 'echo Graphviz' otherwise */ /* #undef LLVM_PATH_GRAPHVIZ */ /* Define to path to gv program if found or 'echo gv' otherwise */ /* #undef LLVM_PATH_GV */ /* Define to path to neato program if found or 'echo neato' otherwise */ /* #undef LLVM_PATH_NEATO */ /* Define to path to twopi program if found or 'echo twopi' otherwise */ /* #undef LLVM_PATH_TWOPI */ /* Define to path to xdot.py program if found or 'echo xdot' otherwise */ /* #undef LLVM_PATH_XDOT */ /* Installation prefix directory */ #define LLVM_PREFIX "C:/dev/lib/win64_vc12/llvm" /* Define if we have the Intel JIT API runtime support library */ /* #undef LLVM_USE_INTEL_JITEVENTS */ /* Define if we have the oprofile JIT-support library */ /* #undef LLVM_USE_OPROFILE */ /* Major version of the LLVM API */ #define LLVM_VERSION_MAJOR 3 /* Minor version of the LLVM API */ #define LLVM_VERSION_MINOR 4 /* Define if the OS needs help to load dependent libraries for dlopen(). */ /* #undef LTDL_DLOPEN_DEPLIBS */ /* Define to the sub-directory in which libtool stores uninstalled libraries. */ #undef LTDL_OBJDIR /* Define to the extension used for shared libraries, say, ".so". */ #define LTDL_SHLIB_EXT ".dll" /* Define to the system default library search path. */ /* #undef LTDL_SYSSEARCHPATH */ /* Define if /dev/zero should be used when mapping RWX memory, or undefine if its not necessary */ #undef NEED_DEV_ZERO_FOR_MMAP /* Define if dlsym() requires a leading underscore in symbol names. */ #undef NEED_USCORE /* Define to the address where bug reports for this package should be sent. */ #define PACKAGE_BUGREPORT "http://llvm.org/bugs/" /* Define to the full name of this package. */ #define PACKAGE_NAME "LLVM" /* Define to the full name and version of this package. */ #define PACKAGE_STRING "LLVM 3.4.2" /* Define to the one symbol short name of this package. */ #undef PACKAGE_TARNAME /* Define to the version of this package. */ #define PACKAGE_VERSION "3.4.2" /* Define as the return type of signal handlers (`int' or `void'). */ #define RETSIGTYPE void /* Define to 1 if the `S_IS*' macros in <sys/stat.h> do not work properly. */ #undef STAT_MACROS_BROKEN /* Define to 1 if you have the ANSI C header files. */ #undef STDC_HEADERS /* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */ #undef TIME_WITH_SYS_TIME /* Define to 1 if your <sys/time.h> declares `struct tm'. */ #undef TM_IN_SYS_TIME /* Define if use udis86 library */ #undef USE_UDIS86 /* Type of 1st arg on ELM Callback */ #define WIN32_ELMCB_PCSTR PCSTR /* Define to empty if `const' does not conform to ANSI C. */ #undef const /* Define to `int' if <sys/types.h> does not define. */ #undef pid_t /* Define to `unsigned int' if <sys/types.h> does not define. */ #undef size_t /* Define to a function replacing strtoll */ /* #undef strtoll */ /* Define to a function implementing strtoull */ /* #undef strtoull */ /* Define to a function implementing stricmp */ #define stricmp _stricmp /* Define to a function implementing strdup */ #define strdup _strdup /* Define to 1 if you have the `_chsize_s' function. */ #define HAVE__CHSIZE_S 1 /* Added by Kevin -- Maximum path length */ #define MAXPATHLEN 160 #endif
[ "493134808@qq.com" ]
493134808@qq.com
8391f4ca304af9bd394dfa73276df6650abd5264
53b24c1093781e3d859e26c2075597c51729b1b1
/linear.cpp
dca8beaf86e99f012dc87ba91aeb3aadb81bb9c7
[]
no_license
Hemant-Negi/Interview_Prep
a95a9301f57c6bbf59d6c5fff81b8bfb05bd2c06
c6bee61de1513cf2edce7c4e652b8093e8cefb30
refs/heads/main
2023-06-14T05:02:16.440171
2021-07-10T15:42:14
2021-07-10T15:42:14
384,732,011
0
0
null
null
null
null
UTF-8
C++
false
false
358
cpp
#include <iostream> #include <algorithm> #include <vector> #include <string> using namespace std; int main(){ int k; cin>>k; int a[100] = {12,13,10,9,5,22}; int len = sizeof(a)/sizeof(a[0]); int i; for(i=0;i<len;i++){ if(a[i]==k){ cout<<"found at index "<<i<<endl; break; } } if(i==len){ cout<<"not found in array"<<endl; } return 0; }
[ "noreply@github.com" ]
Hemant-Negi.noreply@github.com
c941bcc1e9cf7d12e9530933399a7f3ec2ee2f4d
5ee222a34cc567d193cd91afe8fea43c8058d8f3
/Camera3.h
e4414bd8dcd099b6dea0fdb6c7accfcbe67d467a
[]
no_license
KamilChmielewski/DirectXProject
d9a843ec5b37ac8c4f4e1fb582fef652265da9d2
9f44ebcdad3490aff5be3b947fc91d4dfa1f4fec
refs/heads/master
2021-04-26T23:12:37.140368
2018-03-05T16:32:31
2018-03-05T16:32:31
123,947,550
0
0
null
null
null
null
UTF-8
C++
false
false
1,182
h
#pragma once #include <windows.h> #include <d3d11_1.h> #include <d3dcompiler.h> #include <directxmath.h> #include <iostream> using namespace DirectX; class Camera3 { private: XMFLOAT3 _eye; XMFLOAT3 _at; XMFLOAT3 _up; FLOAT _windowWidth; FLOAT _windowHeight; FLOAT _nearDepth; FLOAT _farDepth; XMFLOAT4X4 _view; XMFLOAT4X4 _projection; float horizontalAngle = 3.14f; float verticalAngle = 0.0f; float initalFoV = 45.0f; float speed = 3.0f; float mouseSpeed = 0.05f; public: Camera3(XMFLOAT3 position, XMFLOAT3 at, XMFLOAT3 up, FLOAT windowWidth, FLOAT windowHeight, FLOAT nearDepth, FLOAT farDepth); ~Camera3(); void Update(float deltaTime); XMFLOAT4X4 GetView() const { return _view; } XMFLOAT4X4 GetProjection() const { return _projection; } XMFLOAT4X4 GetViewProjection() const; XMFLOAT3 GetPosition() const { return _eye; } XMFLOAT3 GetLookAt() const { return _at; } XMFLOAT3 GetUp() const { return _up; } void SetPosition(XMFLOAT3 position) { _eye = position; } void SetLookAt(XMFLOAT3 lookAt) { _at = lookAt; } void SetUp(XMFLOAT3 up) { _up = up; } void Reshape(FLOAT windowWidth, FLOAT windowHeight, FLOAT nearDepth, FLOAT farDepth); };
[ "kamilchmielewski24@yahoo.com" ]
kamilchmielewski24@yahoo.com
78c2e47e8853a41fff1f0f99e42dc5a52effaf48
5fbfe741e7823f7eafd819177d6ad075bd9598d9
/SpaceShipGame/src/States/GameState.cpp
edbccfdeca4b412b9b883addf3663d8e1c579231
[]
no_license
OfficialLahusa/SpaceShip
062a81b69b55199906296d7f5724eb42e688864a
991a50478cae564015d1424a196cf6c1676e501a
refs/heads/master
2021-06-27T03:01:22.018966
2020-11-17T13:51:29
2020-11-17T13:51:29
166,654,729
0
0
null
null
null
null
UTF-8
C++
false
false
13,966
cpp
#include "GameState.hpp" /* Returns the animated player sprite, if given the skin id, the direction the player is facing, and the frame */ /* Directions: 0: Down, 1: Right, 2: Top, 3: Left */ /* Frames: 0: Standing, 1: Walk1, 2: Walk2 */ sf::IntRect getPlayerSprite(unsigned int speed, unsigned int shotstate) { return sf::IntRect(sf::Vector2i(128 * 3 * speed + shotstate * 128, 0), sf::Vector2i(128, 128)); } /* Returns the skin name by ID */ std::string getSkinName(unsigned int skin) { switch (skin) { default: return "Unnamed Character"; } } /* Returns the rotated shot origin position */ sf::Vector2f getShotOrigin(unsigned int shotState, float angle) { sf::Vector2f offsetVec; shotState %= 2; if (shotState == 0) { offsetVec = sf::Vector2f(-13*TILE_SCALING, 28*TILE_SCALING); } else { offsetVec = sf::Vector2f(13*TILE_SCALING, 28*TILE_SCALING); } float vecLength = sqrtf(offsetVec.x*offsetVec.x + offsetVec.y*offsetVec.y); float offsetVectorRotation = atan2f(offsetVec.x / vecLength, offsetVec.y / vecLength); offsetVec = sf::Vector2f(cos(offsetVectorRotation + angle / 180 * sse::math::PI)*vecLength, sin(offsetVectorRotation + angle / 180 * sse::math::PI)*vecLength); //std::cout << "X:" << offsetVec.x << "; Y:" << offsetVec.y << "; Angle: " << offsetVectorRotation << "; Length: " << vecLength << "\n"; return offsetVec; } /* Returns the meteorite sprite by ID */ sf::IntRect getMeteoriteSprite(unsigned int ID) { return sf::IntRect(sf::Vector2i(0, 64 * ID), sf::Vector2i(64, 64)); } /* Returns the health bar sprite by health */ sf::IntRect getHealthBarSprite(int current, int max, bool isProtected) { if (isProtected) { return sf::IntRect(sf::Vector2i(0, HEALTH_BAR_PROTECTED * HEALTH_BAR_HEIGHT), sf::Vector2i(HEALTH_BAR_WIDTH, HEALTH_BAR_HEIGHT)); } int verticalOffset = -(int)((((float)current / (float)max)*(float)(HEALTH_BAR_VARIATIONS - 1)) - (float)(HEALTH_BAR_VARIATIONS - 1)); return sf::IntRect(sf::Vector2i(0, verticalOffset * HEALTH_BAR_HEIGHT), sf::Vector2i(HEALTH_BAR_WIDTH, HEALTH_BAR_HEIGHT)); } namespace sse { GameState::GameState(GameDataRef data) : m_data(data) { } GameState::~GameState() { } bool GameState::Init() { /* Player Setup */ playerSprites.loadFromFile("res/raumschiffe_spritesheet.png"); player = Player(0, 0, sf::Vector2f(m_data->window.getSize().x / 2, m_data->window.getSize().y/2)); player.shape.setOrigin(64 * TILE_SCALING, 64 * TILE_SCALING); player.shape.setTexture(&playerSprites); player.shape.setTextureRect(getPlayerSprite(1, 1)); /* Combat Setup */ particleTexture.loadFromFile("res/particles.png"); basicShot.shape.setSize(sf::Vector2f(16 * TILE_SCALING, 16 * TILE_SCALING)); basicShot.shape.setTexture(&particleTexture); basicShot.shape.setTextureRect(sf::IntRect(sf::Vector2i(0, 0), sf::Vector2i(16, 16))); basicShot.shape.setOrigin(8 * TILE_SCALING, 8 * TILE_SCALING); meteoriteTexture.loadFromFile("res/meteorites.png"); basicMeteorite.shape.setSize(sf::Vector2f(64 * TILE_SCALING, 64 * TILE_SCALING)); basicMeteorite.shape.setTexture(&meteoriteTexture); basicMeteorite.shape.setTextureRect(sf::IntRect(sf::Vector2i(0, 0), sf::Vector2i(64, 64))); basicMeteorite.shape.setOrigin(32 * TILE_SCALING, 32 * TILE_SCALING); healthBarTexture.loadFromFile("res/healthbar.png"); healthBar.setSize(sf::Vector2f(HEALTH_BAR_WIDTH * TILE_SCALING, HEALTH_BAR_HEIGHT * TILE_SCALING)); healthBar.setOrigin(HEALTH_BAR_WIDTH * TILE_SCALING / 2, HEALTH_BAR_HEIGHT * TILE_SCALING); healthBar.setTexture(&healthBarTexture); /* Collision detection and resolution variables */ collisionShape.setSize(sf::Vector2f(16, 16)); collisionShape.setScale(TILE_SCALING, TILE_SCALING); collisionShape.setFillColor(sf::Color::Red); /* UI Elements */ font.loadFromFile("res/CarbonBlock.ttf"); xText.setFillColor(sf::Color::White); xText.setPosition(20, 30); xText.setCharacterSize(35); xText.setFont(font); /* Sound Setup */ shotBuffer.loadFromFile("res/laser_shot.wav"); engineBuffer.loadFromFile("res/thruster.wav"); shotSound.setBuffer(shotBuffer); engineSound.setBuffer(engineBuffer); return true; } bool GameState::HandleInput(float dt) { sf::Event evnt; while (m_data->window.pollEvent(evnt)) { if (evnt.type == sf::Event::Closed || sf::Keyboard::isKeyPressed(sf::Keyboard::Escape)) { m_data->window.close(); } } /* Input Handling */ /* Get Joystick axis input and map it correctly + remove calibration faults */ float axisX, axisY, axisU, axisV, axisZ, axisR; axisX = std::max(std::min(sf::Joystick::getAxisPosition(0, sf::Joystick::X), 100.f), -100.f); if (axisX <= CALIBRATION_FAULT_THRESHOLD && axisX >= -CALIBRATION_FAULT_THRESHOLD) axisX = 0.f; axisY = std::max(std::min(sf::Joystick::getAxisPosition(0, sf::Joystick::Y), 100.f), -100.f); if (axisY <= CALIBRATION_FAULT_THRESHOLD && axisY >= -CALIBRATION_FAULT_THRESHOLD) axisY = 0.f; axisU = std::max(std::min(sf::Joystick::getAxisPosition(0, sf::Joystick::U), 100.f), -100.f); if (axisU <= CALIBRATION_FAULT_THRESHOLD && axisU >= -CALIBRATION_FAULT_THRESHOLD) axisU = 0.f; axisV = std::max(std::min(sf::Joystick::getAxisPosition(0, sf::Joystick::V), 100.f), -100.f); if (axisV <= CALIBRATION_FAULT_THRESHOLD && axisV >= -CALIBRATION_FAULT_THRESHOLD) axisV = 0.f; axisZ = std::max(std::min(sf::Joystick::getAxisPosition(0, sf::Joystick::Z), 100.f), -100.f); if (axisZ <= CALIBRATION_FAULT_THRESHOLD && axisZ >= -CALIBRATION_FAULT_THRESHOLD) axisZ = 0.f; sf::Vector2f direction(axisX / 100.f, axisY / 100.f); float vectorLength = std::max(sqrtf(direction.x*direction.x + direction.y*direction.y), 0.00000001f); direction.x = direction.x / vectorLength; direction.y = direction.y / vectorLength; float angle = -atan2f(direction.x, direction.y) * 180 / sse::math::PI + 90; if (direction.x == 0 && direction.y == 0) { // do nothing } else { player.shape.setRotation(angle); } //std::cout << direction.x << "; " << direction.y << "; Angle: " << angle << "deg\n"; if (axisZ != 0) { if (player.shotState == 0 || (player.shotState > 1 && player.hitCooldown == 0.f)) { player.shotState = 1; player.hitCooldown += 0.1f * 1/player.fireSpeed; sf::Vector2f origin = getShotOrigin(player.shotState, player.shape.getRotation()); shots.push_back(basicShot); shots[shots.size() - 1].shape.setPosition(player.shape.getPosition().x + origin.x, player.shape.getPosition().y + origin.y); shots[shots.size() - 1].shape.setRotation(player.shape.getRotation()); shotSound.play(); } else if(player.hitCooldown == 0.f) { player.shotState = 2; player.hitCooldown += 0.1f * 1/player.fireSpeed; sf::Vector2f origin = getShotOrigin(player.shotState, player.shape.getRotation()); shots.push_back(basicShot); shots[shots.size() - 1].shape.setPosition(player.shape.getPosition().x + origin.x, player.shape.getPosition().y + origin.y); shots[shots.size() - 1].shape.setRotation(player.shape.getRotation()); shotSound.play(); } } else { player.shotState = 0; } if (sf::Joystick::isButtonPressed(0, 0)) { player.speed = 1; if (!engineSound.getLoop()) { engineSound.setLoop(true); } if (engineSound.getStatus() != sf::SoundSource::Status::Playing) { engineSound.play(); } } else { player.speed = 0; engineSound.setLoop(false); engineSound.stop(); } if (sf::Joystick::isButtonPressed(0, 4) && player.hitCooldown == 0) { /*player.fireSpeed -= 0.2f; player.hitCooldown += 0.5f;*/ } if (sf::Joystick::isButtonPressed(0, 5) && player.hitCooldown == 0) { /*player.fireSpeed += 0.2f;*/ player.hitCooldown += 0.1f; for (unsigned int i = 0; i < meteorites.size(); i++) { meteorites[i].currentHP = std::max(0, meteorites[i].currentHP - 1); } } //std::cout << "FireSpeed: " << player.fireSpeed << "\n"; player.shape.move(direction.x * dt * player.NormalSpeed * (1 + (player.EngineBonus*player.speed)), direction.y * dt * player.NormalSpeed * (1 + (player.EngineBonus * player.speed))); /* Update Player */ player.update(); return true; } bool GameState::Update(float dt) { /* Spawn Meteorites */ if (sse::random::randomReal<float>(0, 1) <= METEORITE_SPAWN_CHANCE) { meteorites.push_back(basicMeteorite); float spawnAngle = sse::random::randomReal<float>(0, 360); sf::Vector2f spawnVec(cos(spawnAngle / 180.f * sse::math::PI), sin(spawnAngle / 180.f * sse::math::PI)); meteorites[meteorites.size() - 1].shape.setPosition(player.shape.getPosition().x + spawnVec.x * METEORITE_SPAWN_DISTANCE * TILE_SCALING, player.shape.getPosition().y + spawnVec.y * METEORITE_SPAWN_DISTANCE * TILE_SCALING); meteorites[meteorites.size() - 1].movementAngle = fmod(spawnAngle + 180.f, 360); meteorites[meteorites.size() - 1].rotationSpeed = sse::random::randomReal<float>(METEORITE_ROTATIONSPEED_MIN, METEORITE_ROTATIONSPEED_MAX); meteorites[meteorites.size() - 1].speed = sse::random::randomReal<float>(METEORITE_SPEED_MIN, METEORITE_SPEED_MAX); meteorites[meteorites.size() - 1].maxHP = sse::random::randomInteger<int>(METEORITE_HP_MIN, METEORITE_HP_MAX); meteorites[meteorites.size() - 1].currentHP = meteorites[meteorites.size() - 1].maxHP; meteorites[meteorites.size() - 1].SpriteID = sse::random::randomInteger<int>(0, METEORITE_SPRITE_COUNT - 1); meteorites[meteorites.size() - 1].shape.setTextureRect(getMeteoriteSprite(meteorites[meteorites.size() - 1].SpriteID)); } /* Update Meteorites */ for (unsigned int i = 0; i < meteorites.size(); i++) { meteorites[i].shape.rotate(meteorites[i].rotationSpeed * dt); sf::Vector2f transformation(cos(meteorites[i].movementAngle / 180.f * sse::math::PI)*meteorites[i].speed*dt, sin(meteorites[i].movementAngle / 180.f * sse::math::PI)*meteorites[i].speed*dt); meteorites[i].shape.move(transformation); } /* Update Shots */ for (unsigned int i = 0; i < shots.size(); i++) { float rot = shots[i].shape.getRotation(); shots[i].shape.move(shots[i].speed * dt * cos(rot / 180 * sse::math::PI), shots[i].speed * dt * sin(rot / 180 * sse::math::PI)); } /* Update Cooldowns for all entities */ player.shotCooldown -= dt; if (player.shotCooldown <= 0.f) { player.shotCooldown = 0.f; } player.playerWalkCooldown -= dt; if (player.playerWalkCooldown <= 0.f) { player.playerWalkCooldown = 0.f; } player.hitCooldown -= dt; if (player.hitCooldown <= 0.f) { player.hitCooldown = 0.f; } for (unsigned int i = 0; i < meteorites.size(); i++) { meteorites[i].lifetime += dt; } for (unsigned int i = 0; i < shots.size(); i++) { shots[i].lifetime += dt; } /* Collision detection */ /* for (unsigned int x = 0; x < area.x(); x++) { for (unsigned int y = 0; y < area.y(); y++) { collisionShape.setPosition((x + INFO_WIDTH) * 16 * TILE_SCALING, y * 16 * TILE_SCALING + 8 * TILE_SCALING); if (area.at(x, y) != 0 && area.at(x, y) != 1) { collisionBounds = collisionShape.getGlobalBounds(); // Detect for every player for (unsigned int i = 0; i < players.size(); i++) { playerBounds = players[i].shape.getGlobalBounds(); if (collisionBounds.intersects(playerBounds)) { //https://www.youtube.com/watch?v=l2iCYCLi6MU for reference //Delta vector between the centers of both axis-aligned boxes sf::Vector2f translation( (collisionBounds.left + collisionBounds.width / 2) - (playerBounds.left + playerBounds.width / 2), (collisionBounds.top + collisionBounds.height / 2) - (playerBounds.top + playerBounds.height / 2) ); sf::Vector2f colliderHalfSize(collisionBounds.width / 2, collisionBounds.height / 2); sf::Vector2f playerHalfSize(playerBounds.width / 2, playerBounds.height / 2); // Negative intersection values indicate a collision float intersectX = abs(translation.x) - (colliderHalfSize.x + playerHalfSize.x); float intersectY = abs(translation.y) - (colliderHalfSize.y + playerHalfSize.y); // Move the player along the axis of least intersection if (intersectX > intersectY) { if (translation.x > 0) { players[i].shape.move(intersectX, 0.f); } else { players[i].shape.move(-intersectX, 0.f); } } else { if (translation.y > 0) { players[i].shape.move(0, intersectY); } else { players[i].shape.move(0, -intersectY); } } } } } } */ /* Powerup pickup */ /* Damage player */ /* Clear Entities if their lifetime exceeds the maximum */ meteorites.erase(std::remove_if(meteorites.begin(), meteorites.end(), [](Meteorite val) { return val.lifetime > METEORITE_MAXIMUM_LIFETIME; }), meteorites.end()); shots.erase(std::remove_if(shots.begin(), shots.end(), [](Shot val) { return val.lifetime >= SHOT_MAXIMUM_LIFETIME; }), shots.end()); return true; } bool GameState::Render(float dt) { m_data->window.clear(sf::Color(20, 20, 20, 255)); //sf::Color(40, 60, 90, 255) /* Render Player */ player.shape.setTextureRect(getPlayerSprite(player.speed, player.shotState)); m_data->window.draw(player.shape); /* Render Shots */ for (unsigned int i = 0; i < shots.size(); i++) { m_data->window.draw(shots[i].shape); } /* Render Meteorites */ for (unsigned int i = 0; i < meteorites.size(); i++) { m_data->window.draw(meteorites[i].shape); healthBar.setTextureRect(getHealthBarSprite(meteorites[i].currentHP, meteorites[i].maxHP, meteorites[i].isProtected)); healthBar.setPosition(meteorites[i].shape.getPosition()); healthBar.move(0, -15 * TILE_SCALING); m_data->window.draw(healthBar); } /* Draw Text */ xText.setString( "FPS: " + std::to_string((int)(1.f / dt)) + ", X: "+ std::to_string((int)player.shape.getPosition().x) + ", Y: " + std::to_string((int)player.shape.getPosition().y) + ", Shots: " + std::to_string(shots.size()) + ", Meteorites: " + std::to_string(meteorites.size()) ); m_data->window.draw(xText); m_data->window.display(); return true; } }
[ "lassehuber@outlook.de" ]
lassehuber@outlook.de
7acd6aab4774f2ff09ea27633a65cdde2d4371da
cc79412ad1fc0cfe56eb3719e34dab5dd43dd753
/GameFramework/src/BehaviourTrees/Actions/MoveTowards.cpp
9516ab044549b24c8a613182a983e2c690071610
[ "MIT" ]
permissive
lcomstive/AIE_AIForGames
af64dba38ac5cad8cd05cc74676a4e41a5dc91ba
4128b9984a86111871864c904a34da04c12c3293
refs/heads/main
2023-06-21T02:15:27.904570
2021-07-30T14:00:52
2021-07-30T14:00:52
380,891,539
0
0
null
null
null
null
UTF-8
C++
false
false
725
cpp
#include <Framework/BehaviourTrees/Actions/MoveTowards.hpp> using namespace Framework::BT; BehaviourResult MoveTowards::Execute(GameObject* go) { if (GetValuesFromContext) { TargetID = GetContext<unsigned int>("Target", -1); Speed = GetContext("Speed", Speed <= 0 ? 100.0f : Speed); } if (TargetID == (unsigned int)-1) return BehaviourResult::Failure; GameObject* target = GameObject::FromID(TargetID); Vec2 position = go->GetPosition(); Vec2 targetVel = (target->GetPosition() - position).Normalized(); /* float rotation = atan2(targetVel.x, targetVel.y); go->SetRotation(rotation * 50.0f); */ go->SetPosition(position + go->GetForward() * Speed * GetFrameTime()); return BehaviourResult::Success; }
[ "lcomstive@hotmail.com" ]
lcomstive@hotmail.com
2621b6d3c6fe23a57bcbdd149fa35a18f1698c40
c6c4563b4326e40095dd2a1f5d0b2b14ffdab01b
/src/classify_client/main.cpp
590b651ebb9651b1e56bc2f4de4de08ac7aeecca
[]
no_license
prcups/RubbishClassifyFrontend
0e584c19bff05989d92763a843eebc72d4463f96
aa71f18694bc8519c01b70166eb1d5bf2d070a4a
refs/heads/master
2023-08-31T11:52:49.944339
2021-04-19T12:57:44
2021-04-19T12:57:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
719
cpp
#include <QGuiApplication> #include <QQmlApplicationEngine> #include "../classify_utils/classify_utils.h" int main(int argc, char *argv[]) { #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #endif QGuiApplication app(argc, argv); QQmlApplicationEngine engine; qmlRegisterType<Classify_utils>("Classify.utils", 1, 0, "Classify"); const QUrl url(QStringLiteral("qrc:/main.qml")); QObject::connect( &engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) { if (!obj && url == objUrl) QCoreApplication::exit(-1); }, Qt::QueuedConnection); engine.load(url); return app.exec(); }
[ "prcups@163.com" ]
prcups@163.com
95a8305c1ead28c34ae778bf698eed3b09585e23
a9a76aa296767db6407b5491116c59395c7af53a
/codes/cpp/lib/gurobi_ukp_model.hpp
eade4f2bcf80b9dbf2e3fc4771b6a821e242079d
[ "Unlicense" ]
permissive
henriquebecker91/masters
6a050f9b8eae96d4a1b3cbca1276b9e404cf3f4e
df9b63324dbef72080bdd2374f61caf6512b2e54
refs/heads/master
2023-08-30T02:13:55.659539
2023-08-29T18:43:27
2023-08-29T18:43:27
41,876,890
1
2
null
null
null
null
UTF-8
C++
false
false
3,599
hpp
#ifndef HBM_GUROBI_UKP_MODEL_HPP #define HBM_GUROBI_UKP_MODEL_HPP #include <memory> #include <cassert> #include <cmath> #include "gurobi_c++.h" #include "ukp_common.hpp" #ifndef HBM_PRINT_VAR #define HBM_PRINT_VAR(var) out << #var ": " << var << std::endl #endif #define HBM_TOLERANCE 0.00001 namespace hbm { template<typename W, typename P, typename I> void gurobi_solve_ukp( instance_t<W, P> &ukpi, solution_t<W, P, I> &sol, int argc, argv_t argv ) { using namespace std; const int n = static_cast<int>(ukpi.items.size()); const double c = static_cast<double>(ukpi.c); unique_ptr<double[]> w(new double[n]); unique_ptr<double[]> p(new double[n]); // NOTE: I (Henrique Becker) tried adding the trivial variable bounds in // Gurobi 8.0.1 (Thu Sep 6 13:40:08 -03 2018) but this made the code // take 0.6s for instance corepb to 97s. Startling how the code could // be much slower if I had the bounds from start and never tested // without them. //unique_ptr<double[]> ub(new double[n]); //unique_ptr<char[]> type(new char[n]); for (int i = 0; i < n; ++i) { w[i] = static_cast<double>(ukpi.items[i].w); p[i] = static_cast<double>(ukpi.items[i].p); //ub[i] = static_cast<double>(ukpi.c / ukpi.items[i].w); //type[i] = GRB_INTEGER; } try { GRBEnv env = GRBEnv(); GRBModel model = GRBModel(env); unique_ptr<GRBVar[]> x(model.addVars(n, GRB_INTEGER)); //unique_ptr<GRBVar[]> x(model.addVars(nullptr, ub.get(), nullptr, type.get(), 0, n)); GRBLinExpr objective_expr, capacity_lhs_expr; objective_expr.addTerms(p.get(), x.get(), n); model.setObjective(objective_expr, GRB_MAXIMIZE); capacity_lhs_expr.addTerms(w.get(), x.get(), n); model.addConstr(capacity_lhs_expr, GRB_LESS_EQUAL, c); model.set(GRB_IntParam_Seed, 0); model.set(GRB_IntParam_Threads, 1); model.set(GRB_IntParam_DisplayInterval, std::numeric_limits<int>::max()); // This is the relative MIPGap. The absolute MIPGap (MIPGapAbs) is 1e-10 // and will not be messed with. model.set(GRB_DoubleParam_MIPGap, 0.0); model.set(GRB_DoubleParam_TimeLimit, 1800.0); // From the manual: "By default, the Gurobi MIP solver strikes a balance // between finding new feasible solutions and proving that the current // solution is optimal. If you are more interested in finding feasible // solutions quickly, you can select MIPFocus=1. If you believe the // solver is having no trouble finding good quality solutions, and wish // to focus more attention on proving optimality, select MIPFocus=2. If // the best objective bound is moving very slowly (or not at all), you // may want to try MIPFocus=3 to focus on the bound. model.set(GRB_IntParam_MIPFocus, 0); model.set(GRB_DoubleParam_IntFeasTol, 1e-9); model.optimize(); sol.opt = static_cast<P>(model.get(GRB_DoubleAttr_ObjVal) + HBM_TOLERANCE); for (int i = 0; i < n; ++i) { double xi = x[i].get(GRB_DoubleAttr_X); assert(abs(xi - static_cast<int>(xi + HBM_TOLERANCE)) < HBM_TOLERANCE); if (xi >= (1.0 - HBM_TOLERANCE)) sol.used_items.emplace_back( ukpi.items[i], static_cast<I>(xi + HBM_TOLERANCE), i ); } } catch(GRBException e) { cout << "Error code = " << e.getErrorCode() << endl; cout << e.getMessage() << endl; } catch(...) { cout << "Exception during optimization" << endl; } } } #endif //HBM_GUROBI_UKP_MODEL_HPP
[ "henriquebecker91@gmail.com" ]
henriquebecker91@gmail.com
93fe1ce31b0dab00eb43c91a22fcb9683814d361
93113dbf7d8e7c61969f93e530166b8f441e0ad1
/ProjectC/Stats.cpp
de9b3e50eb3803f5ed6ef72c26e1485c370cf922
[]
no_license
JakubKozimorStudy/CompanyProject
f5e1cbaa0cb06fcdbefe43bc6936592decb41e9a
07af04051c92e81fffa14fe90304e2abd4aa8edc
refs/heads/master
2023-02-17T04:24:20.285262
2020-12-20T12:39:44
2020-12-20T12:39:44
312,882,128
0
0
null
null
null
null
UTF-8
C++
false
false
20
cpp
#include "Stats.h"
[ "jakubkozimor399@gmail.com" ]
jakubkozimor399@gmail.com
f6f2ff7d5455e23818c86cbc7f156fe7725b5844
a2fd736c7e1278f85fd21a7c33d8795d9c49dd53
/c++learning/effictive_c++/virtual_destructor.cc
5237d527347e9acb13aa081750174201cbd99d79
[]
no_license
disillusion028/study-diary
058e19b7e24c76fa41c6886ceb83be6dcdb92f55
e184466e538bbaf3d0168fcbdd20c3c0413e3503
refs/heads/master
2021-01-20T16:38:29.235554
2018-01-05T09:44:15
2018-01-05T09:44:15
90,845,793
1
0
null
2017-06-11T07:26:46
2017-05-10T09:23:08
C++
UTF-8
C++
false
false
374
cc
#include <iostream> using namespace std; class Person{ public: virtual ~Person(){ cout<<"Deleting a Person."<<endl; } /* ~Person(){ cout<<"Deleting a Person."<<endl; }*/ }; class Student : public Person{ public: ~Student(){ cout<<"Deleting a student."<<endl; } }; int main(){ Person *p = new Student(); delete p; }
[ "905561651@qq.com" ]
905561651@qq.com
fc152939125cdfade96fa2662c8082b0cdb0c614
b3f86b4edfb9de7d393ba503bb6be7e6d1e5d6bc
/copy_n.cpp
6753e83d69a484a421bb7bb7b71c84608dbc211d
[]
no_license
vuslysty/Stepic-CPP
5fb90c952b79b3f1f8e07a04c6d3f35f98bd2dcd
91432d231b3e7a8c2ac1a2dc267781056093c802
refs/heads/master
2022-04-21T19:12:49.238009
2020-04-24T21:44:46
2020-04-24T21:44:46
255,422,392
0
0
null
null
null
null
UTF-8
C++
false
false
731
cpp
#include <cstddef> #include <new> #include <iostream> template <typename T, typename U> void copy_n(T *dest, U *src, size_t n) { for (size_t i = 0; i < n; i++) { // new (dest + i) T((T)(U(*(src + i)))); dest[i] = (T)src[i]; } } template <typename T> void printBuf(T *buf, int size) { for (int i = 0; i < size; ++i) { std::cout << buf[i] << " "; } std::cout << std::endl; } int main() { // char src[] = "Hello world!"; // char buf[100] = {0}; char src[] = "Hello"; double dest[10]; int size = sizeof(src) / sizeof(*src); // copy_n(buf, src, size); copy_n(dest, src, size); // std::cout << buf << std::endl; printBuf(dest, size); return 0; }
[ "vladyslav.uslystyi@globallogic.com" ]
vladyslav.uslystyi@globallogic.com
fece84b904c0c0d941186db34a7a35294c8d87de
27d0d36de06dce507ff1ed72cac1835fb7661533
/Engine/_lib/include/physx/PxActor.h
9675c8a43afcce7d6c8cc6c759e865ecfbc79b20
[]
no_license
da1ord/3d_engines
5d0d90cf272932b246df7b44a2d793566488b6e3
64ada6c6d89ea1ae75975f52feb35cb936789e69
refs/heads/master
2021-05-04T11:19:55.292285
2016-04-24T08:52:38
2016-04-24T08:52:38
55,834,921
0
0
null
null
null
null
UTF-8
C++
false
false
12,473
h
// This code contains NVIDIA Confidential Information and is disclosed to you // under a form of NVIDIA software license agreement provided separately to you. // // Notice // NVIDIA Corporation and its licensors retain all intellectual property and // proprietary rights in and to this software and related documentation and // any modifications thereto. Any use, reproduction, disclosure, or // distribution of this software and related documentation without an express // license agreement from NVIDIA Corporation is strictly prohibited. // // ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES // NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO // THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT, // MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. // // Information and code furnished is believed to be accurate and reliable. // However, NVIDIA Corporation assumes no responsibility for the consequences of use of such // information or for any infringement of patents or other rights of third parties that may // result from its use. No license is granted by implication or otherwise under any patent // or patent rights of NVIDIA Corporation. Details are subject to change without notice. // This code supersedes and replaces all information previously supplied. // NVIDIA Corporation products are not authorized for use as critical // components in life support devices or systems without express written approval of // NVIDIA Corporation. // // Copyright (c) 2008-2013 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PX_PHYSICS_NX_ACTOR #define PX_PHYSICS_NX_ACTOR /** \addtogroup physics @{ */ #include "PxPhysXConfig.h" #include "foundation/PxBounds3.h" #include "PxClient.h" #include "common/PxBase.h" #ifndef PX_DOXYGEN namespace physx { #endif class PxRigidActor; class PxRigidBody; class PxRigidStatic; class PxRigidDynamic; class PxParticleBase; class PxParticleSystem; class PxParticleFluid; class PxArticulation; class PxArticulationLink; /** Group index which allows to specify 1- or 2-way interaction */ typedef PxU8 PxDominanceGroup; // Must be < 32, PxU8. /** \brief Flags which control the behavior of an actor. @see PxActorFlags PxActor PxActor.setActorFlag() PxActor.getActorFlags() */ struct PxActorFlag { enum Enum { /** \brief Enable debug renderer for this actor @see PxScene.getRenderBuffer() PxRenderBuffer PxVisualizationParameter */ eVISUALIZATION = (1<<0), /** \brief Disables scene gravity for this actor */ eDISABLE_GRAVITY = (1<<1), /** \brief Enables the sending of PxSimulationEventCallback::onWake() and PxSimulationEventCallback::onSleep() notify events @see PxSimulationEventCallback::onWake() PxSimulationEventCallback::onSleep() */ eSEND_SLEEP_NOTIFIES = (1<<2), /** \brief Disables simulation for the actor. \note This is only supported by PxRigidStatic and PxRigidDynamic actors and can be used to reduce the memory footprint when rigid actors are used for scene queries only. \note Setting this flag will remove all constraints attached to the actor from the scene. \note If this flag is set, the following calls are forbidden: \li PxRigidBody: setLinearVelocity(), setAngularVelocity(), addForce(), addTorque(), clearForce(), clearTorque() \li PxRigidDynamic: setKinematicTarget(), setWakeCounter(), wakeUp(), putToSleep() \par <b>Sleeping:</b> Raising this flag will set all velocities and the wake counter to 0, clear all forces, clear the kinematic target, put the actor to sleep and wake up all touching actors from the previous frame. */ eDISABLE_SIMULATION = (1<<3), }; }; /** \brief collection of set bits defined in PxActorFlag. @see PxActorFlag */ typedef PxFlags<PxActorFlag::Enum,PxU16> PxActorFlags; PX_FLAGS_OPERATORS(PxActorFlag::Enum,PxU16); /** \brief Identifies each type of actor. @see PxActor */ struct PxActorType { enum Enum { /** \brief A static rigid body @see PxRigidStatic */ eRIGID_STATIC, /** \brief A dynamic rigid body @see PxRigidDynamic */ eRIGID_DYNAMIC, #if PX_USE_PARTICLE_SYSTEM_API /** \brief A particle system @see PxParticleSystem */ ePARTICLE_SYSTEM, /** \brief A particle fluid @see PxParticleFluid */ ePARTICLE_FLUID, #endif /** \brief An articulation link @see PxArticulationLink */ eARTICULATION_LINK, #if PX_USE_CLOTH_API /** \brief A cloth @see PxCloth */ eCLOTH, #endif //brief internal use only! eACTOR_COUNT, eACTOR_FORCE_DWORD = 0x7fffffff }; }; /** \brief PxActor is the base class for the main simulation objects in the physics SDK. The actor is owned by and contained in a PxScene. */ class PxActor : public PxBase { public: /** \brief Deletes the actor. Do not keep a reference to the deleted instance. If the actor belongs to a #PxAggregate object, it is automatically removed from the aggregate. @see PxBase.release(), PxAggregate */ virtual void release() = 0; /** \brief Retrieves the type of actor. \return The actor type of the actor. @see PxActorType */ virtual PxActorType::Enum getType() const = 0; /** \deprecated \brief Attempts to cast to specific actor type. \return NULL if the actor is not of the appropriate type. Otherwise a pointer to the specific actor type. \note Since PxParticleFluid inherits from PxParticleSystem, calling isParticleSystem() on a PxParticleFluid instance will succeed and return the upcast to PxParticleSystem. @see PxActorType PxRigidActor PxRigidBody PxRigidStatic PxRigidDynamic PxParticleBase PxParticleSystem PxParticleFluid */ PX_DEPRECATED PX_INLINE PxRigidStatic* isRigidStatic(); PX_DEPRECATED PX_INLINE const PxRigidStatic* isRigidStatic() const; PX_DEPRECATED PX_INLINE PxRigidDynamic* isRigidDynamic(); PX_DEPRECATED PX_INLINE const PxRigidDynamic* isRigidDynamic() const; PX_DEPRECATED PX_INLINE PxParticleSystem* isParticleSystem(); PX_DEPRECATED PX_INLINE const PxParticleSystem* isParticleSystem() const; PX_DEPRECATED PX_INLINE PxParticleFluid* isParticleFluid(); PX_DEPRECATED PX_INLINE const PxParticleFluid* isParticleFluid() const; PX_DEPRECATED PX_INLINE PxArticulationLink* isArticulationLink(); PX_DEPRECATED PX_INLINE const PxArticulationLink* isArticulationLink() const; PX_DEPRECATED PX_INLINE PxCloth* isCloth(); PX_DEPRECATED PX_INLINE const PxCloth* isCloth() const; PX_DEPRECATED PX_INLINE PxRigidActor* isRigidActor(); PX_DEPRECATED PX_INLINE const PxRigidActor* isRigidActor() const; PX_DEPRECATED PX_INLINE PxRigidBody* isRigidBody(); PX_DEPRECATED PX_INLINE const PxRigidBody* isRigidBody() const; PX_DEPRECATED PX_INLINE PxParticleBase* isParticleBase(); PX_DEPRECATED PX_INLINE const PxParticleBase* isParticleBase() const; /** \brief Retrieves the scene which this actor belongs to. \return Owner Scene. NULL if not part of a scene. @see PxScene */ virtual PxScene* getScene() const = 0; // Runtime modifications /** \brief Sets a name string for the object that can be retrieved with getName(). This is for debugging and is not used by the SDK. The string is not copied by the SDK, only the pointer is stored. \param[in] name String to set the objects name to. <b>Default:</b> NULL @see getName() */ virtual void setName(const char* name) = 0; /** \brief Retrieves the name string set with setName(). \return Name string associated with object. @see setName() */ virtual const char* getName() const = 0; /** \brief Retrieves the axis aligned bounding box enclosing the actor. \param[in] inflation Scale factor for computed world bounds. Box extents are multiplied by this value. \return The actor's bounding box. @see PxBounds3 */ virtual PxBounds3 getWorldBounds(float inflation=1.01f) const = 0; /** \brief Raises or clears a particular actor flag. See the list of flags #PxActorFlag <b>Sleeping:</b> Does <b>NOT</b> wake the actor up automatically. \param[in] flag The PxActor flag to raise(set) or clear. See #PxActorFlag. \param[in] value The boolean value to assign to the flag. <b>Default:</b> PxActorFlag::eVISUALIZATION @see PxActorFlag getActorFlags() */ virtual void setActorFlag(PxActorFlag::Enum flag, bool value) = 0; /** \brief sets the actor flags See the list of flags #PxActorFlag @see PxActorFlag setActorFlag() */ virtual void setActorFlags( PxActorFlags inFlags ) = 0; /** \brief Reads the PxActor flags. See the list of flags #PxActorFlag \return The values of the PxActor flags. @see PxActorFlag setActorFlag() */ virtual PxActorFlags getActorFlags() const = 0; /** \brief Assigns dynamic actors a dominance group identifier. PxDominanceGroup is a 5 bit group identifier (legal range from 0 to 31). The PxScene::setDominanceGroupPair() lets you set certain behaviors for pairs of dominance groups. By default every dynamic actor is created in group 0. <b>Default:</b> 0 <b>Sleeping:</b> Changing the dominance group does <b>NOT</b> wake the actor up automatically. \param[in] dominanceGroup The dominance group identifier. <b>Range:</b> [0..31] @see getDominanceGroup() PxDominanceGroup PxScene::setDominanceGroupPair() */ virtual void setDominanceGroup(PxDominanceGroup dominanceGroup) = 0; /** \brief Retrieves the value set with setDominanceGroup(). \return The dominance group of this actor. @see setDominanceGroup() PxDominanceGroup PxScene::setDominanceGroupPair() */ virtual PxDominanceGroup getDominanceGroup() const = 0; /** \brief Sets the owner client of an actor. This cannot be done once the actor has been placed into a scene. <b>Default:</b> PX_DEFAULT_CLIENT @see PxClientID PxScene::createClient() */ virtual void setOwnerClient( PxClientID inClient ) = 0; /** \brief Returns the owner client that was specified with at creation time. This value cannot be changed once the object is placed into the scene. @see PxClientID PxScene::createClient() */ virtual PxClientID getOwnerClient() const = 0; /** \brief Sets the behavior bits of the actor. The behavior bits determine which types of events the actor will broadcast to foreign clients. The actor will always send notice for all possible events to its own owner client. By default it will not send any events to any other clients. If the user however raises a bit flag for any event type using this function, that event will then be sent also to any other clients which are programmed to listed to foreign actor events of that type. <b>Default:</b> 0 @see PxClientID PxActorClientBehaviorFlag PxScene::setClientBehaviorFlags() */ virtual void setClientBehaviorFlags(PxActorClientBehaviorFlags) = 0; /** \brief Retrieves the behavior bits of the actor. The behavior bits determine which types of events the actor will broadcast to foreign clients. @see PxActorClientBehaviorFlag setClientBehaviorFlags() */ virtual PxActorClientBehaviorFlags getClientBehaviorFlags() const = 0; /** \brief Retrieves the aggregate the actor might be a part of. \return The aggregate the actor is a part of, or NULL if the actor does not belong to an aggregate. @see PxAggregate */ virtual PxAggregate* getAggregate() const = 0; //public variables: void* userData; //!< user can assign this to whatever, usually to create a 1:1 relationship with a user object. protected: PX_INLINE PxActor(PxType concreteType, PxBaseFlags baseFlags) : PxBase(concreteType, baseFlags), userData(NULL) {} PX_INLINE PxActor(PxBaseFlags baseFlags) : PxBase(baseFlags) {} virtual ~PxActor() {} virtual bool isKindOf(const char* name) const { return !strcmp("PxActor", name) || PxBase::isKindOf(name); } }; #ifndef PX_DOXYGEN } // namespace physx #endif /** @} */ #endif
[ "da1ord@home" ]
da1ord@home
ed84047fdc2dbbb3d54d6dca85df33c29c38b1bc
3a02dfb96fd2fa0bd417bac0b42822be6196c296
/anim/Core/Command.cpp
e81b580fee6deda7c78e7eca1dac0493bdbebf61
[]
no_license
spadapet/png-editor
1d3d55d705e93db79dcf002c0230cfbe6bcccf92
3708536876d62b578c9405af438679e47efb6b82
refs/heads/master
2020-04-12T08:14:03.942466
2019-08-22T16:13:12
2019-08-22T16:13:12
61,907,877
0
0
null
null
null
null
UTF-8
C++
false
false
676
cpp
#include "pch.h" #include "Core/Command.h" anim::Command::Command(std::function<void(Platform::Object ^)> &&execute) : execute(execute) { } anim::Command::Command( std::function<void(Platform::Object ^)> &&execute, std::function<bool(Platform::Object ^)> &&canExecute) : execute(execute) , canExecute(canExecute) { } void anim::Command::NotifyCanExecuteChanged() { this->CanExecuteChanged(this, nullptr); } bool anim::Command::CanExecute(Platform::Object ^parameter) { return this->canExecute == nullptr || this->canExecute(parameter); } void anim::Command::Execute(Platform::Object ^parameter) { if (this->execute != nullptr) { this->execute(parameter); } }
[ "spadapet@hotmail.com" ]
spadapet@hotmail.com
0d75598d29b0a83a2a772c02352a8b9a19d799c2
df0c75142637203f21f07a758a68b82597c3d105
/matrix_mult.cpp
820ee21526e03457b06f061e37d690ab7345fd10
[]
no_license
rajatkantinandi/my-cpp-programs
b466577692f7225fcbd765a833f53df9ba483ddb
d6b655382fb5cea61d538efbc6952a4dd64c8e71
refs/heads/master
2021-09-05T19:44:23.197083
2018-01-30T16:22:36
2018-01-30T16:22:36
110,811,003
0
0
null
null
null
null
UTF-8
C++
false
false
1,519
cpp
/*Matrix Multiplication*/ #include <iostream> using namespace std; int main() { int mat1_dim[2],mat2_dim[2]; cout << "Enter the dimension of matrix 1: "<<endl; cin >> mat1_dim[0]; cin >> mat1_dim[1]; cout << "Enter the dimension of matrix 2: "<<endl; cin >> mat2_dim[0]; cin >> mat2_dim[1]; if(mat1_dim[1]==mat2_dim[0]){ //Checking validity of dimensions float A[mat1_dim[0]][mat1_dim[1]],B[mat2_dim[0]][mat2_dim[1]],result[mat1_dim[0]][mat2_dim[1]],sum=0; //Inputs cout<<"Enter Matrix 1: "<<endl; for(int i=0;i<mat1_dim[0];i++){ for(int j=0;j<mat1_dim[1];j++){ cin >> A[i][j]; } } cout<<"Enter Matrix 2: "<<endl; for(int i=0;i<mat2_dim[0];i++){ for(int j=0;j<mat2_dim[1];j++){ cin >> B[i][j]; } } for(int i=0;i<mat1_dim[0];i++){ //for rows of resultant matrix which is equal to number of rows of A for(int j=0;j<mat2_dim[1];j++){ //for column of resultant matrix which is equal to number of columns of B for(int k=0;k<mat1_dim[1];k++){ //for each element Multiplication & addition loop sum+=A[i][k]*B[k][j]; } result[i][j]=sum;//storing value after Multiplication & addition sum=0;//restoring sum=0 for next element } } //Displaying result cout << "Result matrix: " << '\n'; for(int i=0;i<mat1_dim[0];i++){ for(int j=0;j<mat2_dim[1];j++){ cout << result[i][j] <<"\t "; } cout << '\n'; } } else{ cout<<"Invalid size matrices"<<endl; } return 0; }
[ "noreply@github.com" ]
rajatkantinandi.noreply@github.com
b032c9151600deb4a3a8a33aa1d999f1cf9e568f
e2bdb179231d5123c636905f173f58654df876c4
/algorithms/cpp/addTwoNumbers/addTwoNumbers.cpp
af56f83b7bc62460c817c24f1fe65f359b27f242
[]
no_license
410588896/leetcode
ba130c26be38a68d06b80fe7964b2bc874e39f06
14abd40fad66ae1585ad1564d8af6124f45eb4b3
refs/heads/master
2022-11-14T22:21:02.976222
2022-11-06T05:32:02
2022-11-06T05:32:02
291,714,180
0
0
null
null
null
null
UTF-8
C++
false
false
1,459
cpp
/* * @lc app=leetcode id=2 lang=cpp * * [2] Add Two Numbers */ /************************************************************************************************ * * You are given two non-empty linked lists representing two non-negative integers. * The digits are stored in reverse order and each of their nodes contain a single digit. * Add the two numbers and return it as a linked list. * * You may assume the two numbers do not contain any leading zero, except the number 0 itself. * * Example: * * Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) * Output: 7 -> 0 -> 8 * Explanation: 342 + 465 = 807. * * ************************************************************************************************/ // @lc code=start /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { if (l1 == NULL && l2 == NULL) return NULL; else if (l1 == NULL) return l2; else if (l2 == NULL) return l1; int sum = l1->val + l2->val; ListNode *p = new ListNode(sum % 10); p->next = addTwoNumbers(l1->next, l2->next); if (sum >= 10) p->next = addTwoNumbers(p->next, new ListNode(1)); return p; } }; // @lc code=end
[ "410588896@qq.com" ]
410588896@qq.com
e4c8aa7535676a9e3633c239fdfa2369c32f99f8
6efff92e0c4bc343e26010ead9bdc9e318402cdb
/Lab1-Turtlebot/src/lab1.cpp
2053df1ed719ef031794720d9ead0b1fdb273e4e
[]
no_license
frank-qcd-qk/EECS376-Lab
80586f3612eac8589bdc9024aad19b46368beb68
2c0a7b186005129f1a3fc7fc2564e7a6922d3315
refs/heads/master
2022-01-07T08:21:59.989060
2019-04-29T23:26:20
2019-04-29T23:26:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,408
cpp
// Makes the turtle bot move in a 3by3 foot square #include<ros/ros.h> #include<geometry_msgs/Twist.h> geometry_msgs::Twist currT; double sample_dt = 0.001; void moveForward(double speed, double time, ros::Publisher twist_commander, ros::Rate loop_timer) { double timer = 0.0; currT.linear.x = speed; //command to move forward currT.angular.z = 0.0; while(timer < time) { twist_commander.publish(currT); timer+=sample_dt; loop_timer.sleep(); } } void turn(double angle, double angularSpeed, ros::Publisher twist_commander, ros::Rate loop_timer) { double totalTime = angle/0.5; //How much time you must spin at 0.5rad/s to get desired angle currT.linear.x = 0.0; //stop moving forward currT.angular.z = angularSpeed; //and start spinning in place double timer = 0.0; //reset the timer while(timer < totalTime) { twist_commander.publish(currT); timer+=sample_dt; loop_timer.sleep(); } } int main(int argc, char **argv) { ros::init(argc, argv, "lab1"); ros::NodeHandle nh; //publish a twist velocity publisher ros::Publisher vel_pub = nh.advertise<geometry_msgs::Twist>("/mobile_base/commands/velocity", 1); currT.linear.x = 0.0; currT.linear.y = 0.0; currT.linear.z = 0.0; currT.angular.x = 0.0; currT.angular.y = 0.0; currT.angular.z = 0.0; ros::Rate loop_timer(1/sample_dt); //create a ros object from the ros “Rate” class; set 100Hz rate //start sending some zero-velocity commands, just to warm up communications with STDR for (int i=0; i<10; i++) { vel_pub.publish(currT); loop_timer.sleep(); } double forSpeed = 0.2; double forTime = 6.0; double angle = 1.6; double angSpeed = 0.5; moveForward(forSpeed, forTime, vel_pub, loop_timer); //Move forward forSpeed m/s for 5 seconds turn(angle, angSpeed, vel_pub, loop_timer); //Turn 90 degrees counter clockwise moveForward(forSpeed, forTime, vel_pub, loop_timer); turn(angle, angSpeed, vel_pub, loop_timer); moveForward(forSpeed, forTime, vel_pub, loop_timer); turn(angle, angSpeed, vel_pub, loop_timer); moveForward(forSpeed, forTime, vel_pub, loop_timer); turn(angle, angSpeed, vel_pub, loop_timer); moveForward(0.0, forTime, vel_pub, loop_timer); //Stop return 0; }
[ "user@atlas8.EECS.cwru.edu" ]
user@atlas8.EECS.cwru.edu
b2673a71057de2abb2400f2c437b1673dba71800
469b4d3432803e23eb4c3d2b2246849e8cd08ba6
/src/qt/receiverequestdialog.cpp
2b67bbaf4c965878721046804d5a9f9e7ff9a17f
[ "MIT" ]
permissive
cryptotradingcoin/project-CTD
279a87cdec553874708deaf24d7506b2baa95114
e33a968f5ba887d5337869a83504aad90ccd034d
refs/heads/master
2020-05-21T14:34:09.522908
2019-05-19T09:05:26
2019-05-19T09:05:26
186,082,368
0
1
null
null
null
null
UTF-8
C++
false
false
5,623
cpp
// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "receiverequestdialog.h" #include "ui_receiverequestdialog.h" #include "bitcoinunits.h" #include "guiconstants.h" #include "guiutil.h" #include "optionsmodel.h" #include "walletmodel.h" #include <QClipboard> #include <QDrag> #include <QMenu> #include <QMimeData> #include <QMouseEvent> #include <QPixmap> #if QT_VERSION < 0x050000 #include <QUrl> #endif #if defined(HAVE_CONFIG_H) #include "config/ctdcoin-config.h" /* for USE_QRCODE */ #endif #ifdef USE_QRCODE #include <qrencode.h> #endif QRImageWidget::QRImageWidget(QWidget* parent) : QLabel(parent), contextMenu(0) { contextMenu = new QMenu(); QAction* saveImageAction = new QAction(tr("&Save Image..."), this); connect(saveImageAction, SIGNAL(triggered()), this, SLOT(saveImage())); contextMenu->addAction(saveImageAction); QAction* copyImageAction = new QAction(tr("&Copy Image"), this); connect(copyImageAction, SIGNAL(triggered()), this, SLOT(copyImage())); contextMenu->addAction(copyImageAction); } QImage QRImageWidget::exportImage() { if (!pixmap()) return QImage(); return pixmap()->toImage().scaled(EXPORT_IMAGE_SIZE, EXPORT_IMAGE_SIZE); } void QRImageWidget::mousePressEvent(QMouseEvent* event) { if (event->button() == Qt::LeftButton && pixmap()) { event->accept(); QMimeData* mimeData = new QMimeData; mimeData->setImageData(exportImage()); QDrag* drag = new QDrag(this); drag->setMimeData(mimeData); drag->exec(); } else { QLabel::mousePressEvent(event); } } void QRImageWidget::saveImage() { if (!pixmap()) return; QString fn = GUIUtil::getSaveFileName(this, tr("Save QR Code"), QString(), tr("PNG Image (*.png)"), NULL); if (!fn.isEmpty()) { exportImage().save(fn); } } void QRImageWidget::copyImage() { if (!pixmap()) return; QApplication::clipboard()->setImage(exportImage()); } void QRImageWidget::contextMenuEvent(QContextMenuEvent* event) { if (!pixmap()) return; contextMenu->exec(event->globalPos()); } ReceiveRequestDialog::ReceiveRequestDialog(QWidget* parent) : QDialog(parent), ui(new Ui::ReceiveRequestDialog), model(0) { ui->setupUi(this); #ifndef USE_QRCODE ui->btnSaveAs->setVisible(false); ui->lblQRCode->setVisible(false); #endif connect(ui->btnSaveAs, SIGNAL(clicked()), ui->lblQRCode, SLOT(saveImage())); } ReceiveRequestDialog::~ReceiveRequestDialog() { delete ui; } void ReceiveRequestDialog::setModel(OptionsModel* model) { this->model = model; if (model) connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(update())); // update the display unit if necessary update(); } void ReceiveRequestDialog::setInfo(const SendCoinsRecipient& info) { this->info = info; update(); } void ReceiveRequestDialog::update() { if (!model) return; QString target = info.label; if (target.isEmpty()) target = info.address; setWindowTitle(tr("Request payment to %1").arg(target)); QString uri = GUIUtil::formatBitcoinURI(info); ui->btnSaveAs->setEnabled(false); QString html; html += "<html><font face='verdana, arial, helvetica, sans-serif'>"; html += "<b>" + tr("Payment information") + "</b><br>"; html += "<b>" + tr("URI") + "</b>: "; html += "<a style=\"color:#ff7e0c;\" href=\"" + uri + "\">" + GUIUtil::HtmlEscape(uri) + "</a><br>"; html += "<b>" + tr("Address") + "</b>: " + GUIUtil::HtmlEscape(info.address) + "<br>"; if (info.amount) html += "<b>" + tr("Amount") + "</b>: " + BitcoinUnits::formatWithUnit(model->getDisplayUnit(), info.amount) + "<br>"; if (!info.label.isEmpty()) html += "<b>" + tr("Label") + "</b>: " + GUIUtil::HtmlEscape(info.label) + "<br>"; if (!info.message.isEmpty()) html += "<b>" + tr("Message") + "</b>: " + GUIUtil::HtmlEscape(info.message) + "<br>"; ui->outUri->setText(html); #ifdef USE_QRCODE ui->lblQRCode->setText(""); if (!uri.isEmpty()) { // limit URI length if (uri.length() > MAX_URI_LENGTH) { ui->lblQRCode->setText(tr("Resulting URI too long, try to reduce the text for label / message.")); } else { QRcode* code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1); if (!code) { ui->lblQRCode->setText(tr("Error encoding URI into QR Code.")); return; } QImage myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32); myImage.fill(0xffffff); unsigned char* p = code->data; for (int y = 0; y < code->width; y++) { for (int x = 0; x < code->width; x++) { myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff)); p++; } } QRcode_free(code); ui->lblQRCode->setPixmap(QPixmap::fromImage(myImage).scaled(300, 300)); ui->btnSaveAs->setEnabled(true); } } #endif } void ReceiveRequestDialog::on_btnCopyURI_clicked() { GUIUtil::setClipboard(GUIUtil::formatBitcoinURI(info)); } void ReceiveRequestDialog::on_btnCopyAddress_clicked() { GUIUtil::setClipboard(info.address); }
[ "cryptotradingg@gmail.com" ]
cryptotradingg@gmail.com
95e09c83015a69f9efa9a4ab9cbf1dc5c5922b6d
3dae2a56f28b0fb05f236dcc852daf007e30c7e3
/CSAR Simulation/Build/04/Il2CppOutputProject/Source/lumpedcpp/Lump_libil2cpp_mono.cpp
060f901fe7ee26dd2d503e0fab1ee2bbf97fd0a0
[]
no_license
CSAR1/CSAR
4e9e3e27f9d0b4839d9638c957cd8064034f68c3
4c93f9dab0d4eab74e4b383518acda7865b8b186
refs/heads/master
2023-01-18T17:51:13.033360
2020-11-18T03:40:44
2020-11-18T03:40:44
264,189,889
0
0
null
null
null
null
UTF-8
C++
false
false
930
cpp
#include "il2cpp-config.h" #include "E:\Graduate\Graduate Design\GitHub\CSAR\CSAR Simulation\Build\04\Il2CppOutputProject\IL2CPP\libil2cpp\mono\MonoPosixHelper.cpp" #include "E:\Graduate\Graduate Design\GitHub\CSAR\CSAR Simulation\Build\04\Il2CppOutputProject\IL2CPP\libil2cpp\mono\ThreadPool\ThreadPoolMonitorThread.cpp" #include "E:\Graduate\Graduate Design\GitHub\CSAR\CSAR Simulation\Build\04\Il2CppOutputProject\IL2CPP\libil2cpp\mono\ThreadPool\ThreadPoolWorkerThread.cpp" #include "E:\Graduate\Graduate Design\GitHub\CSAR\CSAR Simulation\Build\04\Il2CppOutputProject\IL2CPP\libil2cpp\mono\ThreadPool\threadpool-ms-io-poll.cpp" #include "E:\Graduate\Graduate Design\GitHub\CSAR\CSAR Simulation\Build\04\Il2CppOutputProject\IL2CPP\libil2cpp\mono\ThreadPool\threadpool-ms-io.cpp" #include "E:\Graduate\Graduate Design\GitHub\CSAR\CSAR Simulation\Build\04\Il2CppOutputProject\IL2CPP\libil2cpp\mono\ThreadPool\threadpool-ms.cpp"
[ "34788672+JxBalance@users.noreply.github.com" ]
34788672+JxBalance@users.noreply.github.com
883fed5956342019ea45e71f728ebf15e51c5299
601e9f409ec1c5de2d5a56331979db3bcb41dc8f
/Code/InfernoEngine/Inc/Core/Private/AI/BehaviorTrees/Condition/IsStationaryBehavior.cpp
628de7faaa6531377385173e1e059b0b8168d24e
[]
no_license
bmclaine/ProtoTowers
1f12cd6e299be6771188e8b0738db5e6f8301b50
c9bbe2896591f456c5fde6595d7d76f9031fd2f4
refs/heads/master
2020-04-17T07:10:05.522159
2016-08-31T01:07:14
2016-08-31T01:07:14
66,881,935
0
0
null
null
null
null
UTF-8
C++
false
false
803
cpp
/////////////////////////////////////////////////////////////////////////////////////////////////// // // Author: Doug Berg // // Description: BaseBehavior is the base class of ALL behaviors. // /////////////////////////////////////////////////////////////////////////////////////////////////// #include "../Public/AI/BehaviorTrees/Condition/IsStationaryBehavior.h" #include "../../../../ProtoTowers/Components/AIEntity.h" IsStationaryBehavior::IsStationaryBehavior(AIEntity* _entity, std::string& _name) : ConditionBehavior(_name) , m_pEntity(_entity) { } IsStationaryBehavior::~IsStationaryBehavior() { } void IsStationaryBehavior::Destroy() { } Status IsStationaryBehavior::Update() { if (m_pEntity->GetState() == State::STATIONARY) return Status::BT_FAILURE; return Status::BT_SUCCESS; }
[ "bizzy18@gmail.com" ]
bizzy18@gmail.com
2c73bbc690ef994280471bd779cf6c7b71c2dd23
ead1807fd97bc4ddff17988f572b4bccac04011d
/project/build/jsb-default/frameworks/cocos2d-x/cocos/editor-support/dragonbones/cocos2dx/CCFactory.h
065d73d94123222197732584dce0e06e78086c87
[ "MIT" ]
permissive
bbx0331/Luke
e1e6cdcc9c30ee3c52d00987e498fbc899a81dac
5dba7de93fa7fec66359a16882a7e90e7dcc6660
refs/heads/master
2021-01-25T12:49:31.962384
2018-08-01T15:45:00
2018-08-01T15:45:00
123,515,910
0
0
null
null
null
null
UTF-8
C++
false
false
1,882
h
#ifndef DRAGONBONES_CC_FACTORY_H #define DRAGONBONES_CC_FACTORY_H #include "dragonbones/DragonBonesHeaders.h" #include "cocos2d.h" #include "CCArmatureDisplay.h" DRAGONBONES_NAMESPACE_BEGIN class CCFactory : public BaseFactory { public: static CCFactory* getInstance(); static void destroyInstance(); CCFactory(); ~CCFactory(); protected: virtual TextureAtlasData* _generateTextureAtlasData(TextureAtlasData* textureAtlasData, void* textureAtlas) const override; virtual Armature* _generateArmature(const BuildArmaturePackage& dataPackage) const override; virtual Slot* _generateSlot(const BuildArmaturePackage& dataPackage, const SlotDisplayDataSet& slotDisplayDataSet) const override; public: virtual DragonBonesData* loadDragonBonesData(const std::string& filePath, const std::string& dragonBonesName = ""); virtual TextureAtlasData* loadTextureAtlasData(const std::string& filePath, const std::string& dragonBonesName = "", float scale = 0.f); virtual TextureAtlasData* parseTextureAtlasData(const std::string& atlasData, cocos2d::Texture2D* texture, const std::string& dragonBonesName = "", float scale = 0.f); virtual TextureAtlasData* parseTextureAtlasData(const std::string& atlasData, const std::string& texturePath, const std::string& dragonBonesName = "", float scale = 0.f); virtual CCArmatureDisplay* buildArmatureDisplay(const std::string& armatureName, const std::string& dragonBonesName = "", const std::string& skinName = "") const; virtual cocos2d::Sprite* getTextureDisplay(const std::string& textureName, const std::string& dragonBonesName = "") const; virtual CCArmatureDisplay* getSoundEventManater() const; private: void _initTextureAtlasData(TextureAtlasData* atlasData); DRAGONBONES_DISALLOW_COPY_AND_ASSIGN(CCFactory); }; DRAGONBONES_NAMESPACE_END #endif // DRAGONBONES_CC_FACTORY_H
[ "zhaonanyu@a-onesoft.com" ]
zhaonanyu@a-onesoft.com
27cbf6553cfc2ecb5308e1eb4cbaf95f98b500b2
299648a8c633728662d0b7651cd98afdc28db902
/src/thirdparty/cef_binary_74.1.16/tests/ceftests/client_app_delegates.cc
19306d42b9e2799af747f3f236814423a593be6a
[ "BSD-3-Clause", "LicenseRef-scancode-unknown" ]
permissive
aardvarkxr/aardvark
2978277b34c2c3894d6aafc4c590f3bda50f4d43
300d0d5e9b872ed839fae932c56eff566967d24b
refs/heads/master
2023-01-12T18:42:10.705028
2021-08-18T04:09:02
2021-08-18T04:09:02
182,431,653
183
25
BSD-3-Clause
2023-01-07T12:42:14
2019-04-20T16:55:30
TypeScript
UTF-8
C++
false
false
5,218
cc
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. #include "tests/shared/browser/client_app_browser.h" #include "tests/shared/renderer/client_app_renderer.h" using client::ClientAppBrowser; using client::ClientAppRenderer; void CreateBrowserDelegates(ClientAppBrowser::DelegateSet& delegates) { // Bring in the Frame tests. extern void CreateFrameBrowserTests(ClientAppBrowser::DelegateSet & delegates); CreateFrameBrowserTests(delegates); // Bring in the Navigation tests. extern void CreateNavigationBrowserTests(ClientAppBrowser::DelegateSet & delegates); CreateNavigationBrowserTests(delegates); // Bring in the plugin tests. extern void CreatePluginBrowserTests(ClientAppBrowser::DelegateSet & delegates); CreatePluginBrowserTests(delegates); // Bring in the preference tests. extern void CreatePreferenceBrowserTests(ClientAppBrowser::DelegateSet & delegates); CreatePreferenceBrowserTests(delegates); // Bring in the RequestHandler tests. extern void CreateRequestHandlerBrowserTests(ClientAppBrowser::DelegateSet & delegates); CreateRequestHandlerBrowserTests(delegates); // Bring in the V8 tests. extern void CreateV8BrowserTests(ClientAppBrowser::DelegateSet & delegates); CreateV8BrowserTests(delegates); } void CreateRenderDelegates(ClientAppRenderer::DelegateSet& delegates) { // Bring in the Frame tests. extern void CreateFrameRendererTests(ClientAppRenderer::DelegateSet & delegates); CreateFrameRendererTests(delegates); // Bring in the DOM tests. extern void CreateDOMRendererTests(ClientAppRenderer::DelegateSet & delegates); CreateDOMRendererTests(delegates); // Bring in the message router tests. extern void CreateMessageRouterRendererTests(ClientAppRenderer::DelegateSet & delegates); CreateMessageRouterRendererTests(delegates); // Bring in the Navigation tests. extern void CreateNavigationRendererTests(ClientAppRenderer::DelegateSet & delegates); CreateNavigationRendererTests(delegates); // Bring in the process message tests. extern void CreateProcessMessageRendererTests(ClientAppRenderer::DelegateSet & delegates); CreateProcessMessageRendererTests(delegates); // Bring in the RequestHandler tests. extern void CreateRequestHandlerRendererTests(ClientAppRenderer::DelegateSet & delegates); CreateRequestHandlerRendererTests(delegates); // Bring in the routing test handler delegate. extern void CreateRoutingTestHandlerDelegate(ClientAppRenderer::DelegateSet & delegates); CreateRoutingTestHandlerDelegate(delegates); // Bring in the thread tests. extern void CreateThreadRendererTests(ClientAppRenderer::DelegateSet & delegates); CreateThreadRendererTests(delegates); // Bring in the URLRequest tests. extern void CreateURLRequestRendererTests(ClientAppRenderer::DelegateSet & delegates); CreateURLRequestRendererTests(delegates); // Bring in the V8 tests. extern void CreateV8RendererTests(ClientAppRenderer::DelegateSet & delegates); CreateV8RendererTests(delegates); } void RegisterCustomSchemes(CefRawPtr<CefSchemeRegistrar> registrar, std::vector<CefString>& cookiable_schemes) { // Bring in the scheme handler tests. extern void RegisterSchemeHandlerCustomSchemes( CefRawPtr<CefSchemeRegistrar> registrar, std::vector<CefString> & cookiable_schemes); RegisterSchemeHandlerCustomSchemes(registrar, cookiable_schemes); // Bring in the cookie tests. extern void RegisterCookieCustomSchemes( CefRawPtr<CefSchemeRegistrar> registrar, std::vector<CefString> & cookiable_schemes); RegisterCookieCustomSchemes(registrar, cookiable_schemes); // Bring in the URLRequest tests. extern void RegisterURLRequestCustomSchemes( CefRawPtr<CefSchemeRegistrar> registrar, std::vector<CefString> & cookiable_schemes); RegisterURLRequestCustomSchemes(registrar, cookiable_schemes); } namespace client { // static void ClientAppBrowser::CreateDelegates(DelegateSet& delegates) { ::CreateBrowserDelegates(delegates); } // static CefRefPtr<CefPrintHandler> ClientAppBrowser::CreatePrintHandler() { return NULL; } // static void ClientAppRenderer::CreateDelegates(DelegateSet& delegates) { ::CreateRenderDelegates(delegates); } // static void ClientApp::RegisterCustomSchemes( CefRawPtr<CefSchemeRegistrar> registrar, std::vector<CefString>& cookiable_schemes) { ::RegisterCustomSchemes(registrar, cookiable_schemes); } } // namespace client
[ "joe@valvesoftware.com" ]
joe@valvesoftware.com
9839d225f6997a910cc2d5306b83df07e83ac9fa
d1a0dc918d1067e3a4af31172f6a1cc2a7eaa506
/base/win32window.cc
92f79d089db5d5ab1f34e539c9c3ffb850f9c98e
[]
no_license
wangscript007/rtc_base
6a84a0e9d6d3f31afb65f1dc8524adbafd01871a
955908c33d8a3c9f6ba4bac85980f9f95fe7cc87
refs/heads/master
2022-01-06T05:22:49.125571
2019-05-09T14:34:49
2019-05-09T14:34:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,694
cc
/* * Copyright 2004 The WebRTC Project Authors. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ //#include "stdafx.h" #include "base/checks.h" #include "base/logging.h" #include "base/win32window.h" namespace rtc { /////////////////////////////////////////////////////////////////////////////// // Win32Window /////////////////////////////////////////////////////////////////////////////// static const wchar_t kWindowBaseClassName[] = L"WindowBaseClass"; HINSTANCE Win32Window::instance_ = NULL; ATOM Win32Window::window_class_ = 0; Win32Window::Win32Window() : wnd_(NULL) { } Win32Window::~Win32Window() { RTC_DCHECK(NULL == wnd_); } bool Win32Window::Create(HWND parent, const wchar_t* title, DWORD style, DWORD exstyle, int x, int y, int cx, int cy) { if (wnd_) { // Window already exists. return false; } if (!window_class_) { if (!GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, reinterpret_cast<LPCWSTR>(&Win32Window::WndProc), &instance_)) { LOG_GLE(LS_ERROR) << "GetModuleHandleEx failed"; return false; } // Class not registered, register it. WNDCLASSEX wcex; memset(&wcex, 0, sizeof(wcex)); wcex.cbSize = sizeof(wcex); wcex.hInstance = instance_; wcex.lpfnWndProc = &Win32Window::WndProc; wcex.lpszClassName = kWindowBaseClassName; window_class_ = ::RegisterClassEx(&wcex); if (!window_class_) { LOG_GLE(LS_ERROR) << "RegisterClassEx failed"; return false; } } wnd_ = ::CreateWindowEx(exstyle, kWindowBaseClassName, title, style, x, y, cx, cy, parent, NULL, instance_, this); return (NULL != wnd_); } void Win32Window::Destroy() { const bool success = ::DestroyWindow(wnd_); RTC_DCHECK(success); } void Win32Window::Shutdown() { if (window_class_) { ::UnregisterClass(MAKEINTATOM(window_class_), instance_); window_class_ = 0; } } bool Win32Window::OnMessage(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT& result) { switch (uMsg) { case WM_CLOSE: if (!OnClose()) { result = 0; return true; } break; } return false; } LRESULT Win32Window::WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { Win32Window* that = reinterpret_cast<Win32Window*>( ::GetWindowLongPtr(hwnd, GWLP_USERDATA)); if (!that && (WM_CREATE == uMsg)) { CREATESTRUCT* cs = reinterpret_cast<CREATESTRUCT*>(lParam); that = static_cast<Win32Window*>(cs->lpCreateParams); that->wnd_ = hwnd; ::SetWindowLongPtr(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(that)); } if (that) { LRESULT result; bool handled = that->OnMessage(uMsg, wParam, lParam, result); if (WM_DESTROY == uMsg) { for (HWND child = ::GetWindow(hwnd, GW_CHILD); child; child = ::GetWindow(child, GW_HWNDNEXT)) { LOG(LS_INFO) << "Child window: " << static_cast<void*>(child); } } if (WM_NCDESTROY == uMsg) { ::SetWindowLongPtr(hwnd, GWLP_USERDATA, NULL); that->wnd_ = NULL; that->OnNcDestroy(); } if (handled) { return result; } } return ::DefWindowProc(hwnd, uMsg, wParam, lParam); } } // namespace rtc
[ "ixiaomo@betofly.cn" ]
ixiaomo@betofly.cn
fb692dc4a488de0dc536c729d9cdaaa2f2342b70
7520b65c6356a22ac2b7adbbf6d4dfb9b6eeae97
/MenuButton.h
b2d6ed766dd229865eaf88387b5b390dccd7b5f7
[]
no_license
gevorgyana/SDLproj
3814b688616b447110894a4adf7fd576b879ac8b
40702eed46200b0c160dcd879b958ff9ba05250a
refs/heads/master
2020-04-14T13:51:57.614198
2019-01-10T20:57:56
2019-01-10T20:57:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
524
h
// // Created by artyom on 10.01.19. // #ifndef UNTITLED1_MENUBUTTON_H #define UNTITLED1_MENUBUTTON_H #include "SDLGameObject.h" class MenuButton : public SDLGameObject { public: MenuButton(const LoaderParams* pParams, void (*callback)()); virtual void draw(); virtual void update(); virtual void clean(); private: enum button_state { MOUSE_OUT = 0, MOUSE_OVER = 1, CLICKED = 2 }; void (*m_callback)(); bool m_bReleased; }; #endif //UNTITLED1_MENUBUTTON_H
[ "artemhevorhian@gmail.com" ]
artemhevorhian@gmail.com
50a8ab71e59bc24fc30b9cbb69f20e8a4b3f7a4c
e0387cf8f45d3e2b7ea3788b299f195a621708a8
/Source/Sable/Core/ManagedObject/ObjectMethod.cpp
c6d82ebbf9f47637d0e72ff2ca93f2644100d1c1
[]
no_license
ClementVidal/sable.sable
eea0e822d90739269e35bed20805a2789b5fbc81
0ec2cd03867a4673472c1bc7b071a3f16b55fb1b
refs/heads/master
2021-01-13T01:28:54.070144
2013-10-15T15:21:49
2013-10-15T15:21:49
39,085,785
0
0
null
null
null
null
UTF-8
C++
false
false
886
cpp
#include <Sable\Core\ManagedObject\ObjectMethod.h> using namespace Sable; CObjectMethod::CObjectMethod() { m_Method = NULL; m_Object = NULL; } CObjectMethod::CObjectMethod( CManagedObject& object, MethodPtr method) { m_Method = method; m_Object = &object; } Bool CObjectMethod::operator==( const CObjectMethod& om ) const { return ( m_Object == om.m_Object ) && ( m_Method == om.m_Method ); } CObjectMethod& CObjectMethod::operator=( const CObjectMethod& other ) { m_Object = other.m_Object; m_Method = other.m_Method; return *this; } Int32 CObjectMethod::Call() { if( m_Object ) return (m_Object->*m_Method)(NULL, 0); return 0; } Int32 CObjectMethod::Call(Void** args, UInt16 argCount) { if( m_Object ) return (m_Object->*m_Method)(args, argCount); return 0; }
[ "clement.vidal@lam.fr" ]
clement.vidal@lam.fr
8580c93f44f74fe58309cd2487442916758b6069
b17bd5aa1c40b598543441f561c0a71e16d6ee97
/src/PhysicalConstants.cpp
dbef70d90fb0726629dc7ab079f92072370d5450
[]
no_license
Liangshiweiii/Opensim
b15880c84ff383f4b66ca30be091edc9a839a4eb
9efb8de50865a53f687adcad04d51c9db69e4801
refs/heads/master
2023-03-27T22:14:45.707776
2021-03-20T02:35:49
2021-03-20T02:35:49
345,040,192
0
0
null
null
null
null
UTF-8
C++
false
false
752
cpp
#include "Info.h" #include "PhysicalConstants.h" #include "Tools/UserInterface.h" namespace opensim { using namespace std; /*************************************************************************/ double PhysicalConstants::R = 8.314; // in Jouls/(mole*K) void PhysicalConstants::ReadInput(string InputFileName) { fstream inp(InputFileName.c_str(), ios::in); if (!inp) { Info::WriteExit("File " + InputFileName + " could not be opened","PhysicalConstants"); exit(1); }; int moduleLocation = UserInterface::FindModuleLocation(inp, "PhysicalConstants"); R = UserInterface::ReadParameterD(inp,moduleLocation, string("R")); inp.close(); } }// namespace opensim
[ "Liangshiweii@126.com" ]
Liangshiweii@126.com
fa4656f831815592f8c309c8708e0d7fb0222698
7fc64f493a4b2164e302b0f97a6b9ed159edd8d3
/src/mzdb/writer/threaded_peak_picker.h
e51da8fcecf9ef457d1f0f4bf6ed98a4c155b54d
[ "Apache-2.0" ]
permissive
jerkos/pwiz-mzdb
b16bc6225546d03a20ded80205ce82675cf9e0e7
edeaefc4388e7c9c1b48dfa2d69ced3a080a9535
refs/heads/master
2020-05-31T00:10:56.392930
2015-01-08T08:44:11
2015-01-08T08:44:11
17,526,406
0
0
null
null
null
null
UTF-8
C++
false
false
3,135
h
#ifndef MULTITHREADEDPEAKPICKER_H #define MULTITHREADEDPEAKPICKER_H #include "boost/thread/thread.hpp" #include "pwiz/data/msdata/MSData.hpp" #include "peak_finder_utils.hpp" using namespace std; namespace mzdb { class mzMultiThreadedPeakPicker { private: /*attribute */ map<int, DataMode>& m_dataModeByMsLevel; /* methods */ template<typename mz_t, typename int_t> void _peakPicksTypedSpectra(vector<std::shared_ptr<mzSpectrum<mz_t, int_t> > >& spectra, DataMode m, pwiz::msdata::CVID filetype, mzPeakFinderUtils::PeakPickerParams& params, size_t maxNbThreads) { size_t maxVal = 0; for (size_t j = 0, N = spectra.size(); j < N; j += maxNbThreads) { maxVal = j; boost::thread_group g; size_t counter = ( N - j < maxNbThreads ) ? N - j : maxNbThreads; for (size_t i = 0; i < counter; ++i) { g.create_thread(std::bind(&mzSpectrum<mz_t, int_t>::doPeakPicking, spectra[j + i], m, filetype, params)); } g.join_all(); } } /* * launch peakPicking using a thread group * */ template<class h_mz_t, class h_int_t, class l_mz_t, class l_int_t> void _peakPicks(vector<std::shared_ptr<mzSpectrum<h_mz_t,h_int_t> > >& highResBuffer, vector<std::shared_ptr<mzSpectrum<l_mz_t,l_int_t> > >& lowResBuffer, DataMode m, pwiz::msdata::CVID filetype, mzPeakFinderUtils::PeakPickerParams& params) { size_t nbProc = boost::thread::hardware_concurrency(); size_t maxNbThreads = std::max<size_t>(1, nbProc);//(nbProc - 4) / 2 + 1); this->_peakPicksTypedSpectra<h_mz_t, h_int_t>(highResBuffer, m, filetype, params, maxNbThreads); this->_peakPicksTypedSpectra<l_mz_t, l_int_t>(lowResBuffer, m, filetype, params, maxNbThreads); //#endif } public: /* constructor */ inline mzMultiThreadedPeakPicker (map<int, DataMode>& dataModeByMsLevel): m_dataModeByMsLevel(dataModeByMsLevel) {} inline map<int, DataMode>& getDataModeByMsLevel() { return this->m_dataModeByMsLevel; } /** * wrapper of the function above */ template<class h_mz_t, class h_int_t, class l_mz_t, class l_int_t> inline void start(unique_ptr<mzSpectraContainer<h_mz_t, h_int_t, l_mz_t, l_int_t> >& cycleObject, pwiz::msdata::CVID filetype, mzPeakFinderUtils::PeakPickerParams& params) { vector<std::shared_ptr<mzSpectrum<h_mz_t, h_int_t> > > highResSpectra; vector<std::shared_ptr<mzSpectrum<l_mz_t, l_int_t> > > lowResSpectra; cycleObject->getSpectra(highResSpectra, lowResSpectra); auto& dataMode = m_dataModeByMsLevel[cycleObject->msLevel]; this->_peakPicks<h_mz_t, h_int_t, l_mz_t, l_int_t>(highResSpectra, lowResSpectra, dataMode, filetype, params); } }; } // end namespace mzdb #endif // MULTITHREADEDPEAKPICKER_H
[ "cram@hotmail.fr" ]
cram@hotmail.fr
319093bdd6f9d0788653907676af2f416a05eab0
8b53ce632b3737906ddeaef4b05ef8cfd693c42d
/Lesson_1/Task_8/main.cpp
f7e88628a71d5eca58872228465fbc8a42a7da11
[]
no_license
VetalHardline/NG_2020_Krivokhizha_Vitalya
3e96ab04901d1122cd6963447685aec60a8ba03c
acbb1196947241e0ade853dc4869e40fa1085c63
refs/heads/main
2023-02-27T12:33:57.187031
2021-02-04T16:06:51
2021-02-04T16:06:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
637
cpp
#include <iostream> using namespace std; int main() { int num = 1; int output = 1; int siize; int width = 1; cout << "Enter size of the christmas tree - "; cin >> siize; width = (siize * 2) - 1; while (num <= siize) { while (output <= siize - num) { cout << " "; output++; } while (output <= width / 2 + num) { cout << "*"; output++; } cout << endl; num++; output = 1; } while (output <= width / 2) { cout << " "; output++; } cout << "*"; }
[ "vvvetal2003@gmail^Com" ]
vvvetal2003@gmail^Com
3e14f15c18183aa907bb12334cb9b59025491b6b
6c57ac845ed9980126f54774bb4288ef264aa21a
/src/chart/datastage.cpp
11f51c61b310873d89bd8aa35b79722a92802ac4
[]
no_license
HiddenSnail/EnergyPlusProject
7d7717fc58f943ca40fac8cc8a8c3fa83968e9cf
7a59960543f1f8ef6de94dd99a0fe974857b9200
refs/heads/master
2021-06-24T19:07:11.478342
2017-08-25T03:46:27
2017-08-25T03:46:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,729
cpp
#include "./chart/datastage.h" QHash<QString, int> DataStage::_monthRange = { {"Jue", 744}, {"Feb", 672}, {"Mar", 744}, {"Apr", 720}, {"May", 744}, {"Jun", 720}, {"Jul", 744}, {"Aug", 744}, {"Sep", 720}, {"Oct", 744}, {"Nov", 720}, {"Dec", 744} }; QHash<QString, QString> DataStage::_langHash = { {"Light", QString::fromLocal8Bit("照明能耗")}, {"Device", QString::fromLocal8Bit("设备能耗")}, {"CooMachine", QString::fromLocal8Bit("冷机能耗")}, {"BoilerFuelUse", QString::fromLocal8Bit("锅炉能耗")}, {"CooTower", QString::fromLocal8Bit("冷却塔能耗")}, {"FreWaterPump", QString::fromLocal8Bit("冷冻水泵能耗")}, {"CooWaterPump", QString::fromLocal8Bit("冷却水泵能耗")}, {"HotWaterPump", QString::fromLocal8Bit("热水泵能耗")}, {"Fan", QString::fromLocal8Bit("风机能耗")} }; QList<QString> DataStage::getMonths(int startMon, int endMon) { static QList<QString> months = { "Jue", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; QList<QString> realMonths; if (startMon <= 0 || endMon <= 0 || endMon < startMon || endMon > 12) { realMonths = months; } else { for (int i = startMon - 1; i < endMon; i++) { realMonths << months[i]; } } return realMonths; } void DataStage::resizeEvent(QResizeEvent *event) { int btnWidth = btnL->width(), btnHeight = btnL->height(); chart1->setGeometry(btnWidth, 0, (event->size().width()- 2*btnL->width())/2, event->size().height()); chart2->setGeometry((event->size().width()- 2*btnL->width())/2 + btnWidth, 0, (event->size().width()- 2*btnL->width())/2, event->size().height()); barChart->setGeometry(btnWidth, 0, event->size().width() - btnWidth*2, event->size().height()); btnL->setGeometry(0, event->size().height()/2 - btnHeight, btnWidth, btnHeight); btnR->setGeometry(event->size().width() - btnWidth, event->size().height()/2 - btnHeight, btnWidth, btnHeight); } DataStage::DataStage() { scene = new QGraphicsScene(); this->setWindowTitle("Chart"); this->setRenderHint(QPainter::Antialiasing); this->setSceneRect(0, 0, 1400, 800); this->setMinimumSize(1400, 800); scene->setBackgroundBrush(QBrush(QColor(240, 240, 240))); btnL = new QPushButton(); btnR = new QPushButton(); btnL->setIcon(QIcon(":/res/icons/L.png")); btnL->setIconSize(QSize(50, 100)); btnR->setIcon(QIcon(":/res/icons/R.png")); btnR->setIconSize(QSize(50, 100)); btnL->setStyleSheet("background-color: rgb(240, 240, 240);"); btnR->setStyleSheet("background-color: rgb(240, 240, 240);"); btnL->setFlat(true); btnR->setFlat(true); L = scene->addWidget(btnL); R = scene->addWidget(btnR); int btnWidth = 50, btnHeight = 100; btnL->setGeometry(0, this->height()/2 - btnHeight, btnWidth, btnHeight); btnR->setGeometry(this->width() - btnWidth, this->height()/2 - btnHeight, btnWidth, btnHeight); this->setScene(scene); QObject::connect(btnL, &QPushButton::clicked, this, [=](){ showAsBarChart(); btnL->setEnabled(false); btnR->setEnabled(true); }); QObject::connect(btnR, &QPushButton::clicked, this, [=](){ showAsPieChart(); btnR->setEnabled(false); btnL->setEnabled(true); }); chart1 = new DrilldownChart(); chart1->setAnimationOptions(QChart::AllAnimations); chart1->legend()->setVisible(true); chart1->legend()->setAlignment(Qt::AlignRight); chart2 = new DrilldownChart(); chart2->setAnimationOptions(QChart::AllAnimations); chart2->legend()->setVisible(true); chart2->legend()->setAlignment(Qt::AlignRight); barChart = new DrilldownChart(); barChart->setAnimationOptions(QChart::SeriesAnimations); barChart->legend()->setVisible(true); barChart->legend()->setAlignment(Qt::AlignBottom); } DataStage::DataStage(EnergySheet s1, EnergySheet s2) :DataStage() { setData(s1, s2); } DataStage::~DataStage() { delete scene; delete chart1; delete chart2; delete barChart; } void DataStage::setData(EnergySheet s1, EnergySheet s2) { this->s1 = s1; this->s2 = s2; } void DataStage::setPieChartData(DrilldownChart *chart, EnergySheet sheet, QString chartName, int quarter) { QPieSeries *mainSeries = new QPieSeries(); mainSeries->setName(chartName); QList<QString> kinds = EnergySheet::_idMap.keys(); QList<QString> months; switch (quarter) { case 1: months = getMonths(1, 3); break; case 2: months = getMonths(4, 6); break; case 3: months = getMonths(7, 9); break; case 4: months = getMonths(10, 12); break; default: months = getMonths(1, 12); break; } for (auto kind: kinds) { QPieSeries *detailSeries = new QPieSeries(mainSeries); detailSeries->setName(chartName + " - " + _langHash[kind]); int head = 0; for (auto month: months) { int range = _monthRange[month]; *detailSeries << new DrilldownSlice(sheet[kind].sum(head, range), month, mainSeries); head += range; } *mainSeries << new DrilldownSlice(sheet[kind].sum(), _langHash[kind], detailSeries); QObject::connect(detailSeries, SIGNAL(clicked(QPieSlice*)), chart, SLOT(handleSliceClicked(QPieSlice*))); } QObject::connect(mainSeries, SIGNAL(clicked(QPieSlice*)), chart, SLOT(handleSliceClicked(QPieSlice*))); chart->changeSeries(mainSeries); } void DataStage::newPieChartData(int quarter) { setPieChartData(chart1, s1, "Base Model", quarter); setPieChartData(chart2, s2, "Proposed Model", quarter); int btnWidth = btnL->width(); chart1->setGeometry(btnWidth, 0, (this->size().width()- 2*btnL->width())/2 , this->size().height()); chart2->setGeometry((this->size().width()- 2*btnL->width())/2 + btnWidth, 0, (this->size().width()- 2*btnL->width())/2, this->size().height()); } void DataStage::showAsPieChart() { if (cur_item == 2) { scene->removeItem(barChart); } scene->addItem(chart1); scene->addItem(chart2); scene->removeItem(L); scene->removeItem(R); scene->addItem(L); scene->addItem(R); cur_item = 1; this->viewport()->repaint(); this->show(); } void DataStage::newBarChartData(int quarter) { QBarSet *baseSet = new QBarSet("Base Model"); QBarSet *proSet = new QBarSet("Proposed Model"); QList<QString> months; switch (quarter) { case 1: months = getMonths(1, 3); break; case 2: months = getMonths(4, 6); break; case 3: months = getMonths(7, 9); break; case 4: months = getMonths(10, 12); break; default: months = getMonths(1, 12); break; } int head = 0; for (auto month: months) { int range = _monthRange[month]; *baseSet << s1.sum(head, range) / (1000 * 3600); *proSet << s2.sum(head, range) / (1000 * 3600); head += range; } barChart->removeAxis(barChart->axisX()); barChart->removeAxis(barChart->axisY()); QBarSeries *barSeries = new QBarSeries(); barSeries->append(baseSet); barSeries->append(proSet); barChart->changeSeries(barSeries); QBarCategoryAxis *axisX = new QBarCategoryAxis(); axisX->append(months); axisX->setRange(months.first(), months.back()); axisX->setTitleFont(QFont("Microsoft YaHei",8)); axisX->setLabelsFont(QFont("Microsoft YaHei",8)); barChart->setAxisX(axisX, barSeries); QValueAxis *axisY = new QValueAxis(); axisY->setMin(0); axisY->setLabelFormat("%.0f"); axisY->setTitleText("kWh"); axisY->setTitleFont(QFont("Microsoft YaHei",8)); axisY->setLabelsFont(QFont("Microsoft YaHei",8)); barChart->setAxisY(axisY, barSeries); barChart->setGeometry(btnL->width(), 0, this->width() - 2*btnL->width() , this->height()); } void DataStage::showAsBarChart() { if (cur_item == 1) { scene->removeItem(chart1); scene->removeItem(chart2); } scene->addItem(barChart); cur_item = 2; scene->removeItem(L); scene->removeItem(R); scene->addItem(L); scene->addItem(R); this->viewport()->repaint(); this->show(); } void DataStage::showChart() { btnL->setEnabled(false); btnR->setEnabled(true); showAsBarChart(); } double DataStage::getSumPercent() { return (s1.sum() - s2.sum())/s1.sum(); } void DataStage::setChartInfo(int quarter) { newBarChartData(quarter); newPieChartData(quarter); }
[ "741409033@qq.com" ]
741409033@qq.com
03962cb33d91da5c77e4e5522849804b15bb1552
96d75738600c6d295266fd4af5e81957a3a26a26
/clients/include/testing_rot_strided_batched.hpp
9d9ff2ae5d50b19780c087738bd35aedcf075d67
[ "MIT" ]
permissive
streamhsa/rocBLAS
ab92a1dfcf92893a93c893ecb210ce455d96f2bd
effaa52647bfcbc1dc90db2a109e05ea230604d9
refs/heads/develop
2020-08-04T00:53:54.099353
2019-11-02T23:48:29
2019-11-02T23:48:29
211,943,149
0
0
MIT
2019-11-02T23:48:30
2019-09-30T19:50:32
null
UTF-8
C++
false
false
10,141
hpp
/* ************************************************************************ * Copyright 2018-2019 Advanced Micro Devices, Inc. * ************************************************************************ */ #include "cblas_interface.hpp" #include "norm.hpp" #include "rocblas.hpp" #include "rocblas_init.hpp" #include "rocblas_math.hpp" #include "rocblas_random.hpp" #include "rocblas_test.hpp" #include "rocblas_vector.hpp" #include "unit.hpp" #include "utility.hpp" template <typename T, typename U = T, typename V = T> void testing_rot_strided_batched_bad_arg(const Arguments& arg) { rocblas_int N = 100; rocblas_int incx = 1; rocblas_stride stride_x = 1; rocblas_int incy = 1; rocblas_stride stride_y = 1; rocblas_int batch_count = 5; static const size_t safe_size = 100; rocblas_local_handle handle; device_vector<T> dx(safe_size); device_vector<T> dy(safe_size); device_vector<U> dc(1); device_vector<V> ds(1); if(!dx || !dy || !dc || !ds) { CHECK_HIP_ERROR(hipErrorOutOfMemory); return; } EXPECT_ROCBLAS_STATUS( (rocblas_rot_strided_batched<T, U, V>( nullptr, N, dx, incx, stride_x, dy, incy, stride_y, dc, ds, batch_count)), rocblas_status_invalid_handle); EXPECT_ROCBLAS_STATUS( (rocblas_rot_strided_batched<T, U, V>( handle, N, nullptr, incx, stride_x, dy, incy, stride_y, dc, ds, batch_count)), rocblas_status_invalid_pointer); EXPECT_ROCBLAS_STATUS( (rocblas_rot_strided_batched<T, U, V>( handle, N, dx, incx, stride_x, nullptr, incy, stride_y, dc, ds, batch_count)), rocblas_status_invalid_pointer); EXPECT_ROCBLAS_STATUS( (rocblas_rot_strided_batched<T, U, V>( handle, N, dx, incx, stride_x, dy, incy, stride_y, nullptr, ds, batch_count)), rocblas_status_invalid_pointer); EXPECT_ROCBLAS_STATUS( (rocblas_rot_strided_batched<T, U, V>( handle, N, dx, incx, stride_x, dy, incy, stride_y, dc, nullptr, batch_count)), rocblas_status_invalid_pointer); } template <typename T, typename U = T, typename V = T> void testing_rot_strided_batched(const Arguments& arg) { rocblas_int N = arg.N; rocblas_int incx = arg.incx; rocblas_int stride_x = arg.stride_x; rocblas_int stride_y = arg.stride_y; rocblas_int incy = arg.incy; rocblas_int batch_count = arg.batch_count; rocblas_local_handle handle; double gpu_time_used, cpu_time_used; double norm_error_host_x = 0.0, norm_error_host_y = 0.0, norm_error_device_x = 0.0, norm_error_device_y = 0.0; // check to prevent undefined memory allocation error if(N <= 0 || incx <= 0 || incy <= 0 || batch_count <= 0) { static const size_t safe_size = 100; // arbitrarily set to 100 device_vector<T> dx(safe_size); device_vector<T> dy(safe_size); device_vector<U> dc(1); device_vector<V> ds(1); if(!dx || !dy || !dc || !ds) { CHECK_HIP_ERROR(hipErrorOutOfMemory); return; } CHECK_ROCBLAS_ERROR(rocblas_set_pointer_mode(handle, rocblas_pointer_mode_device)); if(batch_count < 0) EXPECT_ROCBLAS_STATUS((rocblas_rot_strided_batched<T, U, V>)(handle, N, dx, incx, stride_x, dy, incy, stride_y, dc, ds, batch_count), rocblas_status_invalid_size); else CHECK_ROCBLAS_ERROR((rocblas_rot_strided_batched<T, U, V>( handle, N, dx, incx, stride_x, dy, incy, stride_y, dc, ds, batch_count))); return; } size_t size_x = N * size_t(incx) + size_t(stride_x) * size_t(batch_count - 1); size_t size_y = N * size_t(incy) + size_t(stride_y) * size_t(batch_count - 1); device_vector<T> dx(size_x); device_vector<T> dy(size_y); device_vector<U> dc(1); device_vector<V> ds(1); if(!dx || !dy || !dc || !ds) { CHECK_HIP_ERROR(hipErrorOutOfMemory); return; } // Initial Data on CPU host_vector<T> hx(size_x); host_vector<T> hy(size_y); host_vector<U> hc(1); host_vector<V> hs(1); rocblas_seedrand(); rocblas_init<T>(hx, 1, N, incx, stride_x, batch_count); rocblas_init<T>(hy, 1, N, incy, stride_y, batch_count); // Random alpha (0 - 10) host_vector<rocblas_int> alpha(1); rocblas_init<rocblas_int>(alpha, 1, 1, 1); // cos and sin of alpha (in rads) hc[0] = cos(alpha[0]); hs[0] = sin(alpha[0]); // CPU BLAS reference data host_vector<T> cx = hx; host_vector<T> cy = hy; // cblas_rotg<T, U>(cx, cy, hc, hs); // cx[0] = hx[0]; // cy[0] = hy[0]; cpu_time_used = get_time_us(); for(int b = 0; b < batch_count; b++) { cblas_rot<T, U, V>(N, cx + b * stride_x, incx, cy + b * stride_y, incy, hc, hs); } cpu_time_used = get_time_us() - cpu_time_used; if(arg.unit_check || arg.norm_check) { // Test rocblas_pointer_mode_host { CHECK_ROCBLAS_ERROR(rocblas_set_pointer_mode(handle, rocblas_pointer_mode_host)); CHECK_HIP_ERROR(hipMemcpy(dx, hx, sizeof(T) * size_x, hipMemcpyHostToDevice)); CHECK_HIP_ERROR(hipMemcpy(dy, hy, sizeof(T) * size_y, hipMemcpyHostToDevice)); CHECK_ROCBLAS_ERROR((rocblas_rot_strided_batched<T, U, V>( handle, N, dx, incx, stride_x, dy, incy, stride_y, hc, hs, batch_count))); host_vector<T> rx(size_x); host_vector<T> ry(size_y); CHECK_HIP_ERROR(hipMemcpy(rx, dx, sizeof(T) * size_x, hipMemcpyDeviceToHost)); CHECK_HIP_ERROR(hipMemcpy(ry, dy, sizeof(T) * size_y, hipMemcpyDeviceToHost)); if(arg.unit_check) { unit_check_general<T>(1, N, batch_count, incx, stride_x, cx, rx); unit_check_general<T>(1, N, batch_count, incy, stride_y, cy, ry); } if(arg.norm_check) { norm_error_host_x = norm_check_general<T>('F', 1, N, incx, stride_x, batch_count, cx, rx); norm_error_host_y = norm_check_general<T>('F', 1, N, incy, stride_x, batch_count, cy, ry); } } // Test rocblas_pointer_mode_device { CHECK_ROCBLAS_ERROR(rocblas_set_pointer_mode(handle, rocblas_pointer_mode_device)); CHECK_HIP_ERROR(hipMemcpy(dx, hx, sizeof(T) * size_x, hipMemcpyHostToDevice)); CHECK_HIP_ERROR(hipMemcpy(dy, hy, sizeof(T) * size_y, hipMemcpyHostToDevice)); CHECK_HIP_ERROR(hipMemcpy(dc, hc, sizeof(U), hipMemcpyHostToDevice)); CHECK_HIP_ERROR(hipMemcpy(ds, hs, sizeof(V), hipMemcpyHostToDevice)); CHECK_ROCBLAS_ERROR((rocblas_rot_strided_batched<T, U, V>( handle, N, dx, incx, stride_x, dy, incy, stride_y, dc, ds, batch_count))); host_vector<T> rx(size_x); host_vector<T> ry(size_y); CHECK_HIP_ERROR(hipMemcpy(rx, dx, sizeof(T) * size_x, hipMemcpyDeviceToHost)); CHECK_HIP_ERROR(hipMemcpy(ry, dy, sizeof(T) * size_y, hipMemcpyDeviceToHost)); if(arg.unit_check) { unit_check_general<T>(1, N, batch_count, incx, stride_x, cx, rx); unit_check_general<T>(1, N, batch_count, incy, stride_y, cy, ry); } if(arg.norm_check) { norm_error_device_x = norm_check_general<T>('F', 1, N, incx, stride_x, batch_count, cx, rx); norm_error_device_y = norm_check_general<T>('F', 1, N, incy, stride_y, batch_count, cy, ry); } } } if(arg.timing) { int number_cold_calls = 2; int number_hot_calls = 100; CHECK_ROCBLAS_ERROR(rocblas_set_pointer_mode(handle, rocblas_pointer_mode_host)); CHECK_HIP_ERROR(hipMemcpy(dx, hx, sizeof(T) * size_x, hipMemcpyHostToDevice)); CHECK_HIP_ERROR(hipMemcpy(dy, hy, sizeof(T) * size_y, hipMemcpyHostToDevice)); for(int iter = 0; iter < number_cold_calls; iter++) { rocblas_rot_strided_batched<T, U, V>( handle, N, dx, incx, stride_x, dy, incy, stride_y, hc, hs, batch_count); } gpu_time_used = get_time_us(); // in microseconds for(int iter = 0; iter < number_hot_calls; iter++) { rocblas_rot_strided_batched<T, U, V>( handle, N, dx, incx, stride_x, dy, incy, stride_y, hc, hs, batch_count); } gpu_time_used = (get_time_us() - gpu_time_used) / number_hot_calls; std::cout << "N,incx,incy,rocblas(us),cpu(us)"; if(arg.norm_check) std::cout << ",norm_error_host_x,norm_error_host_y,norm_error_device_x,norm_error_device_y"; std::cout << std::endl; std::cout << N << "," << incx << "," << incy << "," << gpu_time_used << "," << cpu_time_used; if(arg.norm_check) std::cout << ',' << norm_error_host_x << ',' << norm_error_host_y << "," << norm_error_device_x << "," << norm_error_device_y; std::cout << std::endl; } }
[ "noreply@github.com" ]
streamhsa.noreply@github.com
7c8408627a8b58102976f5eeb05704c467b2fd0e
aaf59df8263a4ba01148870138691313b80b2edf
/src/DS3231.cpp
97b3dd327a429be507898be3d2ebdd698470bdea
[ "MIT" ]
permissive
rezaneam/DS3231
2be36c5f0fabb54d725a242966e72f4d9ca08377
9a1f87d0cce1244774e2ba4007b65ad53e298a90
refs/heads/main
2023-07-14T22:44:38.538950
2021-08-12T18:38:39
2021-08-12T18:38:39
375,432,855
0
0
null
null
null
null
UTF-8
C++
false
false
3,249
cpp
#include <DS3231.h> /*! * @brief Initializing the libary * @param _wire TwoWire interface - defalt Wire * @return true if any DS3231 sensor found */ bool DS3231::Initialize(TwoWire &_wire) { wire = &_wire; return (read(DS3231_REG_STATUS) != 0xFF); } void DS3231::GetTime(time_t *time) { tm time_tm = tm(); uint8_t buffer[7] = {0}; read(DS3231_REG_TIMEDATE, 7, buffer); time_tm.tm_sec = bcd2uint(buffer[0]); time_tm.tm_min = bcd2uint(buffer[1]); time_tm.tm_hour = bcd2uint24Hour(buffer[2]); time_tm.tm_wday = buffer[3]; time_tm.tm_mday = bcd2uint(buffer[4]); time_tm.tm_mon = bcd2uint(buffer[5]); time_tm.tm_year = bcd2uint(buffer[6]) + 2000; *time = mktime(&time_tm); } void DS3231::GetTime(tm *time) { uint8_t buffer[7] = {0}; read(DS3231_REG_TIMEDATE, 7, buffer); time->tm_sec = bcd2uint(buffer[0]); time->tm_min = bcd2uint(buffer[1]); time->tm_hour = bcd2uint24Hour(buffer[2]); time->tm_wday = buffer[3]; time->tm_mday = bcd2uint(buffer[4]); time->tm_mon = bcd2uint(buffer[5]); time->tm_year = bcd2uint(buffer[6]) + 2000; } void DS3231::SetTime(const tm &time) { write(DS3231_REG_TIMEDATE, uint2bcd(time.tm_sec)); write(DS3231_REG_TIMEDATE + 1, uint2bcd(time.tm_min)); write(DS3231_REG_TIMEDATE + 2, uint2bcd(time.tm_hour)); write(DS3231_REG_TIMEDATE + 4, uint2bcd(time.tm_mday)); write(DS3231_REG_TIMEDATE + 5, uint2bcd(time.tm_mon + 1)); // Month in tm factor starts with 0 (Jan) write(DS3231_REG_TIMEDATE + 6, uint2bcd(time.tm_year - 100)); // Year has 1900 as offset uint8_t val = read(DS3231_REG_STATUS); write(DS3231_REG_STATUS, val & 0x7F); // Indicate that the time is set } bool DS3231::HasValidDateTime() { return !(read(DS3231_REG_STATUS) & 0x80); } bool DS3231::IsRunning() { return !(read(DS3231_REG_CONTROL) & 0x80); } // Private methods void DS3231::read(uint8_t _register, uint8_t length, uint8_t *values) { wire->beginTransmission(address); wire->write(_register); wire->endTransmission(); wire->requestFrom(address, length); for (uint8_t i = 0; i < length; i++) values[i] = wire->read(); } uint8_t DS3231::read(uint8_t _register) { wire->beginTransmission(address); wire->write(_register); wire->endTransmission(); wire->requestFrom(address, (uint8_t)1); return wire->read(); } void DS3231::write(uint8_t _register, const uint8_t &value) { wire->beginTransmission(address); wire->write((uint8_t)_register); wire->write((uint8_t)value); wire->endTransmission(); } void DS3231::write(uint8_t _register, const uint8_t &value, const uint8_t &mask) { uint8_t val = (read(_register) & mask) | value; wire->beginTransmission(address); wire->write((uint8_t)_register); wire->write((uint8_t)val); wire->endTransmission(); } uint8_t DS3231::uint2bcd(uint8_t uint_val) { return uint_val + 6 * (uint_val / 10); } uint8_t DS3231::bcd2uint(int8_t bcd_val) { return bcd_val - 6 * (bcd_val >> 4); } uint8_t DS3231::bcd2uint24Hour(uint8_t bcdHour) { if (bcdHour & 0x40) return (bcdHour & 0x20) ? bcd2uint(bcdHour & 0x1f) + 12 : bcd2uint(bcdHour & 0x1f); return bcd2uint(bcdHour); }
[ "mr.naeemabadi@gmail.com" ]
mr.naeemabadi@gmail.com
1f44964390c5b77e710b508a3ea8b6c092fdffaf
9e7bc46001fd865b045ffe2619e690c508fe5e41
/src/runtime/vm/executable.cc
c72e70fd6f662c8f548bfba84199bf62d15cb131
[ "Apache-2.0", "Zlib", "MIT", "LicenseRef-scancode-unknown-license-reference", "Unlicense", "BSD-2-Clause" ]
permissive
Previousletters/microprocessor-TVM
6655dfd44d5ae9466c5281da13c1ad3efe80036d
7432f3a383d017d59d63011b87ca7bb42f96c9dd
refs/heads/main
2023-01-20T06:45:58.291504
2020-11-30T08:37:58
2020-11-30T08:37:58
317,151,625
1
0
null
null
null
null
UTF-8
C++
false
false
26,009
cc
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file tvm/runtime/vm/executable.cc * \brief The implementation of a virtual machine executable APIs. */ #include <dmlc/memory_io.h> #include <tvm/runtime/c_runtime_api.h> #include <tvm/runtime/registry.h> #include <tvm/runtime/vm.h> #include <algorithm> #include <iomanip> #include <iostream> #include <memory> #include <sstream> #include <utility> #include <vector> #include "serialize_util.h" namespace tvm { namespace runtime { namespace vm { #define STREAM_CHECK(val, section) \ CHECK(val) << "Invalid VM file format in the " << section << " section." \ << "\n"; // Helper to serialize a vm instruction. VMInstructionSerializer SerializeInstruction(const Instruction& instr); // Helper to deserialize a serialized vm instruction. Instruction DeserializeInstruction(const VMInstructionSerializer& instr); PackedFunc Executable::GetFunction(const std::string& name, const ObjectPtr<Object>& sptr_to_self) { if (name == "get_lib") { return PackedFunc( [sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { *rv = this->GetLib(); }); } else if (name == "get_bytecode") { return PackedFunc( [sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { *rv = this->GetBytecode(); }); } else if (name == "get_stats") { return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { *rv = this->Stats(); }); } else if (name == "save") { return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { *rv = this->Save(); }); } else if (name == "get_function_arity") { return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { std::string func_name = args[0]; *rv = this->GetFunctionArity(func_name); }); } else if (name == "get_function_param_name") { return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { std::string func_name = args[0]; int index = args[1]; *rv = this->GetFunctionParameterName(func_name, index); }); } else { LOG(FATAL) << "Unknown packed function: " << name; return PackedFunc(nullptr); } } int Executable::GetFunctionArity(std::string func_name) const { auto it = global_map.find(func_name); if (it == global_map.end()) { LOG(ERROR) << "Cannot find function " << func_name << " in executable"; return -1; } const auto& func = functions[it->second]; return func.params.size(); } std::string Executable::GetFunctionParameterName(std::string func_name, uint32_t index) const { auto it = global_map.find(func_name); if (it == global_map.end()) { LOG(ERROR) << "Cannot find function " << func_name << " in executable"; return ""; } const auto& func = functions[it->second]; if (index > func.params.size()) { LOG(ERROR) << "Invalid parameter index"; return ""; } return func.params[index]; } std::string Executable::GetBytecode() const { std::ostringstream oss; for (size_t i = 0; i < functions.size(); ++i) { const auto& func = functions[i]; // Print the header of the function format. oss << "VM Function[" << i << "]: " << func.name << "("; for (const auto& param : func.params) { oss << param << ", "; } oss.seekp(-2, std::ios_base::end); oss << ")" << std::endl; oss << "# reg file size = " << func.register_file_size << std::endl; oss << "# instruction count = " << func.instructions.size() << std::endl; // Print the instructions of a `VMFunction`. // The part after ";" is the instruction in text format. oss << "opcode, fields # inst(text):" << std::endl; for (size_t idx = 0; idx < func.instructions.size(); ++idx) { const auto& instr = func.instructions[idx]; const auto& serialized_instr = SerializeInstruction(instr); oss << std::setw(2) << idx << ": " << serialized_instr.opcode << " "; for (auto it : serialized_instr.fields) { oss << it << " "; } oss << " # " << instr; if (oss.str().back() != '\n') oss << std::endl; } oss << std::endl; } return oss.str(); } std::string Executable::Stats() const { std::ostringstream oss; oss << "Relay VM executable statistics:" << std::endl; // Get the number of constants and the shape of each of them. oss << " Constant shapes (# " << constants.size() << "): ["; for (const auto& it : constants) { const auto constant = Downcast<NDArray>(it); const auto& shape = constant.Shape(); // Scalar if (shape.empty()) { oss << "scalar, "; continue; } oss << "["; for (auto s : shape) { oss << s << ", "; } oss.seekp(-2, oss.cur); oss << "], " << std::endl; } if (!constants.empty()) oss.seekp(-2, oss.cur); oss << "]" << std::endl; // Get the number of globals and the name of each of them. oss << " Globals (#" << global_map.size() << "): ["; for (const auto& it : global_map) { oss << "(\"" << it.first << "\", " << it.second << ")" << ", "; } if (!global_map.empty()) oss.seekp(-2, oss.cur); oss << "]" << std::endl; // Get the number of primitive ops and the name of each of them. oss << " Primitive ops (#" << primitive_map.size() << "): ["; std::vector<std::string> prim_ops; for (const auto& it : primitive_map) { auto packed_index = static_cast<size_t>(it.second); if (prim_ops.size() <= packed_index) { prim_ops.resize(packed_index + 1); } prim_ops[packed_index] = it.first; } for (const auto& it : prim_ops) { oss << it << ", "; } if (!prim_ops.empty()) oss.seekp(-2, oss.cur); oss << "]" << std::endl; return oss.str(); } void SaveHeader(dmlc::Stream* strm) { uint64_t header = kTVMVMBytecodeMagic; strm->Write(header); std::string version = TVM_VERSION; strm->Write(version); } TVMByteArray Executable::Save() { // Initialize the stream object. code_.clear(); dmlc::MemoryStringStream strm(&code_); // Save header SaveHeader(&strm); // Global section. SaveGlobalSection(&strm); // Constant section. SaveConstantSection(&strm); // Primitive names. SavePrimitiveOpNames(&strm); // Code section. SaveCodeSection(&strm); TVMByteArray arr; arr.data = code_.c_str(); arr.size = code_.length(); return arr; } void Executable::SaveGlobalSection(dmlc::Stream* strm) { std::vector<std::pair<std::string, Index> > globals(this->global_map.begin(), this->global_map.end()); auto comp = [](const std::pair<std::string, Index>& a, const std::pair<std::string, Index>& b) { return a.second < b.second; }; std::sort(globals.begin(), globals.end(), comp); std::vector<std::string> glbs; for (const auto& it : globals) { glbs.push_back(it.first); } strm->Write(glbs); } void Executable::SaveConstantSection(dmlc::Stream* strm) { std::vector<DLTensor*> arrays; for (const auto& obj : this->constants) { const auto cell = Downcast<runtime::NDArray>(obj); arrays.push_back(const_cast<DLTensor*>(cell.operator->())); } strm->Write(static_cast<uint64_t>(this->constants.size())); for (const auto& it : arrays) { runtime::SaveDLTensor(strm, it); } } void Executable::SavePrimitiveOpNames(dmlc::Stream* strm) { std::vector<std::string> primitive_names; for (const auto& it : this->primitive_map) { auto packed_index = static_cast<size_t>(it.second); if (primitive_names.size() <= packed_index) { primitive_names.resize(packed_index + 1); } primitive_names[packed_index] = it.first; } strm->Write(primitive_names); } // Serialize a virtual machine instruction. It creates a list that contains the // hash, opcode, and all fields of an instruction. // // For example, the function signature used to create an `AllocTensor` // instruction is: // Instruction AllocTensor(std::vector<Index> shape, DLDataType dtype, RegName dst) // // The serialized form will be: // `hash 5 dtype.code dtype.bits dtype.lanes ndim dst_register val1 val2 ... valn` // // where hash is the hash of serialized instruction that is computed internally // by the `VMInstructionExecutable`. It is used for sanity check before decoding. // 5 shows opcode of `AllocTensor`, `(dtype.code dtype.bits dtype.lanes)` // represents a `DLDataType`, `ndim` is the number of dimensions, `dst_register` // is the destination register, and the rest of it together indicates the shape // of the tensor to be allocated. VMInstructionSerializer SerializeInstruction(const Instruction& instr) { std::vector<Index> fields; // Save the opcode. DLOG(INFO) << "Serializing: " << instr << std::endl; switch (instr.op) { case Opcode::Move: { // Number of fields = 2 fields.assign({instr.from, instr.dst}); break; } case Opcode::Ret: { // Number of fields = 1 fields.push_back(instr.result); break; } case Opcode::Fatal: { // Number of fields = 0 break; } case Opcode::InvokePacked: { // Number of fields = 3 + instr.arity // Note that arity includes both input arguments and outputs. We will // put all the `arity` number of fields in the end for serialization. fields.assign({instr.packed_index, instr.arity, instr.output_size}); // Save the args. fields.insert(fields.end(), instr.packed_args, instr.packed_args + instr.arity); break; } case Opcode::AllocTensor: { // Number of fields = 5 + instr.alloc_tensor.ndim fields.push_back(instr.alloc_tensor.storage); // Save `DLDataType` and the dst register. const auto& dtype = instr.alloc_tensor.dtype; fields.push_back(dtype.code); fields.push_back(dtype.bits); fields.push_back(dtype.lanes); // The number of dimensions is not needed for constructing an // `AllocTensor` instruction as it equals to the length of the `shape` // vector. However, we save it to conveniently deserialize the instruction // because we will know how many fields are needed by the `shape` argument. fields.push_back(instr.alloc_tensor.ndim); fields.push_back(instr.dst); // Save the shape of the tensor. // Note that this field is rotated to the end of the list. fields.insert(fields.end(), instr.alloc_tensor.shape, instr.alloc_tensor.shape + instr.alloc_tensor.ndim); break; } case Opcode::AllocTensorReg: { // Number of fields = 6 fields.push_back(instr.alloc_tensor_reg.storage); fields.push_back(instr.alloc_tensor_reg.shape_register); // Save `DLDataType` and the dst register. const auto& dtype = instr.alloc_tensor_reg.dtype; fields.push_back(dtype.code); fields.push_back(dtype.bits); fields.push_back(dtype.lanes); fields.push_back(instr.dst); break; } case Opcode::AllocStorage: { fields.push_back(instr.alloc_storage.allocation_size); fields.push_back(instr.alloc_storage.alignment); // Save `DLDataType` and the dst register. const auto& dtype = instr.alloc_storage.dtype_hint; fields.push_back(dtype.code); fields.push_back(dtype.bits); fields.push_back(dtype.lanes); fields.push_back(instr.dst); break; } case Opcode::AllocADT: { // Number of fields = 3 + instr.num_fields fields.assign({instr.constructor_tag, instr.num_fields, instr.dst}); // Save the fields. fields.insert(fields.end(), instr.datatype_fields, instr.datatype_fields + instr.num_fields); break; } case Opcode::AllocClosure: { // Number of fields = 3 + instr.num_freevar fields.assign({instr.clo_index, instr.num_freevar, instr.dst}); // Save the free vars. fields.insert(fields.end(), instr.free_vars, instr.free_vars + instr.num_freevar); break; } case Opcode::If: { // Number of fields = 4 fields.assign({instr.if_op.test, instr.if_op.target, instr.if_op.true_offset, instr.if_op.false_offset}); break; } case Opcode::Invoke: { // Number of fields = 3 + instr.num_args fields.assign({instr.func_index, instr.num_args, instr.dst}); // Save the args. fields.insert(fields.end(), instr.invoke_args_registers, instr.invoke_args_registers + instr.num_args); break; } case Opcode::InvokeClosure: { // Number of fields = 3 + instr.num_closure_args fields.assign({instr.closure, instr.num_closure_args, instr.dst}); // Save the args. fields.insert(fields.end(), instr.closure_args, instr.closure_args + instr.num_closure_args); break; } case Opcode::LoadConst: { // Number of fields = 2 fields.assign({instr.const_index, instr.dst}); break; } case Opcode::LoadConsti: { // Number of fields = 2 fields.assign({instr.load_consti.val, instr.dst}); break; } case Opcode::GetField: { // Number of fields = 3 fields.assign({instr.object, instr.field_index, instr.dst}); break; } case Opcode::GetTag: { // Number of fields = 2 fields.assign({instr.get_tag.object, instr.dst}); break; } case Opcode::Goto: { // Number of fields = 1 fields.push_back(instr.pc_offset); break; } default: LOG(FATAL) << "Invalid opcode" << static_cast<int>(instr.op); break; } return VMInstructionSerializer(static_cast<Index>(instr.op), fields); } void Executable::SaveCodeSection(dmlc::Stream* strm) { // Save the number of functions. strm->Write(static_cast<uint64_t>(this->functions.size())); for (const auto& func : this->functions) { // Save the function info. VMFunctionSerializer func_format(func.name, func.register_file_size, func.instructions.size(), func.params); func_format.Save(strm); // Serialize each instruction. for (const auto& instr : func.instructions) { const auto& serialized_instr = SerializeInstruction(instr); serialized_instr.Save(strm); } } } void LoadHeader(dmlc::Stream* strm) { // Check header. uint64_t header; STREAM_CHECK(strm->Read(&header), "header"); STREAM_CHECK(header == kTVMVMBytecodeMagic, "header"); // Check version. std::string version; STREAM_CHECK(strm->Read(&version), "version"); STREAM_CHECK(version == TVM_VERSION, "version"); } runtime::Module Executable::Load(const std::string& code, const runtime::Module lib) { auto exec = make_object<Executable>(); exec->lib = lib; exec->code_ = code; dmlc::MemoryStringStream strm(&exec->code_); // Load header. LoadHeader(&strm); // Global section. exec->LoadGlobalSection(&strm); // Constant section. exec->LoadConstantSection(&strm); // Primitive names that will be invoked by `InvokePacked` instructions. exec->LoadPrimitiveOpNames(&strm); // Code section. exec->LoadCodeSection(&strm); return runtime::Module(exec); } void Executable::LoadGlobalSection(dmlc::Stream* strm) { std::vector<std::string> globals; STREAM_CHECK(strm->Read(&globals), "global"); for (size_t i = 0; i < globals.size(); i++) { this->global_map.insert({globals[i], i}); } } void Executable::LoadConstantSection(dmlc::Stream* strm) { uint64_t sz; // Load the number of constants. STREAM_CHECK(strm->Read(&sz, sizeof(sz)), "constant"); size_t size = static_cast<size_t>(sz); // Load each of the constants. for (size_t i = 0; i < size; i++) { runtime::NDArray constant; STREAM_CHECK(constant.Load(strm), "constant"); this->constants.push_back(constant); } } void Executable::LoadPrimitiveOpNames(dmlc::Stream* strm) { std::vector<std::string> primitive_names; STREAM_CHECK(strm->Read(&primitive_names), "primitive name"); for (size_t i = 0; i < primitive_names.size(); i++) { this->primitive_map.insert({primitive_names[i], i}); } } // Extract the `cnt` number of fields started at `start` from the list // `instr_fields`. inline std::vector<Index> ExtractFields(const std::vector<Index>& instr_fields, Index start, Index cnt) { CHECK_LE(static_cast<size_t>(start + cnt), instr_fields.size()); std::vector<Index> ret; for (auto i = start; i < start + cnt; i++) { ret.push_back(instr_fields[i]); } return ret; } Instruction DeserializeInstruction(const VMInstructionSerializer& instr) { Opcode opcode = static_cast<Opcode>(instr.opcode); switch (opcode) { case Opcode::Move: { // Number of fields = 2 DCHECK_EQ(instr.fields.size(), 2U); return Instruction::Move(instr.fields[0], instr.fields[1]); } case Opcode::Ret: { // Number of fields = 1 DCHECK_EQ(instr.fields.size(), 1U); return Instruction::Ret(instr.fields[0]); } case Opcode::Fatal: { // Number of fields = 0 DCHECK(instr.fields.empty()); return Instruction::Fatal(); } case Opcode::InvokePacked: { // Number of fields = 3 + instr.arity DCHECK_GE(instr.fields.size(), 3U); DCHECK_EQ(instr.fields.size(), 3U + static_cast<size_t>(instr.fields[1])); Index packed_index = instr.fields[0]; Index arity = instr.fields[1]; Index output_size = instr.fields[2]; std::vector<RegName> args = ExtractFields(instr.fields, 3, arity); return Instruction::InvokePacked(packed_index, arity, output_size, args); } case Opcode::AllocTensor: { // Number of fields = 6 + instr.alloc_tensor.ndim DCHECK_GE(instr.fields.size(), 6U); DCHECK_EQ(instr.fields.size(), 6U + static_cast<size_t>(instr.fields[4])); RegName storage_reg = instr.fields[0]; DLDataType dtype; dtype.code = instr.fields[1]; dtype.bits = instr.fields[2]; dtype.lanes = instr.fields[3]; Index ndim = instr.fields[4]; RegName dst = instr.fields[5]; std::vector<Index> shape = ExtractFields(instr.fields, 6, ndim); return Instruction::AllocTensor(storage_reg, shape, dtype, dst); } case Opcode::AllocTensorReg: { // Number of fields = 5 DCHECK_EQ(instr.fields.size(), 6U); RegName storage_reg = instr.fields[0]; Index shape_register = instr.fields[1]; DLDataType dtype; dtype.code = instr.fields[2]; dtype.bits = instr.fields[3]; dtype.lanes = instr.fields[4]; RegName dst = instr.fields[5]; return Instruction::AllocTensorReg(storage_reg, shape_register, dtype, dst); } case Opcode::AllocADT: { // Number of fields = 3 + instr.num_fields DCHECK_GE(instr.fields.size(), 3U); DCHECK_EQ(instr.fields.size(), 3U + static_cast<size_t>(instr.fields[1])); Index constructor_tag = instr.fields[0]; Index num_fields = instr.fields[1]; RegName dst = instr.fields[2]; std::vector<Index> fields = ExtractFields(instr.fields, 3, num_fields); return Instruction::AllocADT(constructor_tag, num_fields, fields, dst); } case Opcode::AllocClosure: { // Number of fields = 3 + instr.num_freevar DCHECK_GE(instr.fields.size(), 3U); DCHECK_EQ(instr.fields.size(), 3U + static_cast<size_t>(instr.fields[1])); Index clo_index = instr.fields[0]; Index num_freevar = instr.fields[1]; RegName dst = instr.fields[2]; std::vector<Index> free_vars = ExtractFields(instr.fields, 3, num_freevar); return Instruction::AllocClosure(clo_index, num_freevar, free_vars, dst); } case Opcode::AllocStorage: { DCHECK_GE(instr.fields.size(), 6U); Index allocation_size = instr.fields[0]; Index alignment = instr.fields[1]; DLDataType dtype; dtype.code = instr.fields[2]; dtype.bits = instr.fields[3]; dtype.lanes = instr.fields[4]; RegName dst = instr.fields[5]; return Instruction::AllocStorage(allocation_size, alignment, dtype, dst); } case Opcode::If: { // Number of fields = 4 DCHECK_EQ(instr.fields.size(), 4U); Index test = instr.fields[0]; Index target = instr.fields[1]; Index true_offset = instr.fields[2]; Index false_offset = instr.fields[3]; return Instruction::If(test, target, true_offset, false_offset); } case Opcode::Invoke: { // Number of fields = 3 + instr.num_args DCHECK_GE(instr.fields.size(), 3U); DCHECK_EQ(instr.fields.size(), 3U + static_cast<size_t>(instr.fields[1])); Index func_index = instr.fields[0]; Index num_args = instr.fields[1]; RegName dst = instr.fields[2]; std::vector<Index> args = ExtractFields(instr.fields, 3, num_args); return Instruction::Invoke(func_index, args, dst); } case Opcode::InvokeClosure: { // Number of fields = 3 + instr.num_closure_args DCHECK_GE(instr.fields.size(), 3U); DCHECK_EQ(instr.fields.size(), 3U + static_cast<size_t>(instr.fields[1])); Index closure = instr.fields[0]; Index num_closure_args = instr.fields[1]; RegName dst = instr.fields[2]; std::vector<Index> args = ExtractFields(instr.fields, 3, num_closure_args); return Instruction::InvokeClosure(closure, args, dst); } case Opcode::LoadConst: { // Number of fields = 2 DCHECK_EQ(instr.fields.size(), 2U); return Instruction::LoadConst(instr.fields[0], instr.fields[1]); } case Opcode::LoadConsti: { // Number of fields = 2 DCHECK_EQ(instr.fields.size(), 2U); return Instruction::LoadConsti(instr.fields[0], instr.fields[1]); } case Opcode::GetField: { // Number of fields = 3 DCHECK_EQ(instr.fields.size(), 3U); return Instruction::GetField(instr.fields[0], instr.fields[1], instr.fields[2]); } case Opcode::GetTag: { // Number of fields = 2 DCHECK_EQ(instr.fields.size(), 2U); return Instruction::GetTag(instr.fields[0], instr.fields[1]); } case Opcode::Goto: { // Number of fields = 1 DCHECK_EQ(instr.fields.size(), 1U); return Instruction::Goto(instr.fields[0]); } default: LOG(FATAL) << "Invalid opcode" << instr.opcode; return Instruction(); } } void Executable::LoadCodeSection(dmlc::Stream* strm) { // Load the number of functions. uint64_t sz; STREAM_CHECK(strm->Read(&sz, sizeof(sz)), "code"); size_t num_funcs = static_cast<size_t>(sz); this->functions.resize(num_funcs); for (size_t i = 0; i < num_funcs; i++) { // Load the function info. VMFunctionSerializer loaded_func; STREAM_CHECK(loaded_func.Load(strm), "code/function"); // Load the instructions. std::vector<Instruction> instructions; for (size_t j = 0; j < loaded_func.num_instructions; j++) { VMInstructionSerializer instr; std::vector<Index> instr_fields; STREAM_CHECK(instr.Load(strm), "code/instruction"); instructions.push_back(DeserializeInstruction(instr)); } // Create the VM function. VMFunction vm_func = VMFunction(loaded_func.name, loaded_func.params, instructions, loaded_func.register_file_size); auto it = this->global_map.find(loaded_func.name); CHECK(it != this->global_map.end()); CHECK_LE(it->second, this->global_map.size()); this->functions[it->second] = vm_func; } } TVM_REGISTER_GLOBAL("runtime.GetNumOfGlobals").set_body([](TVMArgs args, TVMRetValue* rv) { runtime::Module mod = args[0]; const auto* exec = dynamic_cast<Executable*>(mod.operator->()); CHECK(exec); *rv = static_cast<int>(exec->global_map.size()); }); TVM_REGISTER_GLOBAL("runtime.GetGlobalFields").set_body([](TVMArgs args, TVMRetValue* rv) { runtime::Module mod = args[0]; const auto* exec = dynamic_cast<Executable*>(mod.operator->()); CHECK(exec); int idx = args[1]; std::vector<std::pair<std::string, Index> > globals(exec->global_map.begin(), exec->global_map.end()); auto comp = [](const std::pair<std::string, Index>& a, const std::pair<std::string, Index>& b) { return a.second < b.second; }; std::sort(globals.begin(), globals.end(), comp); CHECK_LT(idx, globals.size()); *rv = globals[idx].first; }); TVM_REGISTER_GLOBAL("runtime.GetNumOfPrimitives").set_body([](TVMArgs args, TVMRetValue* rv) { runtime::Module mod = args[0]; const auto* exec = dynamic_cast<Executable*>(mod.operator->()); CHECK(exec); *rv = static_cast<int>(exec->primitive_map.size()); }); TVM_REGISTER_GLOBAL("runtime.GetPrimitiveFields").set_body([](TVMArgs args, TVMRetValue* rv) { runtime::Module mod = args[0]; const auto* exec = dynamic_cast<Executable*>(mod.operator->()); CHECK(exec); int idx = args[1]; CHECK_GE(idx, 0); CHECK_LT(idx, exec->primitive_map.size()); for (const auto& it : exec->primitive_map) { if (idx == static_cast<int>(it.second)) { *rv = it.first; break; } } }); TVM_REGISTER_GLOBAL("runtime.Load_Executable") .set_body_typed([](std::string code, runtime::Module lib) { return Executable::Load(code, lib); }); } // namespace vm } // namespace runtime } // namespace tvm
[ "previous@PreviousLetters.localdomain" ]
previous@PreviousLetters.localdomain
cf791db301f8731ed3326f8561d79ddfcc275e8e
2b3b5203233ebb11ccbf3c9830de9e26cc2785ee
/XRay/xrCore/FileSystem.cpp
d67fe1ed265aab35ef509bbe37a965635f9f2785
[ "Apache-2.0" ]
permissive
OLR-xray/XRay-NEW
b308aeefada0f0361706e8e57f23ebafc7fe3bc5
f6988c98b45a9ff4eefec9538c6dffadef170ed7
refs/heads/master
2021-01-24T19:12:44.173491
2016-02-17T21:42:31
2016-02-17T21:42:31
50,777,026
3
1
null
null
null
null
UTF-8
C++
false
false
6,854
cpp
//---------------------------------------------------- // file: FileSystem.cpp //---------------------------------------------------- #include "stdafx.h" #pragma hdrstop #include "cderr.h" #include "commdlg.h" EFS_Utils* xr_EFS = NULL; //---------------------------------------------------- EFS_Utils::EFS_Utils( ) { } EFS_Utils::~EFS_Utils() { } xr_string EFS_Utils::ExtractFileName(LPCSTR src) { string_path name; _splitpath (src,0,0,name,0); return xr_string(name); } xr_string EFS_Utils::ExtractFileExt(LPCSTR src) { string_path ext; _splitpath (src,0,0,0,ext); return xr_string(ext); } xr_string EFS_Utils::ExtractFilePath(LPCSTR src) { string_path drive,dir; _splitpath (src,drive,dir,0,0); return xr_string(drive)+dir; } xr_string EFS_Utils::ExcludeBasePath(LPCSTR full_path, LPCSTR excl_path) { LPCSTR sub = strstr(full_path,excl_path); if (0!=sub) return xr_string(sub+xr_strlen(excl_path)); else return xr_string(full_path); } xr_string EFS_Utils::ChangeFileExt(LPCSTR src, LPCSTR ext) { xr_string tmp; LPSTR src_ext = strext(src); if (src_ext){ size_t ext_pos = src_ext-src; tmp.assign (src,0,ext_pos); }else{ tmp = src; } tmp += ext; return tmp; } xr_string EFS_Utils::ChangeFileExt(const xr_string& src, LPCSTR ext) { return ChangeFileExt(src.c_str(),ext); } //---------------------------------------------------- LPCSTR MakeFilter(string1024& dest, LPCSTR info, LPCSTR ext) { ZeroMemory(dest,sizeof(dest)); if (ext){ int icnt=_GetItemCount(ext,';'); LPSTR dst=dest; if (icnt>1){ strconcat(dst,info," (",ext,")"); dst+=(xr_strlen(dst)+1); strcpy(dst,ext); dst+=(xr_strlen(ext)+1); } for (int i=0; i<icnt; i++){ string64 buf; _GetItem(ext,i,buf,';'); strconcat(dst,info," (",buf,")"); dst+=(xr_strlen(dst)+1); strcpy(dst,buf); dst+=(xr_strlen(buf)+1); } } return dest; } //------------------------------------------------------------------------------ // start_flt_ext = -1-all 0..n-indices //------------------------------------------------------------------------------ bool EFS_Utils::GetOpenName( LPCSTR initial, char *buffer, int sz_buf, bool bMulti, LPCSTR offset, int start_flt_ext ) { VERIFY(buffer&&(sz_buf>0)); FS_Path& P = *FS.get_path(initial); string1024 flt; MakeFilter(flt,P.m_FilterCaption?P.m_FilterCaption:"",P.m_DefExt); OPENFILENAME ofn; Memory.mem_fill ( &ofn, 0, sizeof(ofn) ); if (xr_strlen(buffer)){ string_path dr; if (!(buffer[0]=='\\' && buffer[1]=='\\')){ // if !network _splitpath (buffer,dr,0,0,0); if (0==dr[0]) P._update(buffer,buffer); } } ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = GetForegroundWindow(); ofn.lpstrDefExt = P.m_DefExt; ofn.lpstrFile = buffer; ofn.nMaxFile = sz_buf; ofn.lpstrFilter = flt; ofn.nFilterIndex = start_flt_ext+2; ofn.lpstrTitle = "Open a File"; string512 path; strcpy(path,(offset&&offset[0])?offset:P.m_Path); ofn.lpstrInitialDir = path; ofn.Flags = OFN_PATHMUSTEXIST| OFN_FILEMUSTEXIST| OFN_HIDEREADONLY| OFN_FILEMUSTEXIST| OFN_NOCHANGEDIR|(bMulti?OFN_ALLOWMULTISELECT|OFN_EXPLORER:0); ofn.FlagsEx = OFN_EX_NOPLACESBAR; bool bRes = !!GetOpenFileName( &ofn ); if (!bRes){ u32 err = CommDlgExtendedError(); switch(err){ case FNERR_BUFFERTOOSMALL: Log("Too many file selected."); break; } } if (bRes&&bMulti){ int cnt = _GetItemCount(buffer,0x0); if (cnt>1){ string64 buf; string64 dir; string4096 fns; strcpy(dir, buffer); strcpy (fns,dir); strcat (fns,"\\"); strcat (fns,_GetItem(buffer,1,buf,0x0)); for (int i=2; i<cnt; i++){ strcat (fns,","); strcat (fns,dir); strcat (fns,"\\"); strcat (fns,_GetItem(buffer,i,buf,0x0)); } strcpy (buffer,fns); } } strlwr(buffer); return bRes; } bool EFS_Utils::GetSaveName( LPCSTR initial, char *buffer, int sz_buf, LPCSTR offset, int start_flt_ext ) { VERIFY(buffer&&(sz_buf>0)); FS_Path& P = *FS.get_path(initial); string1024 flt; MakeFilter(flt,P.m_FilterCaption?P.m_FilterCaption:"",P.m_DefExt); OPENFILENAME ofn; Memory.mem_fill ( &ofn, 0, sizeof(ofn) ); if (xr_strlen(buffer)){ string_path dr; if (!(buffer[0]=='\\' && buffer[1]=='\\')){ // if !network _splitpath (buffer,dr,0,0,0); if (0==dr[0]) P._update(buffer,buffer); } } ofn.hwndOwner = GetForegroundWindow(); ofn.lpstrDefExt = P.m_DefExt; ofn.lpstrFile = buffer; ofn.lpstrFilter = flt; ofn.lStructSize = sizeof(ofn); ofn.nMaxFile = sz_buf; ofn.nFilterIndex = start_flt_ext+2; ofn.lpstrTitle = "Save a File"; string512 path; strcpy(path,(offset&&offset[0])?offset:P.m_Path); ofn.lpstrInitialDir = path; ofn.Flags = OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT|OFN_NOCHANGEDIR; ofn.FlagsEx = OFN_EX_NOPLACESBAR; bool bRes = !!GetSaveFileName( &ofn ); if (!bRes){ u32 err = CommDlgExtendedError(); switch(err){ case FNERR_BUFFERTOOSMALL: Log("Too many file selected."); break; } } strlwr(buffer); return bRes; } //---------------------------------------------------- LPCSTR EFS_Utils::AppendFolderToName(LPSTR tex_name, int depth, BOOL full_name) { string256 _fn; strcpy(tex_name,AppendFolderToName(tex_name, _fn, depth, full_name)); return tex_name; } LPCSTR EFS_Utils::AppendFolderToName(LPCSTR src_name, LPSTR dest_name, int depth, BOOL full_name) { shared_str tmp = src_name; LPCSTR s = src_name; LPSTR d = dest_name; int sv_depth= depth; for (; *s&&depth; s++, d++){ if (*s=='_'){depth--; *d='\\';}else{*d=*s;} } if (full_name){ *d = 0; if (depth<sv_depth) strcat(dest_name,*tmp); }else{ for (; *s; s++, d++) *d=*s; *d = 0; } return dest_name; /* if (_GetItemCount(src_name,'_')>1){ string256 fld; _GetItem(src_name,0,fld,'_'); sprintf(dest_name,"%s\\%s",fld,src_name); }else{ strcpy(dest_name,src_name); } return dest_name; */ } LPCSTR EFS_Utils::GenerateName(LPCSTR base_path, LPCSTR base_name, LPCSTR def_ext, LPSTR out_name) { int cnt = 0; string256 fn; if (base_name) strconcat (fn,base_path,base_name,def_ext); else sprintf (fn,"%s%02d%s",base_path,cnt++,def_ext); while (FS.exist(fn)) if (base_name) sprintf(fn,"%s%s%02d%s",base_path,base_name,cnt++,def_ext); else sprintf(fn,"%s%02d%s",base_path,cnt++,def_ext); strcpy(out_name,fn); return out_name; } //#endif
[ "vlad_tislenko@mail.ru" ]
vlad_tislenko@mail.ru
d09f1cbbbd683842f15c75c011cf0659c4fd99a4
5456502f97627278cbd6e16d002d50f1de3da7bb
/ash/display/cursor_window_controller_unittest.cc
e80a1e81a506a7bf11f82062bc454174b8bfa9f2
[ "BSD-3-Clause" ]
permissive
TrellixVulnTeam/Chromium_7C66
72d108a413909eb3bd36c73a6c2f98de1573b6e5
c8649ab2a0f5a747369ed50351209a42f59672ee
refs/heads/master
2023-03-16T12:51:40.231959
2017-12-20T10:38:26
2017-12-20T10:38:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,588
cc
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/display/cursor_window_controller.h" #include "ash/display/display_util.h" #include "ash/display/window_tree_host_manager.h" #include "ash/shell.h" #include "ash/test/ash_test_base.h" #include "ui/aura/window.h" #include "ui/aura/window_tree_host.h" #include "ui/base/cursor/cursor.h" #include "ui/display/display.h" #include "ui/display/screen.h" #include "ui/display/test/display_manager_test_api.h" #include "ui/events/test/event_generator.h" #include "ui/wm/core/coordinate_conversion.h" namespace ash { class CursorWindowControllerTest : public test::AshTestBase { public: CursorWindowControllerTest() {} ~CursorWindowControllerTest() override {} // test::AshTestBase: void SetUp() override { AshTestBase::SetUp(); SetCursorCompositionEnabled(true); } int GetCursorType() const { return cursor_window_controller_->cursor_type_; } const gfx::Point& GetCursorHotPoint() const { return cursor_window_controller_->hot_point_; } aura::Window* GetCursorWindow() const { return cursor_window_controller_->cursor_window_.get(); } const gfx::ImageSkia& GetCursorImage() const { return cursor_window_controller_->GetCursorImageForTest(); } int64_t GetCursorDisplayId() const { return cursor_window_controller_->display_.id(); } void SetCursorCompositionEnabled(bool enabled) { cursor_window_controller_ = Shell::GetInstance() ->window_tree_host_manager() ->cursor_window_controller(); cursor_window_controller_->SetCursorCompositingEnabled(enabled); } private: // Not owned. CursorWindowController* cursor_window_controller_; DISALLOW_COPY_AND_ASSIGN(CursorWindowControllerTest); }; // Test that the composited cursor moves to another display when the real cursor // moves to another display. TEST_F(CursorWindowControllerTest, MoveToDifferentDisplay) { if (!SupportsMultipleDisplays()) return; UpdateDisplay("200x200,200x200*2/r"); WindowTreeHostManager* window_tree_host_manager = Shell::GetInstance()->window_tree_host_manager(); int64_t primary_display_id = window_tree_host_manager->GetPrimaryDisplayId(); int64_t secondary_display_id = display_manager()->GetSecondaryDisplay().id(); aura::Window* primary_root = window_tree_host_manager->GetRootWindowForDisplayId(primary_display_id); aura::Window* secondary_root = window_tree_host_manager->GetRootWindowForDisplayId(secondary_display_id); ui::test::EventGenerator primary_generator(primary_root); primary_generator.MoveMouseToInHost(20, 50); EXPECT_TRUE(primary_root->Contains(GetCursorWindow())); EXPECT_EQ(primary_display_id, GetCursorDisplayId()); EXPECT_EQ(ui::kCursorNull, GetCursorType()); gfx::Point hot_point = GetCursorHotPoint(); EXPECT_EQ("4,4", hot_point.ToString()); gfx::Rect cursor_bounds = GetCursorWindow()->GetBoundsInScreen(); EXPECT_EQ(20, cursor_bounds.x() + hot_point.x()); EXPECT_EQ(50, cursor_bounds.y() + hot_point.y()); // The cursor can only be moved between displays via // WindowTreeHost::MoveCursorTo(). EventGenerator uses a hack to move the // cursor between displays. // Screen location: 220, 50 // Root location: 20, 50 secondary_root->MoveCursorTo(gfx::Point(20, 50)); // Chrome relies on WindowTreeHost::MoveCursorTo() dispatching a mouse move // asynchronously. This is implemented in a platform specific way. Generate a // fake mouse move instead of waiting. gfx::Point new_cursor_position_in_host(20, 50); secondary_root->GetHost()->ConvertPointToHost(&new_cursor_position_in_host); ui::test::EventGenerator secondary_generator(secondary_root); secondary_generator.MoveMouseToInHost(new_cursor_position_in_host); EXPECT_TRUE(secondary_root->Contains(GetCursorWindow())); EXPECT_EQ(secondary_display_id, GetCursorDisplayId()); EXPECT_EQ(ui::kCursorNull, GetCursorType()); hot_point = GetCursorHotPoint(); EXPECT_EQ("3,3", hot_point.ToString()); cursor_bounds = GetCursorWindow()->GetBoundsInScreen(); EXPECT_EQ(220, cursor_bounds.x() + hot_point.x()); EXPECT_EQ(50, cursor_bounds.y() + hot_point.y()); } // Windows doesn't support compositor based cursor. #if !defined(OS_WIN) // Make sure that composition cursor inherits the visibility state. TEST_F(CursorWindowControllerTest, VisibilityTest) { ASSERT_TRUE(GetCursorWindow()); EXPECT_TRUE(GetCursorWindow()->IsVisible()); aura::client::CursorClient* client = Shell::GetInstance()->cursor_manager(); client->HideCursor(); ASSERT_TRUE(GetCursorWindow()); EXPECT_FALSE(GetCursorWindow()->IsVisible()); // Normal cursor should be in the correct state. SetCursorCompositionEnabled(false); ASSERT_FALSE(GetCursorWindow()); ASSERT_FALSE(client->IsCursorVisible()); // Cursor was hidden. SetCursorCompositionEnabled(true); ASSERT_TRUE(GetCursorWindow()); EXPECT_FALSE(GetCursorWindow()->IsVisible()); // Goback to normal cursor and show the cursor. SetCursorCompositionEnabled(false); ASSERT_FALSE(GetCursorWindow()); ASSERT_FALSE(client->IsCursorVisible()); client->ShowCursor(); ASSERT_TRUE(client->IsCursorVisible()); // Cursor was shown. SetCursorCompositionEnabled(true); ASSERT_TRUE(GetCursorWindow()); EXPECT_TRUE(GetCursorWindow()->IsVisible()); } // Make sure that composition cursor stays big even when // the DSF becomes 1x as a result of zooming out. TEST_F(CursorWindowControllerTest, DSF) { UpdateDisplay("1000x500*2"); int64_t primary_id = display::Screen::GetScreen()->GetPrimaryDisplay().id(); display::test::ScopedSetInternalDisplayId set_internal(display_manager(), primary_id); SetCursorCompositionEnabled(true); ASSERT_EQ( 2.0f, display::Screen::GetScreen()->GetPrimaryDisplay().device_scale_factor()); EXPECT_TRUE(GetCursorImage().HasRepresentation(2.0f)); ASSERT_TRUE(display::test::DisplayManagerTestApi(display_manager()) .SetDisplayUIScale(primary_id, 2.0f)); ASSERT_EQ( 1.0f, display::Screen::GetScreen()->GetPrimaryDisplay().device_scale_factor()); EXPECT_TRUE(GetCursorImage().HasRepresentation(2.0f)); } #endif } // namespace ash
[ "lixiaodonglove7@aliyun.com" ]
lixiaodonglove7@aliyun.com
7071092d6d59b1232b44433f45659e861daa2bb3
596b4a6fa7f733bb173ee7bf048ba8e3c6975baa
/Nmea.cpp
43d5f88c66d96e40afa0f3ad0c30eba61aa42422
[]
no_license
idaohang/GNSS_Viewer_V2
de35d57712fd8fc56d7b43b61484039b1e803398
59305cc1b8988c6b1000e7760d0ef034cb9b3d88
refs/heads/master
2020-12-25T06:13:50.690423
2015-07-21T08:18:53
2015-07-21T08:18:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
21,687
cpp
#include "StdAfx.h" #include "NMEA.h" #include "GPSDlg.h" using namespace std; Satellite satellites_gps[MAX_SATELLITE]; Satellite satellites_gnss[MAX_SATELLITE]; Satellite satellites_bd[MAX_SATELLITE]; Satellite satellites_ga[MAX_SATELLITE]; GnssData NMEA::gnssData; NMEA::NMEA_Type NMEA::nmeaType = NMEA::NtUnknown; bool NMEA::firstGsaIn = false; int NMEA::LSB(char lsb) { if(lsb>='0' && lsb<='9') { return (lsb - '0'); } else if(lsb>='A' && lsb<='F') { return (lsb - 'A' + 0xA); } else { // ASSERT(FALSE); } return 0; } int NMEA::MSB(char msb) { return LSB(msb) * 0x10; } int NMEA::ParamInt(LPCSTR p, int first, int second, int defaultValue) { ASSERT(first <= second - 1); int sign = 1; if(p[first + 1]=='-') { first++; sign = -1; } int value = defaultValue; switch(second - first - 1) { case 0: return defaultValue; break; case 1: value = p[first + 1] - '0'; break; case 2: value = (p[first + 1] - '0') * 10 + (p[first + 2] - '0'); break; case 3: value = (p[first + 1] - '0') * 100 + (p[first + 2] - '0') * 10 + (p[first + 3] - '0'); break; case 4: value = (p[first + 1] - '0') * 1000 + (p[first + 2] - '0') * 100 + (p[first + 3] - '0') * 10 + (p[first + 4] - '0'); break; case 5: value = (p[first + 1] - '0') * 10000 + (p[first + 2] - '0') * 1000 + (p[first + 3] - '0') * 100 + (p[first + 4] - '0') * 10 + (p[first + 5] - '0'); break; case 6: value = (p[first + 1] - '0') * 100000 + (p[first + 2] - '0') * 10000 + (p[first + 3] - '0') * 1000 + (p[first + 4] - '0') * 100 + (p[first + 5] - '0') * 10 + (p[first + 6] - '0'); break; case 7: value = (p[first + 1] - '0') * 1000000 + (p[first + 2] - '0') * 100000 + (p[first + 3] - '0') * 10000 + (p[first + 4] - '0') * 1000 + (p[first + 5] - '0') * 100 + (p[first + 6] - '0') * 10 + (p[first + 7] - '0'); break; case 8: value = (p[first + 1] - '0') * 10000000 + (p[first + 2] - '0') * 1000000 + (p[first + 3] - '0') * 100000 + (p[first + 4] - '0') * 10000 + (p[first + 5] - '0') * 1000 + (p[first + 6] - '0') * 100 + (p[first + 7] - '0') * 10 + (p[first + 8] - '0'); break; default: ASSERT(FALSE); } return value * sign; return 0; } char NMEA::ParamChar(LPCSTR p, int first, int second, char defaultValue) { ASSERT(first == second - 2 || first == second - 1); switch(second - first - 1) { case 0: return defaultValue; case 1: return p[first + 1];; break; default: ASSERT(FALSE); } return 0; } float NMEA::ParamFloat(LPCSTR p, int first, int second, float defaultValue) { if(second - first == 1) { return defaultValue; } int dotPos = 0; for(int i=first+1; i<second-1; ++i) { if(p[i]=='.') { dotPos = i; break; } } ASSERT(dotPos); const float scaleTable[] = { 1.0E-1F, 1.0E-2F, 1.0E-3F, 1.0E-4F, 1.0E-5F, 1.0E-6F, 1.0E-7F}; int a = ParamInt(p, first, dotPos, 0); if(a < 0) { return a - ParamInt(p, dotPos, second, 0) * scaleTable[second-dotPos-2]; } return a + ParamInt(p, dotPos, second, 0) * scaleTable[second-dotPos-2]; } double NMEA::ParamDouble(LPCSTR p, int first, int second, float defaultValue) { if(second - first == 1) { return defaultValue; } int dotPos = 0; for(int i=first+1; i<second-1; ++i) { if(p[i]=='.') { dotPos = i; break; } } const double scaleTable[] = { 1.0E-1, 1.0E-2, 1.0E-3, 1.0E-4, 1.0E-5, 1.0E-6, 1.0E-7}; int a = ParamInt(p, first, dotPos, 0); if(a < 0) { return a - ParamInt(p, dotPos, second, 0) * scaleTable[second-dotPos-2]; } return a + ParamInt(p, dotPos, second, 0) * scaleTable[second-dotPos-2]; } int NMEA::ScanDot(LPCSTR pt, int len, int dot[MaxNmeaParam]) { int dotPos = 0; //Pass the beginning "$GPGSV" and the ending "*nn" for(int i=6; i<len-3; ++i) { if(pt[i] == ',') { dot[dotPos] = i; ++dotPos; } } dot[dotPos] = len - 3; return dotPos; } bool NMEA::GGAProc(GPGGA& rgga, LPCSTR pt, int len) { int dot[MaxNmeaParam] = {0}; int dotPos = ScanDot(pt, len, dot); if(dot[0] != 6 || pt[len - 3] != '*') { return false; } rgga.Hour = ParamInt(pt, dot[0], dot[0]+3, 0); rgga.Min = ParamInt(pt, dot[0]+2, dot[0]+5, 0); if(dot[1] - dot[0] == 7) { rgga.Sec = (float)ParamInt(pt, dot[0]+4, dot[1], 0); } else { rgga.Sec = ParamFloat(pt, dot[0]+4, dot[1], 0); } rgga.Latitude = ParamDouble(pt, dot[1], dot[2], 0.0F); rgga.Latitude_N_S = (U08)ParamChar(pt, dot[2], dot[3], 0); rgga.Longitude = ParamDouble(pt, dot[3], dot[4], 0.0F); rgga.Longitude_E_W = (U08)ParamChar(pt, dot[4], dot[5], 0); rgga.GPSQualityIndicator = (U16)ParamChar(pt, dot[5], dot[6], 0); rgga.NumsOfSatellites = (U08)ParamInt(pt, dot[6], dot[7], 0); rgga.HDOP = ParamFloat(pt, dot[7], dot[8], 0); if(dot[9]) { //Some GGA doesn't have those data. rgga.Altitude = ParamFloat(pt, dot[8], dot[9], 0); rgga.Altitude_meters = (U08)ParamChar(pt, dot[9], dot[10], 0); rgga.GeoidalSeparation = ParamFloat(pt, dot[10], dot[11], 0); rgga.GeoidalSeparation_meters = (U08)ParamChar(pt, dot[11], dot[12], 0); rgga.AgeDGPSData = ParamFloat(pt, dot[12], dot[13], 0); rgga.DiffRefStaID = (U16)ParamInt(pt, dot[13], dot[14], 0); } return true; } bool NMEA::GNSProc(GPGGA& rgga, LPCSTR pt, int len) { int dot[MaxNmeaParam] = {0}; int dotPos = ScanDot(pt, len, dot); if(dot[0] != 6 || pt[len - 3] != '*') { return false; } rgga.Hour = ParamInt(pt, dot[0], dot[0]+3, 0); rgga.Min = ParamInt(pt, dot[0]+2, dot[0]+5, 0); rgga.Sec = ParamFloat(pt, dot[0]+4, dot[1], 0); rgga.Latitude = ParamDouble(pt, dot[1], dot[2], 0.0F); rgga.Latitude_N_S = (U08)ParamChar(pt, dot[2], dot[3], 0); rgga.Longitude = ParamDouble(pt, dot[3], dot[4], 0.0F); rgga.Longitude_E_W = (U08)ParamChar(pt, dot[4], dot[5], 0); rgga.GPSQualityIndicator = (U16)ParamChar(pt, dot[5], dot[5]+2, 0) << 8; rgga.GPSQualityIndicator += (U16)ParamChar(pt, dot[5]+1, dot[5]+3, 0); rgga.NumsOfSatellites = ParamInt(pt, dot[6], dot[7], 0); rgga.HDOP = ParamFloat(pt, dot[7], dot[8], 0); rgga.Altitude = ParamFloat(pt, dot[8], dot[9], 0); rgga.GeoidalSeparation = ParamFloat(pt, dot[9], dot[10], 0); rgga.AgeDGPSData = ParamFloat(pt, dot[10], dot[11], 0); rgga.DiffRefStaID = (U16)ParamInt(pt, dot[11], dot[12], 0); return true; } bool NMEA::GSVProc(GPGSV& rgsv, LPCSTR pt, int len) { int dot[MaxNmeaParam] = {0}; int dotPos = ScanDot(pt, len, dot); if( (dotPos + 1) != 8 && (dotPos + 1) != 12 && (dotPos + 1) != 16 && (dotPos + 1) != 20 ) { return false; } if(dot[0] != 6 || pt[len - 3] != '*') { return 0; } rgsv.NumOfMessage = ParamInt(pt, dot[0], dot[1], 0); rgsv.SequenceNum = ParamInt(pt, dot[1], dot[2], 0); rgsv.NumOfSate = ParamInt(pt, dot[2], dot[3], 0); for(int i=3, groupIdx=0; i<dotPos; i+=4, ++groupIdx) { rgsv.sates[groupIdx].SatelliteID = ParamInt(pt, dot[i], dot[i+1], 0); rgsv.sates[groupIdx].Elevation = ParamInt(pt, dot[i+1], dot[i+2], 0); rgsv.sates[groupIdx].Azimuth = ParamInt(pt, dot[i+2], dot[i+3], 0); rgsv.sates[groupIdx].SNR = ParamInt(pt, dot[i+3], dot[i+4], INVALIDATE_SNR); } return true; } bool NMEA::GSAProc(GPGSA& rgsa, LPCSTR pt, int len) { int dot[MaxNmeaParam] = {0}; int dotPos = ScanDot(pt, len, dot); if(dot[0] != 6 || pt[len - 3] != '*') { return false; } rgsa.Auto_Manu_Mode = ParamChar(pt, dot[0], dot[1], 0); rgsa.Mode = ParamInt(pt, dot[1], dot[2], 0); int idPos = 0; memset(rgsa.SatelliteID, 0, sizeof(rgsa.SatelliteID)); for(int i=2; (i<2+GSA_MAX_SATELLITE) && (i+1<=dotPos); ++i) { rgsa.SatelliteID[idPos] = ParamInt(pt, dot[i], dot[i+1], 0);; ++idPos; } rgsa.PDOP = ParamFloat(pt, dot[14], dot[15], 0.0F); rgsa.HDOP = ParamFloat(pt, dot[15], dot[16], 0.0F); rgsa.VDOP = ParamFloat(pt, dot[16], dot[17], 0.0F); return true; } bool NMEA::RMCProc(GPRMC& rrmc, LPCSTR pt, int len) { int dot[MaxNmeaParam] = {0}; int dotPos = ScanDot(pt, len, dot); if(dot[0] != 6 || pt[len - 3] != '*' || dotPos < 11) { return false; } rrmc.Hour = ParamInt(pt, dot[0], dot[0]+3, 0); rrmc.Min = ParamInt(pt, dot[0]+2, dot[0]+5, 0); if(dot[1] - dot[0] == 7) { //Short time format, no dot rrmc.Sec = (float)ParamInt(pt, dot[0]+4, dot[1], 0); } else { rrmc.Sec = ParamFloat(pt, dot[0]+4, dot[1], 0.0F); } rrmc.Status = (U08)ParamChar(pt, dot[1], dot[2], 0); rrmc.Latitude = ParamDouble(pt, dot[2], dot[3], 0.0F); rrmc.Latitude_N_S = (U08)ParamChar(pt, dot[3], dot[4], 0); rrmc.Longitude = ParamDouble(pt, dot[4], dot[5], 0.0F); rrmc.Longitude_E_W = (U08)ParamChar(pt, dot[5], dot[6], 0); rrmc.SpeedKnots = ParamFloat(pt, dot[6], dot[7], 0.0F); rrmc.TrueCourse = ParamFloat(pt, dot[7], dot[8], 0.0F); rrmc.Day = ParamInt(pt, dot[8], dot[8]+3, 0); rrmc.Month = ParamInt(pt, dot[8]+2, dot[8]+5, 0); rrmc.Year = ParamInt(pt, dot[8]+4, dot[9], 0) + 2000; rrmc.MagVar = ParamFloat(pt, dot[9], dot[10], 0.0F); rrmc.MagVarDir = (U08)ParamChar(pt, dot[10], dot[11], 0); if(dotPos > 11) { //Some customer's NMEA doesn't have this field. rrmc.ModeIndicator = (U08)ParamChar(pt, dot[11], dot[12], 0); } return true; } bool NMEA::ZDAProc(GPZDA& rzda, LPCSTR pt, int len) { int dot[MaxNmeaParam] = {0}; int dotPos = ScanDot(pt, len, dot); if(dot[0] != 6 || pt[len - 3] != '*' || (dotPos+1) != 7) { return false; } rzda.Hour = ParamInt(pt, dot[0], dot[0]+3, 0); rzda.Min = ParamInt(pt, dot[0]+2, dot[0]+5, 0); rzda.Sec = ParamFloat(pt, dot[0]+4, dot[1], 0.0F); rzda.Day = ParamInt(pt, dot[1], dot[2], 0); rzda.Month = ParamInt(pt, dot[2], dot[3], 0); rzda.Year = ParamInt(pt, dot[3], dot[4], 0); rzda.LocalZoneHours = ParamInt(pt, dot[4], dot[5], 0); rzda.LocaZoneMinutes = ParamInt(pt, dot[5], dot[6], 0); return true; } bool NMEA::VTGProc(GPVTG& rvtg, LPCSTR pt, int len) { int dot[MaxNmeaParam] = {0}; int dotPos = ScanDot(pt, len, dot); if(dot[0] != 6 || pt[len - 3] != '*') { return false; } rvtg.TrueCourse = ParamFloat(pt, dot[0], dot[1], 0.0F); rvtg.MagneticCourse = ParamFloat(pt, dot[2], dot[3], 0.0F); rvtg.SpeedKnots = ParamFloat(pt, dot[4], dot[5], 0.0F); rvtg.SpeedKmPerHur = ParamFloat(pt, dot[6], dot[7], 0.0F); rvtg.Mode = (U08)ParamChar(pt, dot[8], dot[9], 0); return true; } bool NMEA::GLLProc(GPGLL& rgll, LPCSTR pt, int len) { int dot[MaxNmeaParam] = {0}; int dotPos = ScanDot(pt, len, dot); if(dot[0] != 6 || pt[len - 3] != '*' || (dotPos+1) != 8) { return false; } rgll.Latitude = ParamDouble(pt, dot[0], dot[1], 0.0F); rgll.Latitude_N_S = (U08)ParamChar(pt, dot[1], dot[2], 0); rgll.Longitude = ParamDouble(pt, dot[2], dot[3], 0.0F); rgll.Longitude_E_W = (U08)ParamChar(pt, dot[3], dot[4], 0); rgll.Hour = ParamInt(pt, dot[4], dot[4]+3, 0); rgll.Min = ParamInt(pt, dot[4]+2, dot[4]+5, 0); rgll.Sec = ParamFloat(pt, dot[4]+4, dot[5], 0.0F); return true; } bool NMEA::VarifyNmeaChecksum(LPCSTR pt, int len) { char checksum = 0; for(int j=1; j<len-3; ++j) { checksum ^= pt[j]; } return checksum == (char)(MSB(*(pt+len-2)) + LSB(*(pt+len-1))); } NMEA::GNSS_System NMEA::GetGNSSSystem(int prn) { if(NMEA_PRN_TYPE==0) { return GetGNSSSystem0(prn); } else if(NMEA_PRN_TYPE==1) { return GetGNSSSystem1(prn); } else if(NMEA_PRN_TYPE==2) { return GetGNSSSystem2(prn); } else if(NMEA_PRN_TYPE==3) { return GetGNSSSystem3(prn); } } NMEA::GNSS_System NMEA::GetGNSSSystem0(int prn) { if(prn==0) { return GsUnknown; } if(prn >= 65 && prn <= 96) { return Glonass; } if( (prn >= 0 && prn <= 64) || (prn >= 193 && prn <= 197)) { return Gps; } if(GPS_183_188 && prn>= 183 && prn <= 188) { return Gps; } return Beidou; } NMEA::GNSS_System NMEA::GetGNSSSystem1(int prn) { if(prn==0) { return GsUnknown; } if(prn >= 1 && prn <= 100) { return Beidou; } else if(prn >= 101 && prn <= 200) { return Gps; } else if(prn >= 201 && prn <= 300) { return Glonass; } else if(prn >= 301 && prn <= 400) { return Galileo; } return Beidou; } NMEA::GNSS_System NMEA::GetGNSSSystem2(int prn) { if(prn==0) { return GsUnknown; } if(prn >= 1 && prn <= 85) { return Gps; } else if(prn >= 86) { return Beidou; } return Beidou; } NMEA::GNSS_System NMEA::GetGNSSSystem3(int prn) { if(prn==0) { return GsUnknown; } if(prn >= 65 && prn <= 96) { return Glonass; } if( (prn >= 0 && prn <= 64) || (prn >= 193 && prn <= 197)) { return Gps; } if(prn>= 183 && prn <= 188) { return Gps; } return Beidou; } int StrHeaderCompare(LPCSTR pt, LPCSTR header, int len) { LPCSTR p1 = pt; LPCSTR p2 = header; int cl = 0; while(*p1 != 0 && *p2 != 0 && cl < len) { if(*p1 > *p2) { return 1; } else if(*p1 < *p2) { return -1; } ++cl; ++p1; ++p2; } if(*p2==0) { return 0; } return -1; } int NMEA::TrimTail(const char* buffer, int offset) { for(int i = offset-1 ; i >0 ; i-- ) { if (buffer[i] == '*' ) { offset = i + 3; break; } } return offset; } NmeaType NMEA::MessageType(LPCSTR pt, int len) { struct NmeaTypeEntry { const char *subNmea; NmeaType type; }; NmeaTypeEntry nmeaTable[] = { { "$GPGGA,", MSG_GGA }, { "$GNGGA,", MSG_GGA }, { "$BDGGA,", MSG_GGA }, { "$GAGGA,", MSG_GGA }, { "$GPGSA,", MSG_GPGSA }, { "$GLGSA,", MSG_GLGSA }, { "$BDGSA,", MSG_BDGSA }, { "$GAGSA,", MSG_GAGSA }, { "$GNGSA,", MSG_GNGSA }, { "$GPGSV,", MSG_GPGSV }, { "$GLGSV,", MSG_GLGSV }, { "$BDGSV,", MSG_BDGSV }, { "$GAGSV,", MSG_GAGSV }, { "$GPRMC,", MSG_RMC }, { "$GNRMC,", MSG_RMC }, { "$BDRMC,", MSG_RMC }, { "$GARMC,", MSG_RMC }, { "$GPGNS,", MSG_GNS }, { "$GNGNS,", MSG_GNS }, { "$GPVTG,", MSG_VTG }, { "$GNVTG,", MSG_VTG }, { "$GPGLL,", MSG_GLL }, { "$GNGLL,", MSG_GLL }, { "$GPZDA,", MSG_ZDA }, { "$GNZDA,", MSG_ZDA }, { "$PSTI,", MSG_STI }, { "$SkyTraq,", MSG_REBOOT }, { "$OLinkStar,", MSG_REBOOT }, { NULL, MSG_Unknown } }; int i = 0; NmeaType returnType = MSG_Unknown; while(nmeaTable[i].type) { if(0==StrHeaderCompare(pt, nmeaTable[i].subNmea, strlen(nmeaTable[i].subNmea))) //if(0==strncmp(pt, nmeaTable[i].subNmea, strlen(nmeaTable[i].subNmea))) { returnType = nmeaTable[i].type; break; } ++i; } if(!VarifyNmeaChecksum(pt, len)) { if(MSG_REBOOT==returnType) return MSG_REBOOT; else return MSG_ERROR; } return returnType; } void NMEA::ShowGPGLLmsg(GPGLL& rGll, LPCSTR pt, int len) { firstGsaIn = false; GLLProc(rGll, pt, len); } void NMEA::ShowGPGSAmsg(GPGSA& gpGsa, LPCSTR pt, int len) { GSAProc(gpGsa, pt, len); } ///* void NMEA::ShowGNGSAmsg(GPGSA& rgpgsa, GPGSA& rglgsa, GPGSA& rbdgsa, GPGSA& rgagsa, LPCSTR pt, int len) { if(firstGsaIn == false) { firstGsaIn = true; for(int i=0; i<MAX_SATELLITE; ++i) { rgpgsa.SatelliteID[i] = 0; rglgsa.SatelliteID[i] = 0; rbdgsa.SatelliteID[i] = 0; rgagsa.SatelliteID[i] = 0; } } GPGSA tmpGsa; GSAProc(tmpGsa, pt, len); rgpgsa.Auto_Manu_Mode = tmpGsa.Auto_Manu_Mode; rglgsa.Auto_Manu_Mode = tmpGsa.Auto_Manu_Mode; rbdgsa.Auto_Manu_Mode = tmpGsa.Auto_Manu_Mode; rgagsa.Auto_Manu_Mode = tmpGsa.Auto_Manu_Mode; rgpgsa.Mode = tmpGsa.Mode; rglgsa.Mode = tmpGsa.Mode; rbdgsa.Mode = tmpGsa.Mode; rgagsa.Mode = tmpGsa.Mode; rgpgsa.PDOP = tmpGsa.PDOP; rglgsa.PDOP = tmpGsa.PDOP; rbdgsa.PDOP = tmpGsa.PDOP; rgagsa.PDOP = tmpGsa.PDOP; rgpgsa.HDOP = tmpGsa.HDOP; rglgsa.HDOP = tmpGsa.HDOP; rbdgsa.HDOP = tmpGsa.HDOP; rgagsa.HDOP = tmpGsa.HDOP; rgpgsa.VDOP = tmpGsa.VDOP; rglgsa.VDOP = tmpGsa.VDOP; rbdgsa.VDOP = tmpGsa.VDOP; rgagsa.VDOP = tmpGsa.VDOP; int gpIndex = 0; int glIndex = 0; int bdIndex = 0; int gaIndex = 0; bool hasGpGsa = false; bool hasGlGsa = false; bool hasBdGsa = false; bool hasGaGsa = false; for(int i=0; i<MAX_SATELLITE; ++i) { GNSS_System g = GetGNSSSystem(tmpGsa.SatelliteID[i]); switch(g) { case Gps: rgpgsa.SatelliteID[gpIndex++] = tmpGsa.SatelliteID[i]; hasGpGsa = true; break; case Glonass: rglgsa.SatelliteID[glIndex++] = tmpGsa.SatelliteID[i]; hasGlGsa = true; break; case Beidou: rbdgsa.SatelliteID[bdIndex++] = tmpGsa.SatelliteID[i]; hasBdGsa = true; break; case Galileo: rgagsa.SatelliteID[gaIndex++] = tmpGsa.SatelliteID[i]; hasGaGsa = true; break; default: break; } } } void NMEA::ShowGLGSAmsg(GPGSA& rglgsa, LPCSTR pt, int len) { GSAProc(rglgsa, pt, len); } void NMEA::ShowBDGSAmsg(GPGSA& rbdgsa, LPCSTR pt, int len) { GSAProc(rbdgsa, pt, len); } void NMEA::ShowGAGSAmsg(GPGSA& rgagsa, LPCSTR pt, int len) { GSAProc(rgagsa, pt, len); } void NMEA::ShowGPGGAmsg(GPGGA& gga, LPCSTR pt, int len) { firstGsaIn = false; GGAProc(gga, pt, len); } void NMEA::ShowGNSmsg(GPGGA& gga, LPCSTR pt, int len) { firstGsaIn = false; GNSProc(gga, pt, len); } void NMEA::ShowGPZDAmsg(GPZDA& zda, LPCSTR pt, int len) { firstGsaIn = false; ZDAProc(zda,pt,len); } void NMEA::ShowGPRMCmsg(GPRMC& rmc, LPCSTR pt, int len) { firstGsaIn = false; RMCProc(rmc,pt,len); } void NMEA::ShowGPVTGmsg(GPVTG& vtg, LPCSTR pt, int len) { firstGsaIn = false; VTGProc(vtg,pt,len); } int gpgsv_counter = 0; int glgsv_counter = 0; int bdgsv_counter = 0; int gagsv_counter = 0; bool gpgsvHasGlonass = false; bool gpgsvHasBeidou = false; bool gpgsvHasGalileo = false; bool gpgsvHasGps = false; void NMEA::ShowGPGSVmsg2(GPGSV& rgpgsv, GPGSV& rglgsv, GPGSV& rbdgsv, GPGSV& rgagsv, LPCSTR pt, int len) { firstGsaIn = false; GPGSV tmpGsv = { 0 }; GSVProc(tmpGsv, pt, len); if(1 == tmpGsv.SequenceNum) { gpgsvHasGlonass = false; gpgsvHasBeidou = false; gpgsvHasGalileo = false; gpgsvHasGps = false; } for(int i=0; i<4; ++i) { Satellite* s = NULL; int idx = 0; //int prn = tmpGsv.sates[i].SatelliteID; GNSS_System g = GetGNSSSystem(tmpGsv.sates[i].SatelliteID); if(GsUnknown==g) { continue; } if(Gps==g && !gpgsvHasGps) { //first Gps prn in gsv message. gpgsvHasGps = true; gpgsv_counter = 0; memset(satellites_gps, 0, sizeof(satellites_gps)); } else if(Glonass==g && !gpgsvHasGlonass) { //first Gps prn in gsv message. gpgsvHasGlonass = true; glgsv_counter = 0; memset(satellites_gnss, 0, sizeof(satellites_gnss)); } else if(Beidou==g && !gpgsvHasBeidou) { //first Gps prn in gsv message. gpgsvHasBeidou = true; bdgsv_counter = 0; memset(satellites_bd, 0, sizeof(satellites_bd)); } else if(Galileo==g && !gpgsvHasGalileo) { //first Gps prn in gsv message. gpgsvHasGalileo = true; gagsv_counter = 0; memset(satellites_ga, 0, sizeof(satellites_ga)); } if(Gps==g) { s = satellites_gps; idx = gpgsv_counter; ++gpgsv_counter; } else if(Glonass==g) { s = satellites_gnss; idx = glgsv_counter; ++glgsv_counter; nmeaType = MixGP; } else if(Beidou==g) { s = satellites_bd; idx = bdgsv_counter; ++bdgsv_counter; nmeaType = MixGP; } else if(Galileo==g) { s = satellites_ga; idx = gagsv_counter; ++gagsv_counter; nmeaType = MixGP; } if(idx >= MAX_SATELLITE) { continue; } s[idx].SatelliteID = tmpGsv.sates[i].SatelliteID; s[idx].Elevation = tmpGsv.sates[i].Elevation; s[idx].Azimuth = tmpGsv.sates[i].Azimuth; s[idx].SNR = tmpGsv.sates[i].SNR; } if(gpgsvHasGlonass) { rglgsv = tmpGsv; } if(gpgsvHasBeidou) { rbdgsv = tmpGsv; } if(gpgsvHasGalileo) { rgagsv = tmpGsv; } if(gpgsvHasGps) { rgpgsv = tmpGsv; } } void NMEA::ShowGLGSVmsg(GPGSV& glgsv, LPCSTR pt, int len) { firstGsaIn = false; GPGSV tmpGsv = { 0 }; GSVProc(tmpGsv, pt, len); glgsv = tmpGsv; if(1 == glgsv.SequenceNum) { glgsv_counter = 0; memset(satellites_gnss, 0, sizeof(satellites_gnss)); } for(int i=0; i<4; ++i) { if(0 == glgsv.sates[i].SatelliteID) { continue; } satellites_gnss[glgsv_counter].SatelliteID = glgsv.sates[i].SatelliteID; satellites_gnss[glgsv_counter].Elevation = glgsv.sates[i].Elevation; satellites_gnss[glgsv_counter].Azimuth = glgsv.sates[i].Azimuth; satellites_gnss[glgsv_counter].SNR = glgsv.sates[i].SNR; glgsv_counter++; if(glgsv_counter >= MAX_SATELLITE) { glgsv_counter=0; } } if(glgsv.NumOfMessage == glgsv.SequenceNum) { glgsv_counter = 0; } } void NMEA::ShowBDGSVmsg(GPGSV& bdgsv, LPCSTR pt, int len) { firstGsaIn = false; GPGSV tmpGsv = { 0 }; GSVProc(tmpGsv, pt, len); bdgsv = tmpGsv; if(1 == bdgsv.SequenceNum) { bdgsv_counter = 0; memset(satellites_bd, 0, sizeof(satellites_bd)); } for(int i=0; i<4; ++i) { if(0 == bdgsv.sates[i].SatelliteID) { continue; } satellites_bd[bdgsv_counter].SatelliteID = bdgsv.sates[i].SatelliteID; satellites_bd[bdgsv_counter].Elevation = bdgsv.sates[i].Elevation; satellites_bd[bdgsv_counter].Azimuth = bdgsv.sates[i].Azimuth; satellites_bd[bdgsv_counter].SNR = bdgsv.sates[i].SNR; bdgsv_counter++; if(bdgsv_counter >= MAX_SATELLITE) { bdgsv_counter = 0; } } if(bdgsv.NumOfMessage == bdgsv.SequenceNum) { bdgsv_counter = 0; } } void NMEA::ShowGAGSVmsg(GPGSV& gagsv, LPCSTR pt, int len) { firstGsaIn = false; GPGSV tmpGsv = { 0 }; GSVProc(tmpGsv, pt, len); gagsv = tmpGsv; if(1 == gagsv.SequenceNum) { gagsv_counter = 0; memset(satellites_ga, 0, sizeof(satellites_ga)); } for(int i=0; i<4; ++i) { if(0 == gagsv.sates[i].SatelliteID) { continue; } satellites_ga[gagsv_counter].SatelliteID = gagsv.sates[i].SatelliteID; satellites_ga[gagsv_counter].Elevation = gagsv.sates[i].Elevation; satellites_ga[gagsv_counter].Azimuth = gagsv.sates[i].Azimuth; satellites_ga[gagsv_counter].SNR = gagsv.sates[i].SNR; gagsv_counter++; if(gagsv_counter >= MAX_SATELLITE) { gagsv_counter=0; } } if(gagsv.NumOfMessage == gagsv.SequenceNum) { gagsv_counter=0; } }
[ "alex.lin@skytraq.com.tw" ]
alex.lin@skytraq.com.tw
991963c1b68d641bd7a1198145bcd3b09ab66df5
3d532e8bce43be073f15c8b46afab3e04211bbf1
/02_아두이노_응용/01_초음파센서/02_응용1/02_hc_sr04_example/02_hc_sr04_example.ino
c745325a5f1fd195d0d61a4b5319fb3699d033f4
[]
no_license
oroca/Asul-E
a31a50224fa9a2317e431eb9bec2e7bcaf00a293
872bcfdc360763a81a92db1f758705082e5732ba
refs/heads/master
2021-09-19T08:05:15.849332
2018-07-25T10:08:16
2018-07-25T10:08:16
113,874,432
2
1
null
null
null
null
UTF-8
C++
false
false
1,898
ino
// 초음파 핀 정의하기 const int trigPin = 13; const int echoPin = 12; // led 핀 정의하기 const int ledPin = 11; long duration; // 시간 변수 int distance; // 거리 변수 //led 켜지는 거리 = 10cm const int ledOnDistance = 10; //led 꺼지는 거리 = 15cm const int ledOffDistance = 15; int ledStatus = LOW; //거리를 이용해서 LED 상태 표시 함수 void ledProc(int distance){ //LED가 꺼져 있는 상태라면 if(ledStatus == LOW){ //거리가 LED ON 거리보다 작거나 같다면 //즉, 거리가 10cm 이하라면 if(distance <= ledOnDistance){ //LED ON ledStatus = HIGH; } }else { //LED가 켜져있는 상태라면 //거리가 LED OFF 거리만큼 크거나 같다면 //즉, 거리가 15cm 이상이라면 if(distance >= ledOffDistance){ //LED OFF ledStatus = LOW; } } //ledStatus 변수값을 이용해서 LED에 적용 digitalWrite(ledPin, ledStatus); } void setup() { //ledPin은 LED를 제어아하는 핀 출력으로 설정. pinMode(ledPin, OUTPUT); //trigPin은 초음파를 내보내는 핀 출력으로 설정. pinMode(trigPin, OUTPUT); //echoPin은 초음파를 읽는 핀 입력으로 설정. pinMode(echoPin, INPUT); //모니터 프로그램 실행 Serial.begin(9600); } void loop() { //초음파 초기화 digitalWrite(trigPin, LOW); delayMicroseconds(2); //초음파 송신 digitalWrite(trigPin, HIGH); delayMicroseconds(10); //10us 후 정지 digitalWrite(trigPin, LOW); //ECHO 핀를 통해 리턴된 시간 읽기 duration = pulseIn(echoPin, HIGH); //시간 데이터를 거리데이터로 환산하는 식 distance = duration*0.034/2; //Cm //거리를 이용해 LED 제어 함수 호출 ledProc(distance); //화면에 출력 Serial.print("Distance : "); Serial.print(distance); Serial.println("CM"); }
[ "chandong83@naver.com" ]
chandong83@naver.com
1e027c952418ef89abc7a24d5bd2b5adeaa8948f
8784b06b4ddb41ce72318953fedb5305043a8a3b
/src/init.cpp
b448a2805acbdf022bba0693ddd4336596f61818
[ "MIT" ]
permissive
goldenarchive/advantage-project
b340c56ec20c9490e76e074eab326518efb849f3
0a5534420c59ae0dbda562b23b161666fc840000
refs/heads/master
2020-03-27T09:40:44.664736
2018-08-27T22:49:37
2018-08-27T22:49:37
146,362,569
0
0
null
null
null
null
UTF-8
C++
false
false
50,351
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "init.h" #include "addrman.h" #include "main.h" #include "chainparams.h" #include "txdb.h" #include "rpcserver.h" #include "net.h" #include "key.h" #include "pubkey.h" #include "util.h" #include "ui_interface.h" #include "checkpoints.h" #include "darksend-relay.h" #include "activemasternode.h" #include "masternode-payments.h" #include "masternode.h" #include "masternodeman.h" #include "masternodeconfig.h" #include "spork.h" #include "smessage.h" #ifdef ENABLE_WALLET #include "db.h" #include "wallet.h" #include "walletdb.h" #endif #include <boost/algorithm/string/predicate.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/bind.hpp> #include <boost/filesystem.hpp> #include <boost/function.hpp> #include <boost/interprocess/sync/file_lock.hpp> #include <boost/thread.hpp> #include <openssl/crypto.h> #ifndef WIN32 #include <signal.h> #endif using namespace std; using namespace boost; #ifdef ENABLE_WALLET CWallet* pwalletMain = NULL; int nWalletBackups = 10; #endif CClientUIInterface uiInterface; bool fConfChange; unsigned int nNodeLifespan; unsigned int nDerivationMethodIndex; unsigned int nMinerSleep; bool fUseFastIndex; bool fOnlyTor = false; ////////////////////////////////////////////////////////////////////////////// // // Shutdown // // // Thread management and startup/shutdown: // // The network-processing threads are all part of a thread group // created by AppInit() or the Qt main() function. // // A clean exit happens when StartShutdown() or the SIGTERM // signal handler sets fRequestShutdown, which triggers // the DetectShutdownThread(), which interrupts the main thread group. // DetectShutdownThread() then exits, which causes AppInit() to // continue (it .joins the shutdown thread). // Shutdown() is then // called to clean up database connections, and stop other // threads that should only be stopped after the main network-processing // threads have exited. // // Note that if running -daemon the parent process returns from AppInit2 // before adding any threads to the threadGroup, so .join_all() returns // immediately and the parent exits from main(). // // Shutdown for Qt is very similar, only it uses a QTimer to detect // fRequestShutdown getting set, and then does the normal Qt // shutdown thing. // volatile bool fRequestShutdown = false; void StartShutdown() { fRequestShutdown = true; } bool ShutdownRequested() { return fRequestShutdown; } static boost::scoped_ptr<ECCVerifyHandle> globalVerifyHandle; void Shutdown() { fRequestShutdown = true; // Needed when we shutdown the wallet LogPrintf("Shutdown : In progress...\n"); static CCriticalSection cs_Shutdown; TRY_LOCK(cs_Shutdown, lockShutdown); if (!lockShutdown) return; RenameThread("Advantage-shutoff"); mempool.AddTransactionsUpdated(1); StopRPCThreads(); SecureMsgShutdown(); #ifdef ENABLE_WALLET ShutdownRPCMining(); if (pwalletMain) bitdb.Flush(false); #endif StopNode(); UnregisterNodeSignals(GetNodeSignals()); DumpMasternodes(); { LOCK(cs_main); #ifdef ENABLE_WALLET if (pwalletMain) pwalletMain->SetBestChain(CBlockLocator(pindexBest)); #endif } #ifdef ENABLE_WALLET if (pwalletMain) bitdb.Flush(true); #endif boost::filesystem::remove(GetPidFile()); UnregisterAllWallets(); #ifdef ENABLE_WALLET delete pwalletMain; pwalletMain = NULL; #endif globalVerifyHandle.reset(); ECC_Stop(); LogPrintf("Shutdown : done\n"); } // // Signal handlers are very limited in what they are allowed to do, so: // void HandleSIGTERM(int) { fRequestShutdown = true; } void HandleSIGHUP(int) { fReopenDebugLog = true; } bool static InitError(const std::string &str) { uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_ERROR); return false; } bool static InitWarning(const std::string &str) { uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_WARNING); return true; } bool static Bind(const CService &addr, bool fError = true) { if (IsLimited(addr)) return false; std::string strError; if (!BindListenPort(addr, strError)) { if (fError) return InitError(strError); return false; } return true; } // Core-specific options shared between UI and daemon std::string HelpMessage() { string strUsage = _("Options:") + "\n"; strUsage += " -? " + _("This help message") + "\n"; strUsage += " -conf=<file> " + _("Specify configuration file (default: Advantage.conf)") + "\n"; strUsage += " -pid=<file> " + _("Specify pid file (default: Advantaged.pid)") + "\n"; strUsage += " -datadir=<dir> " + _("Specify data directory") + "\n"; strUsage += " -wallet=<dir> " + _("Specify wallet file (within data directory)") + "\n"; strUsage += " -dbcache=<n> " + _("Set database cache size in megabytes (default: 10)") + "\n"; strUsage += " -dbwalletcache=<n> " + _("Set wallet database cache size in megabytes (default: 1)") + "\n"; strUsage += " -dblogsize=<n> " + _("Set database disk log size in megabytes (default: 100)") + "\n"; strUsage += " -timeout=<n> " + _("Specify connection timeout in milliseconds (default: 5000)") + "\n"; strUsage += " -proxy=<ip:port> " + _("Connect through SOCKS5 proxy") + "\n"; strUsage += " -tor=<ip:port> " + _("Use proxy to reach tor hidden services (default: same as -proxy)") + "\n"; strUsage += " -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n"; strUsage += " -port=<port> " + _("Listen for connections on <port> (default: 13581)") + "\n"; strUsage += " -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n"; strUsage += " -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n"; strUsage += " -connect=<ip> " + _("Connect only to the specified node(s)") + "\n"; strUsage += " -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n"; strUsage += " -externalip=<ip> " + _("Specify your own public address") + "\n"; strUsage += " -onlynet=<net> " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Tor)") + "\n"; strUsage += " -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n"; strUsage += " -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n"; strUsage += " -bind=<addr> " + _("Bind to given address. Use [host]:port notation for IPv6") + "\n"; strUsage += " -dnsseed " + _("Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)") + "\n"; strUsage += " -forcednsseed " + _("Always query for peer addresses via DNS lookup (default: 0)") + "\n"; strUsage += " -synctime " + _("Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)") + "\n"; strUsage += " -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n"; strUsage += " -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n"; strUsage += " -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n"; strUsage += " -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n"; #ifdef USE_UPNP #if USE_UPNP strUsage += " -upnp " + _("Use UPnP to map the listening port (default: 1 when listening)") + "\n"; #else strUsage += " -upnp " + _("Use UPnP to map the listening port (default: 0)") + "\n"; #endif #endif strUsage += " -paytxfee=<amt> " + _("Fee per KB to add to transactions you send") + "\n"; strUsage += " -mininput=<amt> " + _("When creating transactions, ignore inputs with value less than this (default: 0.01)") + "\n"; if (fHaveGUI) strUsage += " -server " + _("Accept command line and JSON-RPC commands") + "\n"; #if !defined(WIN32) if (fHaveGUI) strUsage += " -daemon " + _("Run in the background as a daemon and accept commands") + "\n"; #endif strUsage += " -testnet " + _("Use the test network") + "\n"; strUsage += " -debug=<category> " + _("Output debugging information (default: 0, supplying <category> is optional)") + "\n"; strUsage += _("If <category> is not supplied, output all debugging information.") + "\n"; strUsage += _("<category> can be:"); strUsage += " addrman, alert, db, lock, rand, rpc, selectcoins, mempool, net,"; // Don't translate these and qt below strUsage += " coinage, coinstake, creation, stakemodifier"; if (fHaveGUI){ strUsage += ", qt.\n"; }else{ strUsage += ".\n"; } strUsage += " -logtimestamps " + _("Prepend debug output with timestamp") + "\n"; strUsage += " -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n"; strUsage += " -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n"; strUsage += " -regtest " + _("Enter regression test mode, which uses a special chain in which blocks can be " "solved instantly. This is intended for regression testing tools and app development.") + "\n"; strUsage += " -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n"; strUsage += " -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n"; strUsage += " -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 19100)") + "\n"; strUsage += " -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n"; if (!fHaveGUI){ strUsage += " -rpcconnect=<ip> " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n"; strUsage += " -rpcwait " + _("Wait for RPC server to start") + "\n"; } strUsage += " -rpcthreads=<n> " + _("Set the number of threads to service RPC calls (default: 4)") + "\n"; strUsage += " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n"; strUsage += " -walletnotify=<cmd> " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n"; strUsage += " -confchange " + _("Require a confirmations for change (default: 0)") + "\n"; strUsage += " -alertnotify=<cmd> " + _("Execute command when a relevant alert is received (%s in cmd is replaced by message)") + "\n"; strUsage += " -upgradewallet " + _("Upgrade wallet to latest format") + "\n"; strUsage += " -createwalletbackups=<n> " + _("Number of automatic wallet backups (default: 10)") + "\n"; strUsage += " -keypool=<n> " + _("Set key pool size to <n> (default: 100) (litemode: 10)") + "\n"; strUsage += " -rescan " + _("Rescan the block chain for missing wallet transactions") + "\n"; strUsage += " -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n"; strUsage += " -checkblocks=<n> " + _("How many blocks to check at startup (default: 500, 0 = all)") + "\n"; strUsage += " -checklevel=<n> " + _("How thorough the block verification is (0-6, default: 1)") + "\n"; strUsage += " -loadblock=<file> " + _("Imports blocks from external blk000?.dat file") + "\n"; strUsage += " -maxorphanblocks=<n> " + strprintf(_("Keep at most <n> unconnectable blocks in memory (default: %u)"), DEFAULT_MAX_ORPHAN_BLOCKS) + "\n"; strUsage += "\n" + _("Block creation options:") + "\n"; strUsage += " -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n"; strUsage += " -blockmaxsize=<n> " + _("Set maximum block size in bytes (default: 250000)") + "\n"; strUsage += " -blockprioritysize=<n> " + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\n"; strUsage += "\n" + _("SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n"; strUsage += " -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n"; strUsage += " -rpcsslcertificatechainfile=<file.cert> " + _("Server certificate file (default: server.cert)") + "\n"; strUsage += " -rpcsslprivatekeyfile=<file.pem> " + _("Server private key (default: server.pem)") + "\n"; strUsage += " -rpcsslciphers=<ciphers> " + _("Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv3:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)") + "\n"; strUsage += " -litemode=<n> " + _("Disable all Darksend and Stealth Messaging related functionality (0-1, default: 0)") + "\n"; strUsage += "\n" + _("Masternode options:") + "\n"; strUsage += " -masternode=<n> " + _("Enable the client to act as a masternode (0-1, default: 0)") + "\n"; strUsage += " -mnconf=<file> " + _("Specify masternode configuration file (default: masternode.conf)") + "\n"; strUsage += " -mnconflock=<n> " + _("Lock masternodes from masternode configuration file (default: 1)") + "\n"; strUsage += " -masternodeprivkey=<n> " + _("Set the masternode private key") + "\n"; strUsage += " -masternodeaddr=<n> " + _("Set external address:port to get to this masternode (example: address:port)") + "\n"; strUsage += " -masternodeminprotocol=<n> " + _("Ignore masternodes less than version (example: 61401; default : 0)") + "\n"; strUsage += "\n" + _("Darksend options:") + "\n"; strUsage += " -enabledarksend=<n> " + _("Enable use of automated darksend for funds stored in this wallet (0-1, default: 0)") + "\n"; strUsage += " -darksendrounds=<n> " + _("Use N separate masternodes to anonymize funds (2-8, default: 2)") + "\n"; strUsage += " -anonymizeAdvantageamount=<n> " + _("Keep N Advantage anonymized (default: 0)") + "\n"; strUsage += " -liquidityprovider=<n> " + _("Provide liquidity to Darksend by infrequently mixing coins on a continual basis (0-100, default: 0, 1=very frequent, high fees, 100=very infrequent, low fees)") + "\n"; strUsage += "\n" + _("InstantX options:") + "\n"; strUsage += " -enableinstantx=<n> " + _("Enable instantx, show confirmations for locked transactions (bool, default: true)") + "\n"; strUsage += " -instantxdepth=<n> " + strprintf(_("Show N confirmations for a successfully locked transaction (0-9999, default: %u)"), nInstantXDepth) + "\n"; strUsage += _("Secure messaging options:") + "\n" + " -nosmsg " + _("Disable secure messaging.") + "\n" + " -debugsmsg " + _("Log extra debug messages.") + "\n" + " -smsgscanchain " + _("Scan the block chain for public key addresses on startup.") + "\n" + strUsage += " -stakethreshold=<n> " + _("This will set the output size of your stakes to never be below this number (default: 100)") + "\n"; return strUsage; } /** Sanity checks * Ensure that Bitcoin is running in a usable environment with all * necessary library support. */ bool InitSanityCheck(void) { if(!ECC_InitSanityCheck()) { InitError("OpenSSL appears to lack support for elliptic curve cryptography. For more " "information, visit https://en.bitcoin.it/wiki/OpenSSL_and_EC_Libraries"); return false; } // TODO: remaining sanity checks, see #4081 return true; } /** Initialize bitcoin. * @pre Parameters should be parsed and config file should be read. */ bool AppInit2(boost::thread_group& threadGroup) { // ********************************************************* Step 1: setup #ifdef _MSC_VER // Turn off Microsoft heap dump noise _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0)); #endif #if _MSC_VER >= 1400 // Disable confusing "helpful" text message on abort, Ctrl-C _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); #endif #ifdef WIN32 // Enable Data Execution Prevention (DEP) // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008 // A failure is non-critical and needs no further attention! #ifndef PROCESS_DEP_ENABLE // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7), // which is not correct. Can be removed, when GCCs winbase.h is fixed! #define PROCESS_DEP_ENABLE 0x00000001 #endif typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD); PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy"); if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE); #endif #ifndef WIN32 umask(077); // Clean shutdown on SIGTERM struct sigaction sa; sa.sa_handler = HandleSIGTERM; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(SIGTERM, &sa, NULL); sigaction(SIGINT, &sa, NULL); // Reopen debug.log on SIGHUP struct sigaction sa_hup; sa_hup.sa_handler = HandleSIGHUP; sigemptyset(&sa_hup.sa_mask); sa_hup.sa_flags = 0; sigaction(SIGHUP, &sa_hup, NULL); #endif // ********************************************************* Step 2: parameter interactions nNodeLifespan = GetArg("-addrlifespan", 7); fUseFastIndex = GetBoolArg("-fastindex", true); nMinerSleep = GetArg("-minersleep", 500); nDerivationMethodIndex = 0; if (!SelectParamsFromCommandLine()) { return InitError("Invalid combination of -testnet and -regtest."); } if (mapArgs.count("-bind")) { // when specifying an explicit binding address, you want to listen on it // even when -connect or -proxy is specified if (SoftSetBoolArg("-listen", true)) LogPrintf("AppInit2 : parameter interaction: -bind set -> setting -listen=1\n"); } // Process masternode config masternodeConfig.read(GetMasternodeConfigFile()); if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) { // when only connecting to trusted nodes, do not seed via DNS, or listen by default if (SoftSetBoolArg("-dnsseed", false)) LogPrintf("AppInit2 : parameter interaction: -connect set -> setting -dnsseed=0\n"); if (SoftSetBoolArg("-listen", false)) LogPrintf("AppInit2 : parameter interaction: -connect set -> setting -listen=0\n"); } if (mapArgs.count("-proxy")) { // to protect privacy, do not listen by default if a default proxy server is specified if (SoftSetBoolArg("-listen", false)) LogPrintf("AppInit2 : parameter interaction: -proxy set -> setting -listen=0\n"); // to protect privacy, do not use UPNP when a proxy is set. The user may still specify -listen=1 // to listen locally, so don't rely on this happening through -listen below. if (SoftSetBoolArg("-upnp", false)) LogPrintf("AppInit2 : parameter interaction: -proxy set -> setting -upnp=0\n"); // to protect privacy, do not discover addresses by default if (SoftSetBoolArg("-discover", false)) LogPrintf("AppInit2 : parameter interaction: -proxy set -> setting -discover=0\n"); } if (!GetBoolArg("-listen", true)) { // do not map ports or try to retrieve public IP when not listening (pointless) if (SoftSetBoolArg("-upnp", false)) LogPrintf("AppInit2 : parameter interaction: -listen=0 -> setting -upnp=0\n"); if (SoftSetBoolArg("-discover", false)) LogPrintf("AppInit2 : parameter interaction: -listen=0 -> setting -discover=0\n"); } if (mapArgs.count("-externalip")) { // if an explicit public IP is specified, do not try to find others if (SoftSetBoolArg("-discover", false)) LogPrintf("AppInit2 : parameter interaction: -externalip set -> setting -discover=0\n"); } if (GetBoolArg("-salvagewallet", false)) { // Rewrite just private keys: rescan to find transactions if (SoftSetBoolArg("-rescan", true)) LogPrintf("AppInit2 : parameter interaction: -salvagewallet=1 -> setting -rescan=1\n"); } // ********************************************************* Step 3: parameter-to-internal-flags fDebug = !mapMultiArgs["-debug"].empty(); // Special-case: if -debug=0/-nodebug is set, turn off debugging messages const vector<string>& categories = mapMultiArgs["-debug"]; if (GetBoolArg("-nodebug", false) || find(categories.begin(), categories.end(), string("0")) != categories.end()) fDebug = false; if(fDebug) { fDebugSmsg = true; } else { fDebugSmsg = GetBoolArg("-debugsmsg", false); } if (fLiteMode) fNoSmsg = true; else fNoSmsg = GetBoolArg("-nosmsg", false); // Check for -debugnet (deprecated) if (GetBoolArg("-debugnet", false)) InitWarning(_("Warning: Deprecated argument -debugnet ignored, use -debug=net")); // Check for -socks - as this is a privacy risk to continue, exit here if (mapArgs.count("-socks")) return InitError(_("Error: Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported.")); if (fDaemon) fServer = true; else fServer = GetBoolArg("-server", false); if (!fHaveGUI) fServer = true; fPrintToConsole = GetBoolArg("-printtoconsole", false); fLogTimestamps = GetBoolArg("-logtimestamps", true); #ifdef ENABLE_WALLET bool fDisableWallet = GetBoolArg("-disablewallet", false); #endif if (mapArgs.count("-timeout")) { int nNewTimeout = GetArg("-timeout", 5000); if (nNewTimeout > 0 && nNewTimeout < 600000) nConnectTimeout = nNewTimeout; } #ifdef ENABLE_WALLET if (mapArgs.count("-paytxfee")) { if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee)) return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"])); if (nTransactionFee > 1000 * COIN) InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.")); } #endif fConfChange = GetBoolArg("-confchange", false); #ifdef ENABLE_WALLET if (mapArgs.count("-mininput")) { if (!ParseMoney(mapArgs["-mininput"], nMinimumInputValue)) return InitError(strprintf(_("Invalid amount for -mininput=<amount>: '%s'"), mapArgs["-mininput"])); } #endif // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log // Initialize elliptic curve code ECC_Start(); globalVerifyHandle.reset(new ECCVerifyHandle()); // Sanity check if (!InitSanityCheck()) return InitError(_("Initialization sanity check failed. Advantage is shutting down.")); std::string strDataDir = GetDataDir().string(); #ifdef ENABLE_WALLET std::string strWalletFileName = GetArg("-wallet", "wallet.dat"); // strWalletFileName must be a plain filename without a directory if (strWalletFileName != boost::filesystem::basename(strWalletFileName) + boost::filesystem::extension(strWalletFileName)) return InitError(strprintf(_("Wallet %s resides outside data directory %s."), strWalletFileName, strDataDir)); #endif // Make sure only a single Bitcoin process is using the data directory. boost::filesystem::path pathLockFile = GetDataDir() / ".lock"; FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist. if (file) fclose(file); static boost::interprocess::file_lock lock(pathLockFile.string().c_str()); if (!lock.try_lock()) return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Advantage is probably already running."), strDataDir)); if (GetBoolArg("-shrinkdebugfile", !fDebug)) ShrinkDebugFile(); LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); LogPrintf("Advantage version %s (%s)\n", FormatFullVersion(), CLIENT_DATE); LogPrintf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION)); if (!fLogTimestamps) LogPrintf("Startup time: %s\n", DateTimeStrFormat("%x %H:%M:%S", GetTime())); LogPrintf("Default data directory %s\n", GetDefaultDataDir().string()); LogPrintf("Used data directory %s\n", strDataDir); std::ostringstream strErrors; if (mapArgs.count("-masternodepaymentskey")) // masternode payments priv key { if (!masternodePayments.SetPrivKey(GetArg("-masternodepaymentskey", ""))) return InitError(_("Unable to sign masternode payment winner, wrong key?")); if (!sporkManager.SetPrivKey(GetArg("-masternodepaymentskey", ""))) return InitError(_("Unable to sign spork message, wrong key?")); } //ignore masternodes below protocol version nMasternodeMinProtocol = GetArg("-masternodeminprotocol", MIN_POOL_PEER_PROTO_VERSION); if (fDaemon) fprintf(stdout, "Advantage server starting\n"); int64_t nStart; // ********************************************************* Step 5: Backup wallet and verify wallet database integrity #ifdef ENABLE_WALLET if (!fDisableWallet) { filesystem::path backupDir = GetDataDir() / "backups"; if (!filesystem::exists(backupDir)) { // Always create backup folder to not confuse the operating system's file browser filesystem::create_directories(backupDir); } nWalletBackups = GetArg("-createwalletbackups", 10); nWalletBackups = std::max(0, std::min(10, nWalletBackups)); if(nWalletBackups > 0) { if (filesystem::exists(backupDir)) { // Create backup of the wallet std::string dateTimeStr = DateTimeStrFormat(".%Y-%m-%d-%H.%M", GetTime()); std::string backupPathStr = backupDir.string(); backupPathStr += "/" + strWalletFileName; std::string sourcePathStr = GetDataDir().string(); sourcePathStr += "/" + strWalletFileName; boost::filesystem::path sourceFile = sourcePathStr; boost::filesystem::path backupFile = backupPathStr + dateTimeStr; sourceFile.make_preferred(); backupFile.make_preferred(); try { boost::filesystem::copy_file(sourceFile, backupFile); LogPrintf("Creating backup of %s -> %s\n", sourceFile, backupFile); } catch(boost::filesystem::filesystem_error &error) { LogPrintf("Failed to create backup %s\n", error.what()); } // Keep only the last 10 backups, including the new one of course typedef std::multimap<std::time_t, boost::filesystem::path> folder_set_t; folder_set_t folder_set; boost::filesystem::directory_iterator end_iter; boost::filesystem::path backupFolder = backupDir.string(); backupFolder.make_preferred(); // Build map of backup files for current(!) wallet sorted by last write time boost::filesystem::path currentFile; for (boost::filesystem::directory_iterator dir_iter(backupFolder); dir_iter != end_iter; ++dir_iter) { // Only check regular files if ( boost::filesystem::is_regular_file(dir_iter->status())) { currentFile = dir_iter->path().filename(); // Only add the backups for the current wallet, e.g. wallet.dat.* if(currentFile.string().find(strWalletFileName) != string::npos) { folder_set.insert(folder_set_t::value_type(boost::filesystem::last_write_time(dir_iter->path()), *dir_iter)); } } } // Loop backward through backup files and keep the N newest ones (1 <= N <= 10) int counter = 0; BOOST_REVERSE_FOREACH(PAIRTYPE(const std::time_t, boost::filesystem::path) file, folder_set) { counter++; if (counter > nWalletBackups) { // More than nWalletBackups backups: delete oldest one(s) try { boost::filesystem::remove(file.second); LogPrintf("Old backup deleted: %s\n", file.second); } catch(boost::filesystem::filesystem_error &error) { LogPrintf("Failed to delete backup %s\n", error.what()); } } } } } uiInterface.InitMessage(_("Verifying database integrity...")); if (!bitdb.Open(GetDataDir())) { // try moving the database env out of the way boost::filesystem::path pathDatabase = GetDataDir() / "database"; boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%d.bak", GetTime()); try { boost::filesystem::rename(pathDatabase, pathDatabaseBak); LogPrintf("Moved old %s to %s. Retrying.\n", pathDatabase.string(), pathDatabaseBak.string()); } catch(boost::filesystem::filesystem_error &error) { // failure is ok (well, not really, but it's not worse than what we started with) } // try again if (!bitdb.Open(GetDataDir())) { // if it still fails, it probably means we can't even create the database env string msg = strprintf(_("Error initializing wallet database environment %s!"), strDataDir); return InitError(msg); } } if (GetBoolArg("-salvagewallet", false)) { // Recover readable keypairs: if (!CWalletDB::Recover(bitdb, strWalletFileName, true)) return false; } if (filesystem::exists(GetDataDir() / strWalletFileName)) { CDBEnv::VerifyResult r = bitdb.Verify(strWalletFileName, CWalletDB::Recover); if (r == CDBEnv::RECOVER_OK) { string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!" " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if" " your balance or transactions are incorrect you should" " restore from a backup."), strDataDir); InitWarning(msg); } if (r == CDBEnv::RECOVER_FAIL) return InitError(_("wallet.dat corrupt, salvage failed")); } } // (!fDisableWallet) #endif // ENABLE_WALLET // ********************************************************* Step 6: network initialization RegisterNodeSignals(GetNodeSignals()); // format user agent, check total size strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, mapMultiArgs.count("-uacomment") ? mapMultiArgs["-uacomment"] : std::vector<string>()); if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) { return InitError(strprintf("Total length of network version string %i exceeds maximum of %i characters. Reduce the number and/or size of uacomments.", strSubVersion.size(), MAX_SUBVERSION_LENGTH)); } if (mapArgs.count("-onlynet")) { std::set<enum Network> nets; BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) { enum Network net = ParseNetwork(snet); if(net == NET_TOR) fOnlyTor = true; if (net == NET_UNROUTABLE) return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet)); nets.insert(net); } for (int n = 0; n < NET_MAX; n++) { enum Network net = (enum Network)n; if (!nets.count(net)) SetLimited(net); } } else { SetReachable(NET_IPV4); SetReachable(NET_IPV6); } CService addrProxy; bool fProxy = false; if (mapArgs.count("-proxy")) { addrProxy = CService(mapArgs["-proxy"], 9050); if (!addrProxy.IsValid()) return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"])); if (!IsLimited(NET_IPV4)) SetProxy(NET_IPV4, addrProxy); if (!IsLimited(NET_IPV6)) SetProxy(NET_IPV6, addrProxy); SetNameProxy(addrProxy); fProxy = true; } // -tor can override normal proxy, -notor disables tor entirely if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) { CService addrOnion; if (!mapArgs.count("-tor")) addrOnion = addrProxy; else addrOnion = CService(mapArgs["-tor"], 9050); if (!addrOnion.IsValid()) return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"])); SetProxy(NET_TOR, addrOnion); SetReachable(NET_TOR); } // see Step 2: parameter interactions for more information about these fNoListen = !GetBoolArg("-listen", true); fDiscover = GetBoolArg("-discover", true); fNameLookup = GetBoolArg("-dns", true); bool fBound = false; if (!fNoListen) { std::string strError; if (mapArgs.count("-bind")) { BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) { CService addrBind; if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false)) return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind)); fBound |= Bind(addrBind); } } else { struct in_addr inaddr_any; inaddr_any.s_addr = INADDR_ANY; if (!IsLimited(NET_IPV6)) fBound |= Bind(CService(in6addr_any, GetListenPort()), false); if (!IsLimited(NET_IPV4)) fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound); } if (!fBound) return InitError(_("Failed to listen on any port. Use -listen=0 if you want this.")); } if (mapArgs.count("-externalip")) { BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) { CService addrLocal(strAddr, GetListenPort(), fNameLookup); if (!addrLocal.IsValid()) return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr)); AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL); } } #ifdef ENABLE_WALLET if (mapArgs.count("-reservebalance")) // ppcoin: reserve balance amount { if (!ParseMoney(mapArgs["-reservebalance"], nReserveBalance)) { InitError(_("Invalid amount for -reservebalance=<amount>")); return false; } } #endif BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"]) AddOneShot(strDest); // ********************************************************* Step 7: load blockchain if (GetBoolArg("-loadblockindextest", false)) { CTxDB txdb("r"); txdb.LoadBlockIndex(); PrintBlockTree(); return false; } uiInterface.InitMessage(_("Loading block index...")); nStart = GetTimeMillis(); if (!LoadBlockIndex()) return InitError(_("Error loading block database")); // as LoadBlockIndex can take several minutes, it's possible the user // requested to kill bitcoin-qt during the last operation. If so, exit. // As the program has not fully started yet, Shutdown() is possibly overkill. if (fRequestShutdown) { LogPrintf("Shutdown requested. Exiting.\n"); return false; } LogPrintf(" block index %15dms\n", GetTimeMillis() - nStart); if (GetBoolArg("-printblockindex", false) || GetBoolArg("-printblocktree", false)) { PrintBlockTree(); return false; } if (mapArgs.count("-printblock")) { string strMatch = mapArgs["-printblock"]; int nFound = 0; for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi) { uint256 hash = (*mi).first; if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0) { CBlockIndex* pindex = (*mi).second; CBlock block; block.ReadFromDisk(pindex); block.BuildMerkleTree(); LogPrintf("%s\n", block.ToString()); nFound++; } } if (nFound == 0) LogPrintf("No blocks matching %s were found\n", strMatch); return false; } // ********************************************************* Step 8: load wallet #ifdef ENABLE_WALLET if (fDisableWallet) { pwalletMain = NULL; LogPrintf("Wallet disabled!\n"); } else { uiInterface.InitMessage(_("Loading wallet...")); nStart = GetTimeMillis(); bool fFirstRun = true; pwalletMain = new CWallet(strWalletFileName); DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun); if (nLoadWalletRet != DB_LOAD_OK) { if (nLoadWalletRet == DB_CORRUPT) strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n"; else if (nLoadWalletRet == DB_NONCRITICAL_ERROR) { string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data" " or address book entries might be missing or incorrect.")); InitWarning(msg); } else if (nLoadWalletRet == DB_TOO_NEW) strErrors << _("Error loading wallet.dat: Wallet requires newer version of Advantage") << "\n"; else if (nLoadWalletRet == DB_NEED_REWRITE) { strErrors << _("Wallet needed to be rewritten: restart Advantage to complete") << "\n"; LogPrintf("%s", strErrors.str()); return InitError(strErrors.str()); } else strErrors << _("Error loading wallet.dat") << "\n"; } if (GetBoolArg("-upgradewallet", fFirstRun)) { int nMaxVersion = GetArg("-upgradewallet", 0); if (nMaxVersion == 0) // the -upgradewallet without argument case { LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST); nMaxVersion = CLIENT_VERSION; pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately } else LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion); if (nMaxVersion < pwalletMain->GetVersion()) strErrors << _("Cannot downgrade wallet") << "\n"; pwalletMain->SetMaxVersion(nMaxVersion); } if (fFirstRun) { // Create new keyUser and set as default key RandAddSeedPerfmon(); CPubKey newDefaultKey; if (pwalletMain->GetKeyFromPool(newDefaultKey)) { pwalletMain->SetDefaultKey(newDefaultKey); if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), "")) strErrors << _("Cannot write default address") << "\n"; } pwalletMain->SetBestChain(CBlockLocator(pindexBest)); } LogPrintf("%s", strErrors.str()); LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart); RegisterWallet(pwalletMain); CBlockIndex *pindexRescan = pindexBest; if (GetBoolArg("-rescan", false)) pindexRescan = pindexGenesisBlock; else { CWalletDB walletdb(strWalletFileName); CBlockLocator locator; if (walletdb.ReadBestBlock(locator)) pindexRescan = locator.GetBlockIndex(); else pindexRescan = pindexGenesisBlock; } if (pindexBest != pindexRescan && pindexBest && pindexRescan && pindexBest->nHeight > pindexRescan->nHeight) { uiInterface.InitMessage(_("Rescanning...")); LogPrintf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight); nStart = GetTimeMillis(); pwalletMain->ScanForWalletTransactions(pindexRescan, true); LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart); pwalletMain->SetBestChain(CBlockLocator(pindexBest)); nWalletDBUpdated++; } } // (!fDisableWallet) #else // ENABLE_WALLET LogPrintf("No wallet compiled in!\n"); #endif // !ENABLE_WALLET // ********************************************************* Step 9: import blocks std::vector<boost::filesystem::path> vImportFiles; if (mapArgs.count("-loadblock")) { BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"]) vImportFiles.push_back(strFile); } threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles)); // ********************************************************* Step 10: load peers uiInterface.InitMessage(_("Loading addresses...")); nStart = GetTimeMillis(); { CAddrDB adb; if (!adb.Read(addrman)) LogPrintf("Invalid or missing peers.dat; recreating\n"); } LogPrintf("Loaded %i addresses from peers.dat %dms\n", addrman.size(), GetTimeMillis() - nStart); // ********************************************************* Step 10.1: startup secure messaging SecureMsgStart(fNoSmsg, GetBoolArg("-smsgscanchain", false)); // ********************************************************* Step 11: start node if (!CheckDiskSpace()) return false; if (!strErrors.str().empty()) return InitError(strErrors.str()); uiInterface.InitMessage(_("Loading masternode cache...")); CMasternodeDB mndb; CMasternodeDB::ReadResult readResult = mndb.Read(mnodeman); if (readResult == CMasternodeDB::FileError) LogPrintf("Missing masternode cache file - mncache.dat, will try to recreate\n"); else if (readResult != CMasternodeDB::Ok) { LogPrintf("Error reading mncache.dat: "); if(readResult == CMasternodeDB::IncorrectFormat) LogPrintf("magic is ok but data has invalid format, will try to recreate\n"); else LogPrintf("file format is unknown or invalid, please fix it manually\n"); } fMasterNode = GetBoolArg("-masternode", false); if(fMasterNode) { LogPrintf("IS DARKSEND MASTER NODE\n"); strMasterNodeAddr = GetArg("-masternodeaddr", ""); LogPrintf(" addr %s\n", strMasterNodeAddr.c_str()); if(!strMasterNodeAddr.empty()){ CService addrTest = CService(strMasterNodeAddr, fNameLookup); if (!addrTest.IsValid()) { return InitError("Invalid -masternodeaddr address: " + strMasterNodeAddr); } } strMasterNodePrivKey = GetArg("-masternodeprivkey", ""); if(!strMasterNodePrivKey.empty()){ std::string errorMessage; CKey key; CPubKey pubkey; if(!darkSendSigner.SetKey(strMasterNodePrivKey, errorMessage, key, pubkey)) { return InitError(_("Invalid masternodeprivkey. Please see documenation.")); } activeMasternode.pubKeyMasternode = pubkey; } else { return InitError(_("You must specify a masternodeprivkey in the configuration. Please see documentation for help.")); } activeMasternode.ManageStatus(); } if(GetBoolArg("-mnconflock", false)) { LogPrintf("Locking Masternodes:\n"); uint256 mnTxHash; BOOST_FOREACH(CMasternodeConfig::CMasternodeEntry mne, masternodeConfig.getEntries()) { LogPrintf(" %s %s\n", mne.getTxHash(), mne.getOutputIndex()); mnTxHash.SetHex(mne.getTxHash()); COutPoint outpoint = COutPoint(mnTxHash, boost::lexical_cast<unsigned int>(mne.getOutputIndex())); pwalletMain->LockCoin(outpoint); } } fEnableDarksend = GetBoolArg("-enabledarksend", false); nDarksendRounds = GetArg("-darksendrounds", 2); if(nDarksendRounds > 16) nDarksendRounds = 16; if(nDarksendRounds < 1) nDarksendRounds = 1; nLiquidityProvider = GetArg("-liquidityprovider", 0); //0-100 if(nLiquidityProvider != 0) { darkSendPool.SetMinBlockSpacing(std::min(nLiquidityProvider,100)*15); fEnableDarksend = true; nDarksendRounds = 99999; } nAnonymizeAdvantageAmount = GetArg("-anonymizeadvantageamount", 0); if(nAnonymizeAdvantageAmount > 999999) nAnonymizeAdvantageAmount = 999999; if(nAnonymizeAdvantageAmount < 2) nAnonymizeAdvantageAmount = 2; fEnableInstantX = GetBoolArg("-enableinstantx", fEnableInstantX); nInstantXDepth = GetArg("-instantxdepth", nInstantXDepth); nInstantXDepth = std::min(std::max(nInstantXDepth, 0), 60); //lite mode disables all Masternode and Darksend related functionality fLiteMode = GetBoolArg("-litemode", false); if(fMasterNode && fLiteMode){ return InitError("You can not start a masternode in litemode"); } LogPrintf("fLiteMode %d\n", fLiteMode); LogPrintf("nInstantXDepth %d\n", nInstantXDepth); LogPrintf("Darksend rounds %d\n", nDarksendRounds); LogPrintf("Anonymize Advantage Amount %d\n", nAnonymizeAdvantageAmount); /* Denominations A note about convertability. Within Darksend pools, each denomination is convertable to another. For example: 1DVY+1000 == (.1DVY+100)*10 10DVY+10000 == (1DVY+1000)*10 */ darkSendDenominations.push_back( (1000 * COIN)+1000000 ); darkSendDenominations.push_back( (100 * COIN)+100000 ); darkSendDenominations.push_back( (10 * COIN)+10000 ); darkSendDenominations.push_back( (1 * COIN)+1000 ); darkSendDenominations.push_back( (.1 * COIN)+100 ); /* Disabled till we need them darkSendDenominations.push_back( (.01 * COIN)+10 ); darkSendDenominations.push_back( (.001 * COIN)+1 ); */ darkSendPool.InitCollateralAddress(); threadGroup.create_thread(boost::bind(&ThreadCheckDarkSendPool)); RandAddSeedPerfmon(); // reindex addresses found in blockchain if(GetBoolArg("-reindexaddr", false)) { uiInterface.InitMessage(_("Rebuilding address index...")); CBlockIndex *pblockAddrIndex = pindexBest; CTxDB txdbAddr("rw"); while(pblockAddrIndex) { uiInterface.InitMessage(strprintf("Rebuilding address index, block %i", pblockAddrIndex->nHeight)); bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true); CBlock pblockAddr; if(pblockAddr.ReadFromDisk(pblockAddrIndex, true)) pblockAddr.RebuildAddressIndex(txdbAddr); pblockAddrIndex = pblockAddrIndex->pprev; } } //// debug print LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size()); LogPrintf("nBestHeight = %d\n", nBestHeight); #ifdef ENABLE_WALLET LogPrintf("setKeyPool.size() = %u\n", pwalletMain ? pwalletMain->setKeyPool.size() : 0); LogPrintf("mapWallet.size() = %u\n", pwalletMain ? pwalletMain->mapWallet.size() : 0); LogPrintf("mapAddressBook.size() = %u\n", pwalletMain ? pwalletMain->mapAddressBook.size() : 0); #endif StartNode(threadGroup); #ifdef ENABLE_WALLET // InitRPCMining is needed here so getwork/getblocktemplate in the GUI debug console works properly. InitRPCMining(); #endif if (fServer) StartRPCThreads(); #ifdef ENABLE_WALLET // Mine proof-of-stake blocks in the background if (!GetBoolArg("-staking", true)) LogPrintf("Staking disabled\n"); else if (pwalletMain) threadGroup.create_thread(boost::bind(&ThreadStakeMiner, pwalletMain)); #endif // ********************************************************* Step 12: finished uiInterface.InitMessage(_("Done loading")); #ifdef ENABLE_WALLET if (pwalletMain) { // Add wallet transactions that aren't already in a block to mapTransactions pwalletMain->ReacceptWalletTransactions(); // Run a thread to flush wallet periodically threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile))); } #endif return !fRequestShutdown; }
[ "you@example.com" ]
you@example.com
00b0c54eb5ce8bc8d94682958d7ea9ee026b8d8f
2da47abec7c8c35356a0902cbe790c3f3558cb6a
/Week4/D - RSA Attack/D - RSA Attack/main.cpp
6b250dbb84f625c7fb864fc70a4b63946f55e286
[ "MIT" ]
permissive
coolspring1293/Algorithm_2015_Later
b0b79cc7f87a1103abf825c590eab518cd936a5a
7be91b0711d430245c52f351f339864853896f90
refs/heads/master
2021-01-10T13:14:41.719886
2016-01-26T07:45:09
2016-01-26T07:45:09
47,117,253
1
0
null
null
null
null
UTF-8
C++
false
false
1,554
cpp
// // main.cpp // D - RSA Attack // // Created by Kieran Will on 10/20/15. // Copyright © 2015 Kieran Will. All rights reserved. // #include <iostream> #include <algorithm> #include <cmath> #define MSIZE 32015 using namespace std; int m[MSIZE], _count = 0; bool flg[MSIZE]; int K, e, n, c; int p, q, x, y; void gcd(int, int, int&, int&); long long sol(int, int, int);//mod int main(int argc, const char * argv[]) { for(int i = 2; i < MSIZE ; ++ i) { if (!flg[i]) { for(int j = i * 2 ; j < MSIZE ; j += i) { flg[j] = 1; } } } for(int i = 2; i < MSIZE ; ++ i) { if (!flg[i]) { m[++ _count] = i; } } //筛法打表 while (cin >> K) { for (int ii = 0; ii < K; ++ ii) { cin >> e >> n >> c; for (int i = 1; i < _count; ++ i) { if (n % m[i] == 0) { p = m[i]; q = (n/m[i]); break; } } int tmp = (p-1) * (q-1); gcd(e, tmp, x, y); if (x < 0) { x += e * tmp;} cout << sol(c, x, n) << "\n"; } } return 0; } /* 3 9 187 129 11 221 56 7 391 204 */ void gcd(int a,int b,int &x, int &y) { if(!b) { x = 1; y = 0; return; } gcd(b, a%b, x, y); int tmp = x; x = y; y = tmp - a/b*y; } long long sol(int a, int b, int mod) { long long tmp; if (b == 0) { return 1 % mod; } if (b == 1) { return a % mod; } tmp = sol(a, b/2, mod); tmp = tmp*tmp % mod; if(b & 1) { tmp = tmp * a % mod; } return tmp; }
[ "coolspring1293@outlook.com" ]
coolspring1293@outlook.com
48963ed84edc0c89b6bf64076a47cb3f586f76b1
b82659cb3c5c065a084424a1b4e237292fbf72f8
/VulkanEngine/VulkanEngine/GameObject.h
51c1d05c7238d51f19a2b4fc7087c9b5e3dd998f
[]
no_license
WestonJMarshall/VulkanEngine
bb1d421b72c472697c5661649cf6e8b59c22a50a
a9086e6dc6355a1dfaa0e00bb5e20d70c446d45a
refs/heads/master
2023-05-08T05:19:48.363003
2021-03-08T21:16:37
2021-03-08T21:16:37
341,319,101
0
0
null
2021-03-11T16:12:07
2021-02-22T19:51:27
C++
UTF-8
C++
false
false
2,514
h
#pragma once #include "pch.h" #include "Transform.h" #include "Mesh.h" #include "PhysicsObject.h" class GameObject { private: std::shared_ptr<Transform> transform; std::shared_ptr<PhysicsObject> physicsObject; std::shared_ptr<Mesh> mesh; int instanceId; std::string name; bool active; public: #pragma region Constructor GameObject(std::shared_ptr<Mesh> mesh, std::shared_ptr<Transform> transform = nullptr, std::shared_ptr<PhysicsObject> physicsObject = nullptr); #pragma endregion #pragma region Accessors /// <summary> /// Returns the transform that is being used by this game object /// </summary> /// <returns>The game object's transform</returns> std::shared_ptr<Transform> GetTransform(); /// <summary> /// Sets the game object's transform to the specified value /// </summary> /// <param name="value">The transform to set to</param> void SetTransform(std::shared_ptr<Transform> value); /// <summary> /// Returns the physics object that is being used by this game object /// </summary> /// <returns>The game object's physics object</returns> std::shared_ptr<PhysicsObject> GetPhysicsObject(); /// <summary> /// Sets the game object's physics object /// </summary> /// <param name="value">The physics object to set to</param> void SetPhysicsObject(std::shared_ptr<PhysicsObject> value); /// <summary> /// Returns the mesh that is being used by this game object /// </summary> /// <returns>The gameobject's mesh</returns> std::shared_ptr<Mesh> GetMesh(); /// <summary> /// Returns the name of this gameobject /// </summary> /// <returns>The gameobject's name</returns> std::string GetName(); /// <summary> /// Sets the name of this gameobject used to display the object and access it in game manager /// </summary> /// <param name="value">The string to set the name to</param> void SetName(std::string value); /// <summary> /// Returns whether this object is active (visible and interactable) /// </summary> /// <returns>True if the object is active</returns> bool GetActive(); #pragma endregion #pragma region Spawning /// <summary> /// Sets the object to active and spawns it into the entity manager /// </summary> virtual void Spawn(); /// <summary> /// Sets the object as inactive and despawns it with the entity manager /// </summary> virtual void Despawn(); #pragma endregion #pragma region Update /// <summary> /// Updates this objects variables once per frame /// </summary> virtual void Update(); #pragma endregion };
[ "jxd8037@g.rit.edu" ]
jxd8037@g.rit.edu
7aa4cec507e5a55399770e0d9a9f71fdee7d2f7f
c8d7a0c0970582d179babaadc514ab27f226db04
/Thirdarty/opengv/src/absolute_pose/modules/gpnp2/reductors.cpp
eb06c1dcb17a666ed1751356f5309e4620edb028
[]
no_license
wf-hahaha/orbslam_hfnet-SuperGlue
47e199fd9ef4bedf7f9f3adb2ce63e7494dca4d9
9d415289705fdacb7dd57da4c9a135b390d10617
refs/heads/master
2022-11-24T04:35:55.636617
2020-07-27T10:54:17
2020-07-27T10:54:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,347
cpp
/****************************************************************************** * Author: Laurent Kneip * * Contact: kneip.laurent@gmail.com * * License: Copyright (c) 2013 Laurent Kneip, ANU. All rights reserved. * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions * * are met: * * * Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * * Neither the name of ANU nor the names of its contributors may be * * used to endorse or promote products derived from this software without * * specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"* * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * * ARE DISCLAIMED. IN NO EVENT SHALL ANU OR THE CONTRIBUTORS BE LIABLE * * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * * SUCH DAMAGE. * ******************************************************************************/ #include <opengv/absolute_pose/modules/gpnp2/modules.hpp> void opengv::absolute_pose::modules::gpnp2::groebnerRow5_00_f(Eigen::Matrix<double, 10, 6> &groebnerMatrix, int targetRow) { double factor = groebnerMatrix(targetRow, 1) / groebnerMatrix(5, 1); groebnerMatrix(targetRow, 1) = 0.0; groebnerMatrix(targetRow, 2) -= factor * groebnerMatrix(5, 2); groebnerMatrix(targetRow, 3) -= factor * groebnerMatrix(5, 3); groebnerMatrix(targetRow, 4) -= factor * groebnerMatrix(5, 4); groebnerMatrix(targetRow, 5) -= factor * groebnerMatrix(5, 5); } void opengv::absolute_pose::modules::gpnp2::groebnerRow6_00_f(Eigen::Matrix<double, 10, 6> &groebnerMatrix, int targetRow) { double factor = groebnerMatrix(targetRow, 2) / groebnerMatrix(6, 2); groebnerMatrix(targetRow, 2) = 0.0; groebnerMatrix(targetRow, 3) -= factor * groebnerMatrix(6, 3); groebnerMatrix(targetRow, 4) -= factor * groebnerMatrix(6, 4); groebnerMatrix(targetRow, 5) -= factor * groebnerMatrix(6, 5); } void opengv::absolute_pose::modules::gpnp2::groebnerRow7_10_f(Eigen::Matrix<double, 10, 6> &groebnerMatrix, int targetRow) { double factor = groebnerMatrix(targetRow, 1) / groebnerMatrix(7, 3); groebnerMatrix(targetRow, 1) = 0.0; groebnerMatrix(targetRow, 2) -= factor * groebnerMatrix(7, 4); groebnerMatrix(targetRow, 4) -= factor * groebnerMatrix(7, 5); } void opengv::absolute_pose::modules::gpnp2::groebnerRow7_00_f(Eigen::Matrix<double, 10, 6> &groebnerMatrix, int targetRow) { double factor = groebnerMatrix(targetRow, 3) / groebnerMatrix(7, 3); groebnerMatrix(targetRow, 3) = 0.0; groebnerMatrix(targetRow, 4) -= factor * groebnerMatrix(7, 4); groebnerMatrix(targetRow, 5) -= factor * groebnerMatrix(7, 5); } void opengv::absolute_pose::modules::gpnp2::groebnerRow8_00_f(Eigen::Matrix<double, 10, 6> &groebnerMatrix, int targetRow) { double factor = groebnerMatrix(targetRow, 4) / groebnerMatrix(8, 4); groebnerMatrix(targetRow, 4) = 0.0; groebnerMatrix(targetRow, 5) -= factor * groebnerMatrix(8, 5); }
[ "yinjiahao505@163.com" ]
yinjiahao505@163.com
b1e581d4cc5c2e55dc6b68d0394aeea94b2d5769
9d2aec0bc8a3187523cc5a66bcae62ef4bbac3f5
/cyan/src/engine/script/chai_engine.hpp
cc4e8cc77e8dc141793d2dd5e58049baf3794b76
[]
no_license
akortman/cyanengine
5732571ef17f6bc722bc844809cf78883f198b85
ab1078576ec95b4b1ab7bce3f932a7c5ce20c326
refs/heads/master
2023-06-29T10:27:18.035108
2021-04-21T08:17:55
2021-04-21T08:17:55
358,542,719
0
0
null
null
null
null
UTF-8
C++
false
false
2,091
hpp
#pragma once #include <utility> #include "chaiscript/chaiscript.hpp" namespace cyan { struct ChaiEngine { /// Construct a ChaiEngine. ChaiEngine() : chai() {} /** * RunReport is returned by functions that execute chai code. * Errors will always result in a log warning, but if you want to ensure that a script ran correctly, * you can check the status of a RunReport. */ struct RunReport { /// `ok` is true unless the script execution encountered an error. bool ok; /// If ok is false, `what` will contain the details of the error. std::string what; /// Create a RunReport. RunReport() : ok(true), what() {} RunReport(bool ok, std::string what) : ok(ok), what(std::move(what)) {} /// Throw an informative cyan::Error if the RunReport contains an error, and otherwise do nothing. void ensure_ok() const; }; /** * Get the underlying chaiscript::Chaiscript object for direct manipulation. Necessary (at this stage) to add * functions, variables, etc. to the engine. (cyanengine provides it's own functions to run chaiscript code, * which offer protection from exceptions crashing the entire app). * @return A chaiscript::Chaiscript script engine object */ chaiscript::ChaiScript& get_chai_object(); /** * Run a string of chai code. * TODO: this is a temporary function. In the future, chai code will be executed by running Script resources. * @param code The code to run. */ ChaiEngine::RunReport run(const std::string& code); /** * Run a file of chai code. * TODO: this is a temporary function. In the future, chai code will be executed by running Script resources. * @param code The path to the file to run. */ ChaiEngine::RunReport run_file(const std::string& path); private: chaiscript::ChaiScript chai; }; }
[ "april.kortman@gmail.com" ]
april.kortman@gmail.com
2e66e7998236bd25d2e42ef3cc21ae78901a24b3
9223819f344d3864d856ab55deb6899e871bb08e
/test/UnitTest/generated/Store_Manager_Ringbuffer_UnitTest_GeneratorTestCode.h
45e25b3440c646db7eeaf70bd0c83930eda4f5b9
[ "MIT" ]
permissive
ConnectedVision/connectedvision
f78d9444025fc942dc6a91efbc15358474e8fa93
210e49205ca50f73584178b6cedb298a74cea798
refs/heads/master
2021-01-15T22:46:25.003207
2019-01-23T18:16:39
2019-01-23T18:16:39
99,911,987
3
1
null
null
null
null
UTF-8
C++
false
false
1,927
h
// auto-generated header by CodeFromTemplate // CodeFromTemplate Version: 0.3 alpha // Store_Manager_Ringbuffer_UnitTest_GeneratorTestCode.h // This file implements the Store_Manager interface for a ringbuffer // It is generated once and will NOT be OVERWRITTEN by CodeFromTemplate. #ifndef Store_Manager_Ringbuffer_UnitTest_GeneratorTestCode_def #define Store_Manager_Ringbuffer_UnitTest_GeneratorTestCode_def #include "stubs/Store_Manager_Ringbuffer_Stub_UnitTest_GeneratorTestCode.h" namespace ConnectedVision { namespace UnitTest { namespace DataHandling { // if you want to extend the auto-generated class, enable the line below //#define Store_Manager_Ringbuffer_UnitTest_GeneratorTestCode_extended #ifdef Store_Manager_Ringbuffer_UnitTest_GeneratorTestCode_extended /** * Store_Manager_Ringbuffer_UnitTest_GeneratorTestCode * * module: * description: test object to check generator */ class Store_Manager_Ringbuffer_UnitTest_GeneratorTestCode : public Store_Manager_Ringbuffer_Stub_UnitTest_GeneratorTestCode { public: /** * constructor */ Store_Manager_Ringbuffer_UnitTest_GeneratorTestCode( const int64_t storeCount, ///< [in] number of stores in manager const int64_t ringbufferSize, ///< [in] number of element slots in ringbuffer const int64_t poolSize ///< [in] total number of available objects (for all ring buffers) ) : Store_Manager_Ringbuffer_Stub_UnitTest_GeneratorTestCode ( storeCount, ringbufferSize, poolSize ) {} /* * virtual destructor */ virtual ~Store_Manager_Ringbuffer_UnitTest_GeneratorTestCode() {} // TODO --> Your declarations and code comes HERE! <-- }; #endif // Store_Manager_Ringbuffer_UnitTest_GeneratorTestCode_extended } // namespace DataHandling } // namespace UnitTest } // namespace ConnectedVision #include "stubs/Store_Manager_Ringbuffer_UnitTest_GeneratorTestCode_Default.h" #endif // Store_Manager_Ringbuffer_UnitTest_GeneratorTestCode_def
[ "30321609+connected-vision@users.noreply.github.com" ]
30321609+connected-vision@users.noreply.github.com
894a6b202dee4932895d5f7d3ae297531956bdb7
63adbec842c5fdb03d415011e9f804c4e502785b
/FinalProjectATM/FinalProjectATM/Atm.cpp
cb9ddcffbab4396c6d145ce49b8b1c2124bbd1ac
[ "Apache-2.0" ]
permissive
Tsuzee/PortfolioProjects
611bacc35accdb6289bc0a03a989bb452dbe833d
f2edc4fb3e3dd534273f88c03eafdedde2c85291
refs/heads/master
2021-01-01T06:11:45.609563
2018-09-26T17:36:25
2018-09-26T17:36:25
42,064,895
0
0
null
null
null
null
UTF-8
C++
false
false
12,891
cpp
//Atm.cpp File for Atm.h //Darren Farr //Final Project ATM //MW 10:00 #include <iostream> #include <iomanip> #include <string> #include <stdio.h> #include <stdlib.h> #include "Atm.h" using namespace std; //constructor Atm::Atm() { pinCount = 0; amount = 0; checkingBalance = 1000; savingBalance = 2000; userChoice[arraySize]; inputAmount[arraySize]; } //display welcome message void Atm::welcomeMessage() { for (int i = 0; i < 40; i++) cout << "*"; cout << "\n\n"; cout << setw(31) <<"Welcome to the C++ ATM\n" << endl; for (int i = 0; i < 40; i++) cout << "*"; cout << "\n\n"; }//end welcome //display initial screen and solicit account card information bool Atm::gatherCardInfo() { string accountNum; cout << "Please enter your 10-digit card number or -1 to exit. "; cin >> accountNum; if(accountNum == "-1") return 0; while(accountNum.length() < 10 || accountNum.length() > 10) { cout << "The card number you entered is invalid. Please try agian. "; cin >> accountNum; }//end error check while return 1; }//end gatherCard //solicit pin info bool Atm::gatherPinInfo() { string accountPin; cout << "Please enter your 4-digit PIN number or -1 to exit. "; cin >> accountPin; if(accountPin == "-1") return 0; //error check while(accountPin.length() < 4 || accountPin.length() > 4) { cout << "The PIN number you entered is invalid. Please try agian. "; cin >> accountPin; pinCount++; if(pinCount > 2) { cout << "I'm sorry. You've tried to many pins. Have a nice day." << endl; return 0; } }//end error check while return 1; }//end gatherPin //display main menu char Atm::menu() { cout << endl; cout << setw(19) << "Main Menu" << endl; cout << endl; cout << "1. Withdrawl" << endl; cout << "2. Deposit" << endl; cout << "3. Transfer Funds" << endl; cout << "4. Balance Inquiry" << endl; cout << "9. Help Text" << endl; cout << "*. Exit" << endl; cin.clear(); //needed due to cin.getline picking up on the last cin.sync(); //endl and causing an error by not waiting for user input cin.getline(userChoice, arraySize); choice = errorCheckMenu(userChoice); return choice; }//end main menu //withdrawl menu void Atm::withdrawMenu() { system("cls"); cout << "\nWhich account would you like to withdraw from?" << endl; cout << "1. Checking\n2. Savings\n3. Main Menu" << endl; cin.getline(userChoice, arraySize); choice = errorCheck(userChoice); if(choice == '1') withdrawChecking(); if(choice == '2') withdrawSaving(); if(choice == '3') { system("cls"); return; } }//end withdrawl menu //withdraw from checking void Atm::withdrawChecking() { //solict user input cout << "\nHow much would you like to withdraw from your checking account? Enter -1 to cancel withdrawl. "; cin >> inputAmount; amount = atof(inputAmount); amount = errorCheckInput(amount); if(amount == -1) { system("cls"); return; } //error check while(amount > checkingBalance) { cout << "I'm sorry, but you do not have that much available to withdraw." << endl; cout << "Please enter a smaller amount or enter -1 to cancel withdrawl. "; cin >> inputAmount; amount = atof(inputAmount); amount = errorCheckInput(amount); if(amount == -1) { system("cls"); return; } }//end while //modify account if(amount >= 0) { amount = roundAmount(amount); checkingBalance = roundAmount(checkingBalance - amount); }//end if //print summary system("cls"); cout << fixed << setprecision(2) << "You withdrew $" << amount << " You're remaining balance is $" << checkingBalance << endl; }//end withdraw checking //withdraw from savings void Atm::withdrawSaving() { //solict user input cout << "\nHow much would you like to withdraw from your savings account? Enter -1 to cancel withdrawl. "; cin >> inputAmount; amount = atof(inputAmount); amount = errorCheckInput(amount); if(amount == -1) { system("cls"); return; } //error check while(amount > savingBalance) { cout << "I'm sorry, but you do not have that much available to withdraw." << endl; cout << "Please enter a smaller amount or enter -1 to cancel withdrawl. "; cin >> inputAmount; amount = atof(inputAmount); amount = errorCheckInput(amount); if(amount == -1) { system("cls"); return; } }//end while //modify account if(amount >= 0) { amount = roundAmount(amount); savingBalance = roundAmount(savingBalance - amount); }//end if //print summary system("cls"); cout << fixed << setprecision(2) << "You withdrew $" << amount << " You're remaining balance is $" << savingBalance << endl; }//end withdraw savings //deposit menu void Atm::depositMenu() { system("cls"); cout << "\nWhich account would you like to deposit into?" << endl; cout << "1. Checking\n2. Savings\n3. Main Menu" << endl; cin.getline(userChoice, arraySize); choice = errorCheck(userChoice); if(choice == '1') depositChecking(); if(choice == '2') depositSaving(); if(choice == '3') { system("cls"); return; } }//end deposit menu //depsoit into checking void Atm::depositChecking() { //solict user input cout << "\nHow much would you like to deposit your checking account? Enter -1 to cancel deposit. "; cin >> inputAmount; amount = atof(inputAmount); amount = errorCheckInput(amount); if(amount == -1) { system("cls"); return; } //error check while(amount <= 0) { cout << "Please enter an amount greater than 0 or enter -1 to cancel deposit. "; cin >> inputAmount; amount = atof(inputAmount); amount = errorCheckInput(amount); if(amount == -1) { system("cls"); return; } }//end while //modify account if(amount >= 0) { amount = roundAmount(amount); checkingBalance = roundAmount(checkingBalance + amount); }//end if //print summary system("cls"); cout << fixed << setprecision(2) << "You deposited $" << amount << " You're current balance is $" << checkingBalance << endl; }//end deposit checking //deposit into savings void Atm::depositSaving() { //solict user input cout << "\nHow much would you like to deposit your savings account? Enter -1 to cancel deposit. "; cin >> inputAmount; amount = atof(inputAmount); amount = errorCheckInput(amount); if(amount == -1) { system("cls"); return; } //error check while(amount <= 0) { cout << "Please enter an amount greater than 0 or enter -1 to cancel deposit. "; cin >> inputAmount; amount = atof(inputAmount); amount = errorCheckInput(amount); if(amount == -1) { system("cls"); return; } }//end while //modify account if(amount >= 0) { amount = roundAmount(amount); savingBalance = roundAmount(savingBalance + amount); }//end if //print summary system("cls"); cout << fixed << setprecision(2) << "You deposited $" << amount << " You're current balance is $" << savingBalance << endl; }//end deposit savings //transfer menu void Atm::transferMenu() { system("cls"); cout << "\nHow would you like to transfer your funds?" << endl; cout << "1. From Checking into Savings\n2. From Savings into Checking\n3. Main Menu" << endl; cin.getline(userChoice, arraySize); choice = errorCheck(userChoice); if(choice == '1') transferToSaving(); if(choice == '2') transferToChecking(); if(choice == '3') { system("cls"); return; } }//end transfer menu //transfer to checking void Atm::transferToChecking() { //solict user input cout << "\nHow much would you like remove from your savings account and deposit into your checking account? Enter -1 to cancel transfer. "; cin >> inputAmount; amount = atof(inputAmount); amount = errorCheckInput(amount); if(amount == -1) { system("cls"); return; } //error check while(amount > savingBalance) { cout << "I'm sorry, but you do not have that much in your savings account." << endl; cout << "Please enter a smaller amount or enter -1 to cancel transfer. "; cin >> inputAmount; amount = atof(inputAmount); amount = errorCheckInput(amount); if(amount == -1) { system("cls"); return; } }//end while //modify accounts if(amount >= 0) { amount = roundAmount(amount); savingBalance = roundAmount(savingBalance - amount); checkingBalance = roundAmount(checkingBalance + amount); }//end if //print summary system("cls"); cout << fixed << setprecision(2) << "You transferred $" << amount << " From your savings account." << endl; cout << "You're current balances are checking $" << checkingBalance << " and savings $" << savingBalance << endl; }//end transfer checking //transfer into savings void Atm::transferToSaving() { //solict input cout << "\nHow much would you like remove from your checking account and deposit into your savings account? Enter -1 to cancel transfer. "; cin >> inputAmount; amount = atof(inputAmount); amount = errorCheckInput(amount); if(amount == -1) { system("cls"); return; } //error check while(amount > checkingBalance) { cout << "I'm sorry, but you do not have that much in your checking account." << endl; cout << "Please enter a smaller amount or enter -1 to cancel transfer. "; cin >> inputAmount; amount = atof(inputAmount); amount = errorCheckInput(amount); if(amount == -1) { system("cls"); return; } }//end while //modify accounts if(amount >= 0) { amount = roundAmount(amount); savingBalance = roundAmount(savingBalance + amount); checkingBalance = roundAmount(checkingBalance - amount); }//end if //print summary system("cls"); cout << fixed << setprecision(2) << "You transferred $" << amount << " From your checking account." << endl; cout << "You're current balances are checking $" << checkingBalance << " and savings $" << savingBalance << endl; }//end transfer savings //balance inquiry void Atm::balanceInquiry() { system("cls"); cout << "\nYour balances are:" << endl; cout << fixed << setprecision(2) << "Checking $" << checkingBalance << endl; cout << "Savings $" << savingBalance << endl; }//end inquiry //help text void Atm::helpText() { system("cls"); cout << setw(33) << "The C++ ATM Help Text\n" << endl; cout << "1. Withdrawl Allows you to choose which account (Checking or Savings) that you would like to withdraw cash from." << endl; cout << "2. Deposit Allows you to choose which account (Checking or Savings) that you would like to deposit cash into." << endl; cout << "3. Transfer Funds Allows you to choose which account (Checking or Savings) that you would like to transfer money from into your other account." << endl; cout << "4. Balance Inquiry Displays the balances of both your Checking and Savings Accounts." << endl; cout << "*. Exit Logs out of your accounts and exits the ATM." <<endl << endl << endl; }//end help //error check menu input char Atm::errorCheck(const char choiceArray[]) { int count = 0; while(choiceArray[0] != '1' && choiceArray[0] != '2' && choiceArray[0] != '3') { cout << "Please choose option 1, 2, or 3 "; cin.getline(userChoice, arraySize); count++; if(count == 15) //returns to main menu after too many wrong inputs return '3'; } return choiceArray[0]; }//end error check //error checks menu choice char Atm::errorCheckMenu(const char choiceArray[]) { int count = 0; while(choiceArray[0] != '1' && choiceArray[0] != '2' && choiceArray[0] != '3' && choiceArray[0] != '4' && choiceArray[0] != '9' && choiceArray[0] != '*') { cout << "Please choose option 1, 2, 3, 4, 9, or *. "; cin.getline(userChoice, arraySize); count++; if(count == 10) //clears screen after too many wrong inputs and pulls up help text { system("cls"); helpText(); } } return choiceArray[0]; }//end error check //round incoming amount to keep balances correct to 2 decimals double Atm::roundAmount(double amount) { amount *=100; amount = int(amount); amount /= 100; return amount; }//end round //confirm user input double Atm::errorCheckInput(double input) { string choice; //check for a negative number if(input < -1 || (input > -1 && input < 0)) { cout << "Please enter an amount greater then 0 or -1 to cancel. "; cin >> inputAmount; amount = atof(inputAmount); return errorCheckInput(amount); }//end if //confirm user input if(input != -1) { cout << "\nYou entered $" << fixed << setprecision(2) << input << " Is this correct? (Y or N)"; cin >> choice; } else { cout << "\nYou entered " << setprecision(0) << input << " Is this correct? (Y or N)"; cin >> choice; }//end else //error check choice while (choice != "Y" && choice != "y" && choice != "N" && choice != "n") { cout << "Please enter Y or N. "; cin >> choice; }//end error check loop if((choice == "Y" || choice == "y") && input >= -1) return input; else { //take in new input cout << "\nPlease enter an amount."; cin >> inputAmount; amount = atof(inputAmount); return errorCheckInput(amount); }//end else }//end function
[ "darrenmichfarr@gmail.com" ]
darrenmichfarr@gmail.com
69e9b74c313be1aaaeca3f8c78cdf02ae2459ddf
76144d1dc83b7deb43c6f62d4b24d620236bef85
/ClientDemo/DlgPosChanFilter.cpp
cccf68b045818f9692f789a1982f504dbe8c09fd
[ "MIT" ]
permissive
qinzhenyi1314/hkvs
e271b76af392e4753f6c8d064066aa0548ec09a2
569c57b03adf5723ccc1df0de6c96858062d23e1
refs/heads/master
2021-06-23T05:32:54.711238
2017-09-03T05:40:55
2017-09-03T05:40:55
null
0
0
null
null
null
null
GB18030
C++
false
false
7,824
cpp
// DlgPosChanFilter.cpp : implementation file // #include "stdafx.h" #include "clientdemo.h" #include "DlgPosChanFilter.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CDlgPosChanFilter dialog CDlgPosChanFilter::CDlgPosChanFilter(CWnd* pParent /*=NULL*/) : CDialog(CDlgPosChanFilter::IDD, pParent) { //{{AFX_DATA_INIT(CDlgPosChanFilter) m_csPosFilterName = _T(""); m_iUserID = -1; m_iDevIndex = -1; //}}AFX_DATA_INIT } void CDlgPosChanFilter::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CDlgPosChanFilter) DDX_Control(pDX, IDC_COMBO_CONNECT_MODE, m_comboConnectMode); DDX_Control(pDX, IDC_COMBO_THEFILTERNUM, m_comboTheFilterNum); DDX_Control(pDX, IDC_COMBO_GROUP, m_comboGroup); DDX_Control(pDX, IDC_COMBO_CHANNEL, m_comboChannel); DDX_Text(pDX, IDC_EDIT_POS_FILTERNAME, m_csPosFilterName); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CDlgPosChanFilter, CDialog) //{{AFX_MSG_MAP(CDlgPosChanFilter) ON_BN_CLICKED(IDC_BTN_REFRESH, OnBtnRefresh) ON_CBN_SELCHANGE(IDC_COMBO_GROUP, OnSelchangeComboGroup) ON_BN_CLICKED(IDC_BTN_SET, OnBtnSet) ON_BN_CLICKED(IDC_BTN_GET, OnBtnGet) ON_CBN_SELCHANGE(IDC_COMBO_CHANNEL, OnSelchangeComboChannel) ON_CBN_EDITCHANGE(IDC_COMBO_THEFILTERNUM, OnEditchangeComboThefilternum) ON_CBN_SELCHANGE(IDC_COMBO_THEFILTERNUM, OnSelchangeComboThefilternum) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CDlgPosChanFilter message handlers BOOL CDlgPosChanFilter::OnInitDialog() { CDialog::OnInitDialog(); m_dwCurselectIndx = 0; // TODO: Add extra initialization here memset(&m_struChanFilterCfg, 0 ,sizeof(m_struChanFilterCfg)); memset(&m_struPosFilterCfg, 0 ,sizeof(m_struPosFilterCfg)); memset(&m_struIPParaCfgV40,0, sizeof(m_struIPParaCfgV40)); GetFilterCfgInfo(0); AddChanInfo(); m_comboChannel.SetCurSel(0); m_comboGroup.SetCurSel(0); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void CDlgPosChanFilter::OnBtnRefresh() { // TODO: Add your control notification handler code here GetFilterCfgInfo(0); } void CDlgPosChanFilter::OnSelchangeComboGroup() { // TODO: Add your control notification handler code here char szLan[128] = {0}; int iIndex = m_comboGroup.GetCurSel(); if (iIndex == LB_ERR) { g_StringLanType(szLan,"请选择组号","Please select Group Number frist!"); AfxMessageBox(szLan); return ; } GetFilterCfgInfo(iIndex); } void CDlgPosChanFilter::GetFilterCfgInfo(UINT dwIndex) { UpdateData(TRUE); DWORD dwReturn = 0; char szLan[128] = {0}; int i = 0; //获取过滤规则信息 memset(&m_struPosFilterCfg, 0, sizeof(m_struPosFilterCfg)); m_struPosFilterCfg.struVerHead.wLength = sizeof(m_struPosFilterCfg); m_struPosFilterCfg.dwMaxGroupNum = dwIndex; if (!NET_DVR_GetDVRConfig(m_iUserID,NET_DVR_GET_POS_FILTER_CFG,dwIndex,&m_struPosFilterCfg,sizeof(m_struPosFilterCfg), &dwReturn)) { g_pMainDlg->AddLog(m_iDevIndex, OPERATION_FAIL_T, "NET_DVR_GET_POS_FILTER_CFG"); return ; } else { g_pMainDlg->AddLog(m_iDevIndex, OPERATION_SUCC_T, "NET_DVR_GET_POS_FILTER_CFG"); } //添加规则信息 m_comboTheFilterNum.ResetContent(); m_csPosFilterName = ""; if (m_struPosFilterCfg.dwMaxRuleNum != 0) { for (i = 0; i < m_struPosFilterCfg.dwMaxRuleNum;i++) { sprintf(szLan,"%d",i+1); m_comboTheFilterNum.AddString(szLan); } } UpdateData(FALSE); } void CDlgPosChanFilter::ShowPosFilterInfo( UINT dwTheFilterNum) { m_csPosFilterName.Format("%s",m_struPosFilterCfg.struFilterCfg[dwTheFilterNum].sPosName); m_comboConnectMode.SetCurSel(m_struPosFilterCfg.struFilterCfg[dwTheFilterNum].dwProtocolType - 1); } void CDlgPosChanFilter::AddChanInfo() { UpdateData(TRUE); DWORD dwReturn = 0; CString strTemp =_T(""); DWORD dwChanNum = 0; int iIndex = 0; DWORD dwIPChanIndex = 0; int i = 0; int iMaxSimulateChannelNO = g_struDeviceInfo[m_iDevIndex].iAnalogChanNum; //***模拟通道***// for (i = 0; i < g_struDeviceInfo[m_iDevIndex].iAnalogChanNum; i++) { dwChanNum = i +1; if ((dwChanNum) > iMaxSimulateChannelNO) { break; } strTemp.Format(ANALOG_C_FORMAT, dwChanNum); m_comboChannel.AddString(strTemp); } //***IP channel***// int iMaxIPChannelNO = g_struDeviceInfo[m_iDevIndex].iIPChanNum; for (i = 0; i < iMaxIPChannelNO; i++) { dwChanNum = i + m_struIPParaCfgV40.dwStartDChan + 1; if ((dwChanNum ) > iMaxIPChannelNO) { break; } strTemp.Format(IP_CAMERA_NAME, dwChanNum); m_comboChannel.AddString(strTemp); } UpdateData(FALSE); } void CDlgPosChanFilter::OnBtnSet() { // TODO: Add your control notification handler code here char szLan[2] = {0}; m_struChanFilterCfg.struVerHead.wLength = sizeof(m_struChanFilterCfg); m_struChanFilterCfg.struVerHead.byVersion = 0; m_struChanFilterCfg.dwFilterID = m_comboTheFilterNum.GetCurSel() + m_comboGroup.GetCurSel() * FILTERRULE_NUM +1; DWORD dwChannelNum = 0; dwChannelNum = m_comboChannel.GetCurSel() +1; if (NET_DVR_SetDVRConfig(m_iUserID, NET_DVR_SET_CHAN_FILTER_CFG, dwChannelNum, &m_struChanFilterCfg, sizeof(m_struChanFilterCfg))) { g_pMainDlg->AddLog(m_iDevIndex, OPERATION_SUCC_T, "NET_DVR_SET_CHAN_FILTER_CFG"); } else { g_pMainDlg->AddLog(m_iDevIndex, OPERATION_FAIL_T, "NET_DVR_SET_CHAN_FILTER_CFG"); return; } } void CDlgPosChanFilter::OnBtnGet() { // TODO: Add your control notification handler code here // UpdateData(TRUE); DWORD dwGroupNum = 0; char szLan[2] = {0}; DWORD dwReturn = 0; // m_comboGroup.GetWindowText(szLan, m_comboChannel.GetCurSel()); // dwGroupNum = atoi(szLan); memset(&m_struChanFilterCfg, 0, sizeof(m_struChanFilterCfg)); m_struChanFilterCfg.struVerHead.wLength = sizeof(m_struChanFilterCfg); m_struChanFilterCfg.struVerHead.byVersion = 0; UINT32 dwChannelNum = 0 ; dwChannelNum = m_comboChannel.GetCurSel() + 1; if (NET_DVR_GetDVRConfig(m_iUserID, NET_DVR_GET_CHAN_FILTER_CFG,dwChannelNum , &m_struChanFilterCfg, sizeof(m_struChanFilterCfg),&dwReturn)) { g_pMainDlg->AddLog(m_iDevIndex, OPERATION_SUCC_T, "NET_DVR_GET_CHAN_FILTER_CFG"); } else { g_pMainDlg->AddLog(m_iDevIndex, OPERATION_FAIL_T, "NET_DVR_GET_CHAN_FILTER_CFG"); return; } //首先计算组号 if (m_struChanFilterCfg.dwFilterID >0) { dwGroupNum = (m_struChanFilterCfg.dwFilterID -1)/FILTERRULE_NUM; } else //表示目前未设置通道与规则的关联信息 { dwGroupNum = 0; } //Get Filter Cfg Info GetFilterCfgInfo(dwGroupNum); //set show Info if (m_struChanFilterCfg.dwFilterID >0) { m_comboTheFilterNum.SetCurSel(m_struChanFilterCfg.dwFilterID - 1 - dwGroupNum * FILTERRULE_NUM); ShowPosFilterInfo(m_struChanFilterCfg.dwFilterID - 1 - dwGroupNum * FILTERRULE_NUM); } UpdateData(FALSE); } void CDlgPosChanFilter::OnSelchangeComboChannel() { // TODO: Add your control notification handler code here UpdateData(FALSE); int iSelectChan = -1; char szLan[128] = {0}; iSelectChan = m_comboChannel.GetCurSel(); sprintf(szLan, "%s", m_struPosFilterCfg.struFilterCfg[iSelectChan].sPosName); UpdateData(FALSE); } void CDlgPosChanFilter::OnEditchangeComboThefilternum() { // TODO: Add your control notification handler code here UpdateData(TRUE); DWORD dwTheFilterNum = m_comboTheFilterNum.GetCurSel(); ShowPosFilterInfo(dwTheFilterNum); UpdateData(FALSE); } void CDlgPosChanFilter::OnSelchangeComboThefilternum() { // TODO: Add your control notification handler code here UpdateData(TRUE); //Get FilterNum DWORD dwSelectFilter = m_comboTheFilterNum.GetCurSel(); ShowPosFilterInfo(dwSelectFilter); UpdateData(FALSE); }
[ "centercao2010@163.com" ]
centercao2010@163.com
4f2e098ceba0d1b711ae82ed61b135a2ed08383c
84f2278ea66c63b620b7118ce8f2745bf4b03198
/1_white_belt/week_4/4_08/1/rational_interface.cpp
c6351b6114eec41eda87d048166b105828f685e4
[]
no_license
VasilyevEvgeny/cpp_development_fundamentals
9f86178f53043c988fc9ac4dc025124aeb944d1c
40b47b9d5500f97ffcf787b2de92414014b51005
refs/heads/master
2023-09-01T00:39:44.338258
2023-08-21T17:48:06
2023-08-21T17:48:06
135,203,787
0
0
null
null
null
null
UTF-8
C++
false
false
2,360
cpp
// https://www.coursera.org/learn/c-plus-plus-white/programming/pZwQ4/klass-rational #include <iostream> using namespace std; class Rational { public: Rational() { numerator = 0; denominator = 1; } Rational(int new_numerator, int new_denominator) { numerator = new_numerator; denominator = new_denominator; NormalizeRational(numerator, denominator); } int Numerator() const { return numerator; } int Denominator() const { return denominator; } int Calculate_gcd (int a, int b) { return b ? Calculate_gcd(b, a % b) : a; } int ChangeSign(int n) { return -n; } void NormalizeRational(int& numerator, int& denominator) { int gcd = Calculate_gcd(abs(numerator), abs(denominator)); numerator /= gcd; denominator /= gcd; if (denominator < 0) { denominator = ChangeSign(denominator); numerator = ChangeSign(numerator); } } private: int numerator; int denominator; }; int main() { /*{ const Rational r(3, 10); if (r.Numerator() != 3 || r.Denominator() != 10) { cout << "Rational(3, 10) != 3/10" << endl; return 1; } } { const Rational r(8, 12); if (r.Numerator() != 2 || r.Denominator() != 3) { cout << "Rational(8, 12) != 2/3" << endl; return 2; } } { const Rational r(-4, 6); if (r.Numerator() != -2 || r.Denominator() != 3) { cout << "Rational(-4, 6) != -2/3" << endl; return 3; } } { const Rational r(4, -6); if (r.Numerator() != -2 || r.Denominator() != 3) { cout << "Rational(4, -6) != -2/3" << endl; return 3; } } { const Rational r(0, 15); if (r.Numerator() != 0 || r.Denominator() != 1) { cout << "Rational(0, 15) != 0/1" << endl; return 4; } } { const Rational defaultConstructed; if (defaultConstructed.Numerator() != 0 || defaultConstructed.Denominator() != 1) { cout << "Rational() != 0/1" << endl; return 5; } }*/ const Rational r(0, -1); cout << r.Numerator() << endl; cout << r.Denominator() << endl; //cout << "OK" << endl; return 0; }
[ "vasilev.evgeniy@physics.msu.ru" ]
vasilev.evgeniy@physics.msu.ru
b5e45117c563eb264fbf24c9284d7a7e30b974ee
3bc5d22175e2e32dcfd007bd94039ea8fa0a4b4e
/index/IndexReader.cpp
41c9f0c0f3df6c918a37dab36c995f97bdb0b550
[]
no_license
longmm/lucene--Distributed-
3d21b1fdc3f03894420880498ecba075e721b1b4
174857cea15dd1312c2a00ae8f53ccb4603f758a
refs/heads/master
2021-01-01T05:35:14.628982
2017-02-08T08:50:00
2017-02-08T08:50:00
14,352,836
0
0
null
null
null
null
UTF-8
C++
false
false
8,889
cpp
#include "index.h" using namespace std; using namespace lucene_index; using namespace lucene_util; lucene_index::IndexReader::IndexReader(wstring dir){ this->dir=dir; this->sis=new SegmentInfos(dir); this->srs=new vector<SegmentReader*>(); init(); init_V_Term(); IndexFileDeleter::incRef(sis); } lucene_index::IndexReader::~IndexReader(){ int ssize=srs->size(); for(int i=0;i<ssize;i++){ SegmentReader* sr=srs->at(i); delete sr; } IndexFileDeleter::decRef(sis); delete srs; delete sis; delete[] isCur; delete[] starts; if(curT!=NULL){ delete curT; } } void lucene_index::IndexReader::init(){ curT=NULL; int ssize=sis->size(); if(ssize==0){ return; } for(int i=0;i<ssize;i++){ SegmentInfo* si=sis->info(i); wstring name=si->name; int docNum=si->docCount; SegmentReader* sr=new SegmentReader(name,dir,docNum); srs->push_back(sr); } starts=new int[ssize]; isCur=new int[ssize]; docCount=0; delCount=0; for(int i=0;i<ssize;i++){ SegmentReader* sr=srs->at(i); starts[i]=docCount; isCur[i]=0; docCount+=sr->docCount; delCount+=sr->delCount; } } int lucene_index::IndexReader::readerIndex(int index){ int rsize=sis->size(); for(int i=0;i<rsize;i++){ if(i+1<rsize&&index>=starts[i]&&index<starts[i+1]){ return i; }else if(i+1==rsize&&index<docCount){ return i; }else{ continue; } } return -1; } Document* lucene_index::IndexReader::getDoc(int index){ if(index>=docCount){ return NULL; } int i=readerIndex(index); if(i==-1){ return NULL; } SegmentReader* sr=srs->at(i); Document* doc=sr->getDoc(index-starts[i]); return doc; } bool lucene_index::IndexReader::isDeleted(int index){ if(index>=docCount){ return false; } int i=readerIndex(index); if(i==-1){ return false; } SegmentReader* sr=srs->at(i); bool isdeleted= sr->isDeleted(index-starts[i]); return isdeleted; } int lucene_index::IndexReader::read(int* docs,int*freqs,int len){ int tmp_size=srs->size(); int total_len=0; for(int i=0;i<tmp_size;i++){ if(isCur[i]==1 || isCur[i]==2){ continue; } SegmentReader* sr=srs->at(i); int tmp_df=sr->termdocs->df; int base=starts[i]; //total_len+=emp_df; if(total_len+tmp_df<len){ sr->termdocs->read(docs+total_len,freqs+total_len,tmp_df); for(int x=total_len;x<total_len+tmp_df;x++){ docs[x]+=base; } total_len+=tmp_df; }else{ sr->termdocs->read(docs+total_len,freqs+total_len,len-total_len); for(int x=total_len;x<len;x++){ docs[x]+=base; total_len=len; } break; } } return total_len; } vector<int>* lucene_index::IndexReader::getPoss(){ return this->poss; } int lucene_index::IndexReader::getFreq(){ return this->freq; } int lucene_index::IndexReader::getDocID(){ return this->docid; } bool lucene_index::IndexReader::nextTerm(){ int tmp_size=srs->size(); for(int i=0;i<tmp_size;i++){ if(isCur[i]==2){ continue; } if(isCur[i]==1){ isCur[i]=0; continue; } SegmentReader* sr=srs->at(i); bool tmp_flag=sr->termdocs->nextTerm(); if(tmp_flag==true){ sr->termposs->nextTerm(); }else{ isCur[i]=2; } } bool res_flag=false; for(int i=0;i<tmp_size;i++){ if(isCur[i]==0){ res_flag=true; } } if(res_flag==true){ selectTerm(); Comput_df(); pos=0; return true; }else{ return false; } } bool lucene_index::IndexReader::skipTo(int target){ if(target<0||target>docCount){ return false; } int posi=readerIndex(target); if(posi==-1){ return false; } if(isCur[posi]==1 || isCur[posi]==2){ return false; } SegmentReader* sr=srs->at(posi); bool flag=sr->termdocs->skipTo(target-starts[posi]); if(flag==true){ pos=posi; sr->termposs->skipTo(target-starts[posi]); docid=sr->termdocs->doc+starts[pos]; freq=sr->termdocs->freq; poss=sr->termposs->poss; return true; }else{ return false; } } bool lucene_index::IndexReader::next(){ int tmp_size=srs->size(); /* if(pos>=tmp_size){ return false; } SegmentReader* sr=srs->at(pos); bool flag=sr->termdocs->next(); if(flag==true){ sr->termposs->next(); docid=sr->termdocs->doc+starts[pos]; freq=sr->termdocs->freq; poss=sr->termposs->poss; return true; } */ //pos++; while(pos<tmp_size){ if(isCur[pos]==0){ SegmentReader* tmp_sr=srs->at(pos); bool tmp_flag=tmp_sr->termdocs->next(); if(tmp_flag==true){ tmp_sr->termposs->next(); docid=tmp_sr->termdocs->doc+starts[pos]; freq=tmp_sr->termdocs->freq; poss=tmp_sr->termposs->poss; return true; }else{ pos++; } }else{ pos++; } } return false; } bool lucene_index::IndexReader::seek(Term* t){ if(t==NULL){ return false; } bool flag=false; int tmp_size=srs->size(); for(int i=0;i<tmp_size;i++){ SegmentReader* sr=srs->at(i); bool tmp_flag=sr->termdocs->seek(t); sr->termposs->seek(t); if(tmp_flag==false){ TermInfo* ti=sr->termdocs->cti; wstring fname=ti->fname; wstring fvalue=ti->fvalue; Term tmp_t(fname,fvalue); if(tmp_t<(*t)){ isCur[i]=2; }else{ isCur[i]=1; } }else{ isCur[i]=0; flag=true; if(curT==NULL){ curT=new Term(*t); }else{ delete curT; curT=new Term(*t); } } }//for if(flag==false){ if(curT!=NULL){ delete curT; } curT=NULL; return false; } if(flag==true){ Comput_df(); pos=0; return true; } } void lucene_index::IndexReader::Comput_df(){ this->df=0; this->del_df=0; int tmp_size=srs->size(); for(int i=0;i<tmp_size;i++){ if(isCur[i]==0){ SegmentReader* sr=srs->at(i); this->df+=sr->termdocs->df; this->del_df+=sr->termdocs->del_df; } } } bool lucene_index::IndexReader::init_V_Term(){ int tmp_size=srs->size(); bool flag=false; for(int i=0;i<tmp_size;i++){ SegmentReader* sr=srs->at(i); bool tmp_flag=sr->init_V_Term(); if(tmp_flag==false){ isCur[i]=2; }else{ isCur[i]=0; flag=true; } } if(flag==false){ return false; }else{ selectTerm(); Comput_df(); pos=0; return true; } } void lucene_index::IndexReader::selectTerm(){ TermInfo* min_ti=NULL; int tmp_size=srs->size(); for(int i=0;i<tmp_size;i++){ if(isCur[i]==1|| isCur[i]==2){ continue; } SegmentReader* sr=srs->at(i); TermInfo* tmp_ti=sr->termdocs->cti; if(min_ti==NULL){ min_ti=sr->termdocs->cti; }else{ if((*tmp_ti)<(*min_ti)){ min_ti=tmp_ti; } } } if(min_ti==NULL){ return ; } wstring tmp_fname=min_ti->fname; wstring tmp_value=min_ti->fvalue; if(curT!=NULL){ delete curT; }else{ curT=new Term(tmp_fname,tmp_value); } for(int i=0;i<tmp_size;i++){ if(isCur[i]==1|| isCur[i]==2){ continue; } SegmentReader* sr=srs->at(i); TermInfo* tmp_ti=sr->termdocs->cti; if((*tmp_ti)==(*min_ti)){ continue; }else{ isCur[i]=1; } } } void lucene_index::IndexReader::resetDocPos(){ int tmp_size=srs->size(); for(int i=0;i<tmp_size;i++){ SegmentReader* sr=srs->at(i); sr->resetDocPos(); } } MTermDocs* lucene_index::IndexReader::getMTDocs(){ MTermDocs* mtds=new MTermDocs(srs); return mtds; }
[ "longmm1988@sina.com" ]
longmm1988@sina.com
04637fce2ccf96cee904e4f4d5ce3f17c47bbbf6
7c3176c3e22f92417ac007ce2bee96ef6e860227
/SMS_Broadcast/SpeedSms/SerialCommunication.cpp
379b4e9a362015305402bbed4561188ecb7de59f
[]
no_license
pnsb87/SMS_WAP_SENDER
38c3f2ad614ab44c7f481e8ccff7bef9e4fe47ff
4ca630c6be7f3c994177b52641efce6e8c024c39
refs/heads/master
2021-01-17T09:10:35.982961
2017-03-05T15:46:41
2017-03-05T15:46:41
83,980,453
1
0
null
null
null
null
UTF-8
C++
false
false
4,379
cpp
#include "StdAfx.h" #include "SerialCommunication.h" #include "UsbInterface.h" #include <string> using namespace std; SerialCommunication::SerialCommunication() { m_serialParam.hCom = INVALID_HANDLE_VALUE; } string SerialCommunication::GetNumber() { string sPhoneNumber; DWORD nWriten = 0; DWORD nRead = 0; char buffer[MAX_BUFFER_SIZE] = {0}; string sRequest = "AT+CNUM=?\r"; //string sReply; this->Write(sRequest.c_str(), sRequest.length()); //WriteFile(m_serialParam.hCom,(LPCVOID)sRequest.c_str(), sRequest.length(), &nWriten, NULL); //ReadFile(m_serialParam.hCom, (LPVOID)sReply.c_str(), 100, &nRead, NULL); this->Read(buffer, MAX_BUFFER_SIZE); std::string sReply(buffer); sReply.erase(0, 8); sReply.erase(sReply.find("\""), sReply.length()-1); sPhoneNumber = sReply; return sPhoneNumber; } int SerialCommunication::Open(CString name) { m_serialParam.szName = name; m_serialParam.hCom = CreateFile(name, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if(m_serialParam.hCom == INVALID_HANDLE_VALUE) return -1; BOOL isReady = SetupComm(m_serialParam.hCom, MAX_BUFFER_SIZE, MAX_BUFFER_SIZE); if(!isReady) return -1; DCB m_dcb; isReady = GetCommState(m_serialParam.hCom, &m_dcb); m_dcb.BaudRate = 9600; m_dcb.ByteSize = 8; m_dcb.Parity = NOPARITY; m_dcb.StopBits = ONE5STOPBITS; m_dcb.fParity = 0; m_dcb.fAbortOnError = 0; isReady = SetCommState(m_serialParam.hCom, &m_dcb); if(!isReady) return -1; isReady = GetCommTimeouts (m_serialParam.hCom, &m_serialParam.m_CommTimeouts); if(!isReady) return -1; m_serialParam.m_CommTimeouts.ReadIntervalTimeout = 50; m_serialParam.m_CommTimeouts.ReadTotalTimeoutConstant = 50; m_serialParam.m_CommTimeouts.ReadTotalTimeoutMultiplier = 10; m_serialParam.m_CommTimeouts.WriteTotalTimeoutConstant = 50; m_serialParam.m_CommTimeouts.WriteTotalTimeoutMultiplier = 10; //m_serialParam.m_CommTimeouts.ReadIntervalTimeout = MAXDWORD; //m_serialParam.m_CommTimeouts.ReadTotalTimeoutConstant = 0; //m_serialParam.m_CommTimeouts.ReadTotalTimeoutMultiplier = 0; //m_serialParam.m_CommTimeouts.WriteTotalTimeoutConstant = 1000; //m_serialParam.m_CommTimeouts.WriteTotalTimeoutMultiplier = 10; isReady = SetCommTimeouts (m_serialParam.hCom, &m_serialParam.m_CommTimeouts); if(!isReady) return -1; if(WriteWaitReply("AT\r") != 0) return -1; return 0; } int SerialCommunication::Close() { if(m_serialParam.hCom != INVALID_HANDLE_VALUE) { CloseHandle(m_serialParam.hCom); m_serialParam.hCom = INVALID_HANDLE_VALUE; } return 0; } int SerialCommunication::Write(const char* data, int len) { DWORD nWriten = 0; WriteFile(m_serialParam.hCom,(LPCVOID)data, len, &nWriten, NULL); return nWriten; } int SerialCommunication::WriteWaitReply(const char *data) { char szReply[MAX_BUFFER_SIZE] = {0}; memset(szReply, 0, sizeof(szReply)); int ret = 0; string szSend(data); ret = Write(szSend.c_str(), szSend.length()); ret = Read(szReply, MAX_BUFFER_SIZE); if(strstr(szReply, "CMGW:") != NULL) { int nMsgPos = atoi(strstr(szReply, ":") + 2); return nMsgPos; } else if(strstr(szReply, "RSSI") != NULL) return -1; else if((strstr(szReply, "OK") !=NULL) || (strstr(szReply, "\r\n>") !=NULL)) return 0; else return -2; return 0; } int SerialCommunication::Read(char* dataout, int dataout_len) { DWORD nRead; ReadFile(m_serialParam.hCom, (LPVOID)dataout, dataout_len, &nRead, NULL); return nRead; } int SerialCommunication::SendSms(const char *szText, const char *szNumber) { char szSend[50]; memset(szSend, 0, sizeof(szSend)); //gui dau so truoc sprintf(szSend, "AT+CMGS=\"%s\"", szNumber); if(WriteWaitReply(szSend) != 0) return -1; //gui noi dung sprintf(szSend, "%s%c", szText, (char)26); if(WriteWaitReply(szSend) != 0) return -1; return 0; } int SerialCommunication::SendWap(const char *szText, const char *szUrl, const char *szNumber) { return 0; } int SerialCommunication::ChangeSmsMode() { if(WriteWaitReply("AT+CMGF=1") != 0) return -1; return 0; } int SerialCommunication::ChangeWapMode() { if(WriteWaitReply("AT+CMGF=0") != 0) return -1; return 0; } SerialCommunication::~SerialCommunication(void) { }
[ "noreply@github.com" ]
pnsb87.noreply@github.com
3b3348cb055f01e45d0a4d33ba20851dc2beb836
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5753053697277952_1/C++/wfe2016/gcj3a.cpp
25a0289a96b9a97ba99e86a3680e35050d08971f
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
1,297
cpp
#include <iostream> using namespace std; int main() { int T; cin >> T; for (int i = 0; i < T; i++) { int N; cin >> N; int sen[N]; int sum = 0; for (int j = 0; j < N; j++) { cin >> sen[j]; sum += sen[j]; } int evac = 0; cout << "Case #" << i+1 << ": "; while (evac < sum) { int top = -1; for (int j = 0; j < N; j++) { if (sen[j] > top) { top = sen[j]; } } int counttop = 0; for (int j = 0; j < N; j++) { if (sen[j] == top) { counttop += 1; } } int party1; int party2; char party1c; char party2c; if (counttop != 2) { for (int j = 0; j < N; j++) { if (sen[j] == top) { counttop += 1; party1 = j; } } party1c = party1 + 65; cout << party1c << " "; evac += 1; sen[party1] -= 1; } else { for (int j = 0; j < N; j++) { if (sen[j] == top) { counttop += 1; party1 = j; } } for (int j = N-1; j >= 0; j--) { if (sen[j] == top) { counttop += 1; party2 = j; } } party1c = party1 + 65; party2c = party2 + 65; cout << party1c << party2c << " "; evac += 2; sen[party1] -= 1; sen[party2] -= 1; } } cout << endl; } }
[ "alexandra1.back@gmail.com" ]
alexandra1.back@gmail.com
bea7479351a0bf9acf22f343adcf877fe406cf8f
af3d55c6d71cc5670eecd0d79045f0a01a4badf2
/Plugins/CaptionMod/SourceSDK/tier1/strtools.cpp
bb4593aa4bd1f38fda57ac71c20e0b7d8ce897c4
[ "MIT" ]
permissive
fengjixuchui/MetaHookSv
2a1c43385fd75d88a4eb654042cdd223d39aba8a
a07d0629338100342dc4f8f1bb2b830455d214b0
refs/heads/main
2023-07-20T06:54:00.174206
2021-09-04T05:58:16
2021-09-04T05:58:16
331,490,232
1
1
MIT
2021-09-04T05:58:17
2021-01-21T02:21:08
C++
UTF-8
C++
false
false
43,353
cpp
//===== Copyright ?1996-2005, Valve Corporation, All rights reserved. ======// // // Purpose: String Tools // //===========================================================================// // These are redefined in the project settings to prevent anyone from using them. // We in this module are of a higher caste and thus are privileged in their use. #ifdef strncpy #undef strncpy #endif #ifdef _snprintf #undef _snprintf #endif #if defined( sprintf ) #undef sprintf #endif #if defined( vsprintf ) #undef vsprintf #endif #ifdef _vsnprintf #ifdef _WIN32 #undef _vsnprintf #endif #endif #ifdef vsnprintf #ifndef _WIN32 #undef vsnprintf #endif #endif #if defined( strcat ) #undef strcat #endif #ifdef strncat #undef strncat #endif // NOTE: I have to include stdio + stdarg first so vsnprintf gets compiled in #include <stdio.h> #include <stdarg.h> #ifdef _LINUX #include <ctype.h> #include <unistd.h> #include <stdlib.h> #define _getcwd getcwd #elif _WIN32 #include <direct.h> #if !defined( _X360 ) #define WIN32_LEAN_AND_MEAN #include <windows.h> #endif #endif #ifdef _WIN32 #ifndef CP_UTF8 #define CP_UTF8 65001 #endif #endif #include <tier0/dbg.h> #include "strtools.h" #include <string.h> #include <stdlib.h> #include <tier0/basetypes.h> #include "utldict.h" #if defined( _X360 ) #include "xbox/xbox_win32stubs.h" #endif #include <tier0/memdbgon.h> void _V_memset (const char* file, int line, void *dest, int fill, int count) { Assert( count >= 0 ); AssertValidWritePtr( dest, count ); memset(dest,fill,count); } void _V_memcpy (const char* file, int line, void *dest, const void *src, int count) { Assert( count >= 0 ); AssertValidReadPtr( src, count ); AssertValidWritePtr( dest, count ); memcpy( dest, src, count ); } void _V_memmove(const char* file, int line, void *dest, const void *src, int count) { Assert( count >= 0 ); AssertValidReadPtr( src, count ); AssertValidWritePtr( dest, count ); memmove( dest, src, count ); } int _V_memcmp (const char* file, int line, const void *m1, const void *m2, int count) { Assert( count >= 0 ); AssertValidReadPtr( m1, count ); AssertValidReadPtr( m2, count ); return memcmp( m1, m2, count ); } int _V_strlen(const char* file, int line, const char *str) { AssertValidStringPtr(str); return strlen( str ); } void _V_strcpy (const char* file, int line, char *dest, const char *src) { AssertValidWritePtr(dest); AssertValidStringPtr(src); strcpy( dest, src ); } int _V_wcslen(const char* file, int line, const wchar_t *pwch) { return wcslen( pwch ); } char *_V_strrchr(const char* file, int line, const char *s, char c) { AssertValidStringPtr( s ); int len = V_strlen(s); s += len; while (len--) if (*--s == c) return (char *)s; return 0; } int _V_strcmp (const char* file, int line, const char *s1, const char *s2) { AssertValidStringPtr( s1 ); AssertValidStringPtr( s2 ); return strcmp( s1, s2 ); } int _V_wcscmp (const char* file, int line, const wchar_t *s1, const wchar_t *s2) { while (1) { if (*s1 != *s2) return -1; // strings not equal if (!*s1) return 0; // strings are equal s1++; s2++; } return -1; } int _V_stricmp(const char* file, int line, const char *s1, const char *s2 ) { AssertValidStringPtr( s1 ); AssertValidStringPtr( s2 ); return stricmp( s1, s2 ); } char *_V_strstr(const char* file, int line, const char *s1, const char *search ) { AssertValidStringPtr( s1 ); AssertValidStringPtr( search ); #if defined( _X360 ) return (char *)strstr( (char *)s1, search ); #else return (char *)strstr( s1, search ); #endif } char *_V_strupr (const char* file, int line, char *start) { AssertValidStringPtr( start ); return strupr( start ); } char *_V_strlower (const char* file, int line, char *start) { AssertValidStringPtr( start ); return strlwr(start); } int V_strncmp (const char *s1, const char *s2, int count) { Assert( count >= 0 ); AssertValidStringPtr( s1, count ); AssertValidStringPtr( s2, count ); while ( count-- > 0 ) { if ( *s1 != *s2 ) return *s1 < *s2 ? -1 : 1; // string different if ( *s1 == '\0' ) return 0; // null terminator hit - strings the same s1++; s2++; } return 0; // count characters compared the same } char *V_strnlwr(char *s, size_t count) { Assert( count >= 0 ); AssertValidStringPtr( s, count ); char* pRet = s; if ( !s ) return s; while ( --count >= 0 ) { if ( !*s ) break; *s = tolower( *s ); ++s; } if ( count > 0 ) { s[count-1] = 0; } return pRet; } int V_strncasecmp (const char *s1, const char *s2, int n) { Assert( n >= 0 ); AssertValidStringPtr( s1 ); AssertValidStringPtr( s2 ); while ( n-- > 0 ) { int c1 = *s1++; int c2 = *s2++; if (c1 != c2) { if (c1 >= 'a' && c1 <= 'z') c1 -= ('a' - 'A'); if (c2 >= 'a' && c2 <= 'z') c2 -= ('a' - 'A'); if (c1 != c2) return c1 < c2 ? -1 : 1; } if ( c1 == '\0' ) return 0; // null terminator hit - strings the same } return 0; // n characters compared the same } int V_strcasecmp( const char *s1, const char *s2 ) { AssertValidStringPtr( s1 ); AssertValidStringPtr( s2 ); return stricmp( s1, s2 ); } int V_strnicmp (const char *s1, const char *s2, int n) { Assert( n >= 0 ); AssertValidStringPtr(s1); AssertValidStringPtr(s2); return V_strncasecmp( s1, s2, n ); } const char *StringAfterPrefix( const char *str, const char *prefix ) { AssertValidStringPtr( str ); AssertValidStringPtr( prefix ); do { if ( !*prefix ) return str; } while ( tolower( *str++ ) == tolower( *prefix++ ) ); return NULL; } const char *StringAfterPrefixCaseSensitive( const char *str, const char *prefix ) { AssertValidStringPtr( str ); AssertValidStringPtr( prefix ); do { if ( !*prefix ) return str; } while ( *str++ == *prefix++ ); return NULL; } int V_atoi (const char *str) { AssertValidStringPtr( str ); int val; int sign; int c; Assert( str ); if (*str == '-') { sign = -1; str++; } else sign = 1; val = 0; // // check for hex // if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X') ) { str += 2; while (1) { c = *str++; if (c >= '0' && c <= '9') val = (val<<4) + c - '0'; else if (c >= 'a' && c <= 'f') val = (val<<4) + c - 'a' + 10; else if (c >= 'A' && c <= 'F') val = (val<<4) + c - 'A' + 10; else return val*sign; } } // // check for character // if (str[0] == '\'') { return sign * str[1]; } // // assume decimal // while (1) { c = *str++; if (c <'0' || c > '9') return val*sign; val = val*10 + c - '0'; } return 0; } float V_atof (const char *str) { AssertValidStringPtr( str ); double val; int sign; int c; int decimal, total; if (*str == '-') { sign = -1; str++; } else sign = 1; val = 0; // // check for hex // if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X') ) { str += 2; while (1) { c = *str++; if (c >= '0' && c <= '9') val = (val*16) + c - '0'; else if (c >= 'a' && c <= 'f') val = (val*16) + c - 'a' + 10; else if (c >= 'A' && c <= 'F') val = (val*16) + c - 'A' + 10; else return val*sign; } } // // check for character // if (str[0] == '\'') { return sign * str[1]; } // // assume decimal // decimal = -1; total = 0; while (1) { c = *str++; if (c == '.') { decimal = total; continue; } if (c <'0' || c > '9') break; val = val*10 + c - '0'; total++; } if (decimal == -1) return val*sign; while (total > decimal) { val /= 10; total--; } return val*sign; } //----------------------------------------------------------------------------- // Normalizes a float string in place. // // (removes leading zeros, trailing zeros after the decimal point, and the decimal point itself where possible) //----------------------------------------------------------------------------- void V_normalizeFloatString( char* pFloat ) { // If we have a decimal point, remove trailing zeroes: if( strchr( pFloat,'.' ) ) { int len = V_strlen(pFloat); while( len > 1 && pFloat[len - 1] == '0' ) { pFloat[len - 1] = '\0'; len--; } if( len > 1 && pFloat[ len - 1 ] == '.' ) { pFloat[len - 1] = '\0'; len--; } } // TODO: Strip leading zeros } //----------------------------------------------------------------------------- // Finds a string in another string with a case insensitive test //----------------------------------------------------------------------------- char const* V_stristr( char const* pStr, char const* pSearch ) { AssertValidStringPtr(pStr); AssertValidStringPtr(pSearch); if (!pStr || !pSearch) return 0; char const* pLetter = pStr; // Check the entire string while (*pLetter != 0) { // Skip over non-matches if (tolower((unsigned char)*pLetter) == tolower((unsigned char)*pSearch)) { // Check for match char const* pMatch = pLetter + 1; char const* pTest = pSearch + 1; while (*pTest != 0) { // We've run off the end; don't bother. if (*pMatch == 0) return 0; if (tolower((unsigned char)*pMatch) != tolower((unsigned char)*pTest)) break; ++pMatch; ++pTest; } // Found a match! if (*pTest == 0) return pLetter; } ++pLetter; } return 0; } char* V_stristr( char* pStr, char const* pSearch ) { AssertValidStringPtr( pStr ); AssertValidStringPtr( pSearch ); return (char*)V_stristr( (char const*)pStr, pSearch ); } //----------------------------------------------------------------------------- // Finds a string in another string with a case insensitive test w/ length validation //----------------------------------------------------------------------------- char const* V_strnistr( char const* pStr, char const* pSearch, int n ) { AssertValidStringPtr(pStr); AssertValidStringPtr(pSearch); if (!pStr || !pSearch) return 0; char const* pLetter = pStr; // Check the entire string while (*pLetter != 0) { if ( n <= 0 ) return 0; // Skip over non-matches if (tolower(*pLetter) == tolower(*pSearch)) { int n1 = n - 1; // Check for match char const* pMatch = pLetter + 1; char const* pTest = pSearch + 1; while (*pTest != 0) { if ( n1 <= 0 ) return 0; // We've run off the end; don't bother. if (*pMatch == 0) return 0; if (tolower(*pMatch) != tolower(*pTest)) break; ++pMatch; ++pTest; --n1; } // Found a match! if (*pTest == 0) return pLetter; } ++pLetter; --n; } return 0; } const char* V_strnchr( const char* pStr, char c, int n ) { char const* pLetter = pStr; char const* pLast = pStr + n; // Check the entire string while ( (pLetter < pLast) && (*pLetter != 0) ) { if (*pLetter == c) return pLetter; ++pLetter; } return NULL; } void V_strncpy( char *pDest, char const *pSrc, int maxLen ) { Assert( maxLen >= 0 ); AssertValidWritePtr( pDest, maxLen ); AssertValidStringPtr( pSrc ); strncpy( pDest, pSrc, maxLen ); if ( maxLen > 0 ) { pDest[maxLen-1] = 0; } } void V_wcsncpy( wchar_t *pDest, wchar_t const *pSrc, int maxLenInBytes ) { Assert( maxLenInBytes >= 0 ); AssertValidWritePtr( pDest, maxLenInBytes ); AssertValidReadPtr( pSrc ); int maxLen = maxLenInBytes / sizeof(wchar_t); wcsncpy( pDest, pSrc, maxLen ); if( maxLen ) { pDest[maxLen-1] = 0; } } int V_snprintf( char *pDest, int maxLen, char const *pFormat, ... ) { Assert( maxLen >= 0 ); AssertValidWritePtr( pDest, maxLen ); AssertValidStringPtr( pFormat ); va_list marker; va_start( marker, pFormat ); #ifdef _WIN32 int len = _vsnprintf( pDest, maxLen, pFormat, marker ); #elif _LINUX int len = vsnprintf( pDest, maxLen, pFormat, marker ); #else #error "define vsnprintf type." #endif va_end( marker ); // Len < 0 represents an overflow if( len < 0 ) { len = maxLen; pDest[maxLen-1] = 0; } return len; } int V_vsnprintf( char *pDest, int maxLen, char const *pFormat, va_list params ) { Assert( maxLen > 0 ); AssertValidWritePtr( pDest, maxLen ); AssertValidStringPtr( pFormat ); int len = _vsnprintf( pDest, maxLen, pFormat, params ); if( len < 0 ) { len = maxLen; pDest[maxLen-1] = 0; } return len; } //----------------------------------------------------------------------------- // Purpose: If COPY_ALL_CHARACTERS == max_chars_to_copy then we try to add the whole pSrc to the end of pDest, otherwise // we copy only as many characters as are specified in max_chars_to_copy (or the # of characters in pSrc if thats's less). // Input : *pDest - destination buffer // *pSrc - string to append // destBufferSize - sizeof the buffer pointed to by pDest // max_chars_to_copy - COPY_ALL_CHARACTERS in pSrc or max # to copy // Output : char * the copied buffer //----------------------------------------------------------------------------- char *V_strncat(char *pDest, const char *pSrc, size_t destBufferSize, int max_chars_to_copy ) { size_t charstocopy = (size_t)0; Assert( destBufferSize >= 0 ); AssertValidStringPtr( pDest); AssertValidStringPtr( pSrc ); size_t len = strlen(pDest); size_t srclen = strlen( pSrc ); if ( max_chars_to_copy <= COPY_ALL_CHARACTERS ) { charstocopy = srclen; } else { charstocopy = (size_t)min( max_chars_to_copy, (int)srclen ); } if ( len + charstocopy >= destBufferSize ) { charstocopy = destBufferSize - len - 1; } if ( !charstocopy ) { return pDest; } char *pOut = strncat( pDest, pSrc, charstocopy ); pOut[destBufferSize-1] = 0; return pOut; } //----------------------------------------------------------------------------- // Purpose: Converts value into x.xx MB/ x.xx KB, x.xx bytes format, including commas // Input : value - // 2 - // false - // Output : char //----------------------------------------------------------------------------- #define NUM_PRETIFYMEM_BUFFERS 8 char *V_pretifymem( float value, int digitsafterdecimal /*= 2*/, bool usebinaryonek /*= false*/ ) { static char output[ NUM_PRETIFYMEM_BUFFERS ][ 32 ]; static int current; float onekb = usebinaryonek ? 1024.0f : 1000.0f; float onemb = onekb * onekb; char *out = output[ current ]; current = ( current + 1 ) & ( NUM_PRETIFYMEM_BUFFERS -1 ); char suffix[ 8 ]; // First figure out which bin to use if ( value > onemb ) { value /= onemb; V_snprintf( suffix, sizeof( suffix ), " MB" ); } else if ( value > onekb ) { value /= onekb; V_snprintf( suffix, sizeof( suffix ), " KB" ); } else { V_snprintf( suffix, sizeof( suffix ), " bytes" ); } char val[ 32 ]; // Clamp to >= 0 digitsafterdecimal = max( digitsafterdecimal, 0 ); // If it's basically integral, don't do any decimals if ( FloatMakePositive( value - (int)value ) < 0.00001 ) { V_snprintf( val, sizeof( val ), "%i%s", (int)value, suffix ); } else { char fmt[ 32 ]; // Otherwise, create a format string for the decimals V_snprintf( fmt, sizeof( fmt ), "%%.%if%s", digitsafterdecimal, suffix ); V_snprintf( val, sizeof( val ), fmt, value ); } // Copy from in to out char *i = val; char *o = out; // Search for decimal or if it was integral, find the space after the raw number char *dot = strstr( i, "." ); if ( !dot ) { dot = strstr( i, " " ); } // Compute position of dot int pos = dot - i; // Don't put a comma if it's <= 3 long pos -= 3; while ( *i ) { // If pos is still valid then insert a comma every third digit, except if we would be // putting one in the first spot if ( pos >= 0 && !( pos % 3 ) ) { // Never in first spot if ( o != out ) { *o++ = ','; } } // Count down comma position pos--; // Copy rest of data as normal *o++ = *i++; } // Terminate *o = 0; return out; } //----------------------------------------------------------------------------- // Purpose: Returns a string representation of an integer with commas // separating the 1000s (ie, 37,426,421) // Input : value - Value to convert // Output : Pointer to a static buffer containing the output //----------------------------------------------------------------------------- #define NUM_PRETIFYNUM_BUFFERS 8 char *V_pretifynum( int64 value ) { static char output[ NUM_PRETIFYMEM_BUFFERS ][ 32 ]; static int current; char *out = output[ current ]; current = ( current + 1 ) & ( NUM_PRETIFYMEM_BUFFERS -1 ); *out = 0; // Render the leading -, if necessary if ( value < 0 ) { char *pchRender = out + V_strlen( out ); V_snprintf( pchRender, 32, "-" ); value = -value; } // Render quadrillions if ( value >= 1000000000000 ) { char *pchRender = out + V_strlen( out ); V_snprintf( pchRender, 32, "%d,", value / 1000000000000 ); } // Render trillions if ( value >= 1000000000000 ) { char *pchRender = out + V_strlen( out ); V_snprintf( pchRender, 32, "%d,", value / 1000000000000 ); } // Render billions if ( value >= 1000000000 ) { char *pchRender = out + V_strlen( out ); V_snprintf( pchRender, 32, "%d,", value / 1000000000 ); } // Render millions if ( value >= 1000000 ) { char *pchRender = out + V_strlen( out ); if ( value >= 1000000000 ) V_snprintf( pchRender, 32, "%03d,", ( value / 1000000 ) % 1000 ); else V_snprintf( pchRender, 32, "%d,", ( value / 1000000 ) % 1000 ); } // Render thousands if ( value >= 1000 ) { char *pchRender = out + V_strlen( out ); if ( value >= 1000000 ) V_snprintf( pchRender, 32, "%03d,", ( value / 1000 ) % 1000 ); else V_snprintf( pchRender, 32, "%d,", ( value / 1000 ) % 1000 ); } // Render units char *pchRender = out + V_strlen( out ); if ( value > 1000 ) V_snprintf( pchRender, 32, "%03d", value % 1000 ); else V_snprintf( pchRender, 32, "%d", value % 1000 ); return out; } //----------------------------------------------------------------------------- // Purpose: Converts a UTF8 string into a unicode string //----------------------------------------------------------------------------- int V_UTF8ToUnicode( const char *pUTF8, wchar_t *pwchDest, int cubDestSizeInBytes ) { AssertValidStringPtr(pUTF8); AssertValidWritePtr(pwchDest); pwchDest[0] = 0; #ifdef _WIN32 int cchResult = MultiByteToWideChar( CP_UTF8, 0, pUTF8, -1, pwchDest, cubDestSizeInBytes / sizeof(wchar_t) ); #elif _LINUX int cchResult = mbstowcs( pwchDest, pUTF8, cubDestSizeInBytes / sizeof(wchar_t) ); #endif pwchDest[(cubDestSizeInBytes / sizeof(wchar_t)) - 1] = 0; return cchResult; } //----------------------------------------------------------------------------- // Purpose: Converts a unicode string into a UTF8 (standard) string //----------------------------------------------------------------------------- int V_UnicodeToUTF8( const wchar_t *pUnicode, char *pUTF8, int cubDestSizeInBytes ) { AssertValidStringPtr(pUTF8, cubDestSizeInBytes); AssertValidReadPtr(pUnicode); pUTF8[0] = 0; #ifdef _WIN32 int cchResult = WideCharToMultiByte( CP_UTF8, 0, pUnicode, -1, pUTF8, cubDestSizeInBytes, NULL, NULL ); #elif _LINUX int cchResult = wcstombs( pUTF8, pUnicode, cubDestSizeInBytes ); #endif pUTF8[cubDestSizeInBytes - 1] = 0; return cchResult; } //----------------------------------------------------------------------------- // Purpose: Returns the 4 bit nibble for a hex character // Input : c - // Output : unsigned char //----------------------------------------------------------------------------- static unsigned char V_nibble( char c ) { if ( ( c >= '0' ) && ( c <= '9' ) ) { return (unsigned char)(c - '0'); } if ( ( c >= 'A' ) && ( c <= 'F' ) ) { return (unsigned char)(c - 'A' + 0x0a); } if ( ( c >= 'a' ) && ( c <= 'f' ) ) { return (unsigned char)(c - 'a' + 0x0a); } return '0'; } //----------------------------------------------------------------------------- // Purpose: // Input : *in - // numchars - // *out - // maxoutputbytes - //----------------------------------------------------------------------------- void V_hextobinary( char const *in, int numchars, byte *out, int maxoutputbytes ) { int len = V_strlen( in ); numchars = min( len, numchars ); // Make sure it's even numchars = ( numchars ) & ~0x1; // Must be an even # of input characters (two chars per output byte) Assert( numchars >= 2 ); memset( out, 0x00, maxoutputbytes ); byte *p; int i; p = out; for ( i = 0; ( i < numchars ) && ( ( p - out ) < maxoutputbytes ); i+=2, p++ ) { *p = ( V_nibble( in[i] ) << 4 ) | V_nibble( in[i+1] ); } } //----------------------------------------------------------------------------- // Purpose: // Input : *in - // inputbytes - // *out - // outsize - //----------------------------------------------------------------------------- void V_binarytohex( const byte *in, int inputbytes, char *out, int outsize ) { Assert( outsize >= 1 ); char doublet[10]; int i; out[0]=0; for ( i = 0; i < inputbytes; i++ ) { unsigned char c = in[i]; V_snprintf( doublet, sizeof( doublet ), "%02x", c ); V_strncat( out, doublet, outsize, COPY_ALL_CHARACTERS ); } } #if defined( _WIN32 ) || defined( WIN32 ) #define PATHSEPARATOR(c) ((c) == '\\' || (c) == '/') #else //_WIN32 #define PATHSEPARATOR(c) ((c) == '/') #endif //_WIN32 //----------------------------------------------------------------------------- // Purpose: Extracts the base name of a file (no path, no extension, assumes '/' or '\' as path separator) // Input : *in - // *out - // maxlen - //----------------------------------------------------------------------------- void V_FileBase( const char *in, char *out, int maxlen ) { Assert( maxlen >= 1 ); Assert( in ); Assert( out ); if ( !in || !in[ 0 ] ) { *out = 0; return; } int len, start, end; len = V_strlen( in ); // scan backward for '.' end = len - 1; while ( end&& in[end] != '.' && !PATHSEPARATOR( in[end] ) ) { end--; } if ( in[end] != '.' ) // no '.', copy to end { end = len-1; } else { end--; // Found ',', copy to left of '.' } // Scan backward for '/' start = len-1; while ( start >= 0 && !PATHSEPARATOR( in[start] ) ) { start--; } if ( start < 0 || !PATHSEPARATOR( in[start] ) ) { start = 0; } else { start++; } // Length of new sting len = end - start + 1; int maxcopy = min( len + 1, maxlen ); // Copy partial string V_strncpy( out, &in[start], maxcopy ); } //----------------------------------------------------------------------------- // Purpose: // Input : *ppath - //----------------------------------------------------------------------------- void V_StripTrailingSlash( char *ppath ) { Assert( ppath ); int len = V_strlen( ppath ); if ( len > 0 ) { if ( PATHSEPARATOR( ppath[ len - 1 ] ) ) { ppath[ len - 1 ] = 0; } } } //----------------------------------------------------------------------------- // Purpose: // Input : *in - // *out - // outSize - //----------------------------------------------------------------------------- void V_StripExtension( const char *in, char *out, int outSize ) { // Find the last dot. If it's followed by a dot or a slash, then it's part of a // directory specifier like ../../somedir/./blah. // scan backward for '.' int end = V_strlen( in ) - 1; while ( end > 0 && in[end] != '.' && !PATHSEPARATOR( in[end] ) ) { --end; } if (end > 0 && !PATHSEPARATOR( in[end] ) && end < outSize) { int nChars = min( end, outSize-1 ); if ( out != in ) { memcpy( out, in, nChars ); } out[nChars] = 0; } else { // nothing found if ( out != in ) { V_strncpy( out, in, outSize ); } } } //----------------------------------------------------------------------------- // Purpose: // Input : *path - // *extension - // pathStringLength - //----------------------------------------------------------------------------- void V_DefaultExtension( char *path, const char *extension, int pathStringLength ) { Assert( path ); Assert( pathStringLength >= 1 ); Assert( extension ); Assert( extension[0] == '.' ); char *src; // if path doesn't have a .EXT, append extension // (extension should include the .) src = path + V_strlen(path) - 1; while ( !PATHSEPARATOR( *src ) && ( src > path ) ) { if (*src == '.') { // it has an extension return; } src--; } // Concatenate the desired extension V_strncat( path, extension, pathStringLength, COPY_ALL_CHARACTERS ); } //----------------------------------------------------------------------------- // Purpose: Force extension... // Input : *path - // *extension - // pathStringLength - //----------------------------------------------------------------------------- void V_SetExtension( char *path, const char *extension, int pathStringLength ) { V_StripExtension( path, path, pathStringLength ); V_DefaultExtension( path, extension, pathStringLength ); } //----------------------------------------------------------------------------- // Purpose: Remove final filename from string // Input : *path - // Output : void V_StripFilename //----------------------------------------------------------------------------- void V_StripFilename (char *path) { int length; length = V_strlen( path )-1; if ( length <= 0 ) return; while ( length > 0 && !PATHSEPARATOR( path[length] ) ) { length--; } path[ length ] = 0; } #ifdef _WIN32 #define CORRECT_PATH_SEPARATOR '\\' #define INCORRECT_PATH_SEPARATOR '/' #elif _LINUX #define CORRECT_PATH_SEPARATOR '/' #define INCORRECT_PATH_SEPARATOR '\\' #endif //----------------------------------------------------------------------------- // Purpose: Changes all '/' or '\' characters into separator // Input : *pname - // separator - //----------------------------------------------------------------------------- void V_FixSlashes( char *pname, char separator /* = CORRECT_PATH_SEPARATOR */ ) { while ( *pname ) { if ( *pname == INCORRECT_PATH_SEPARATOR || *pname == CORRECT_PATH_SEPARATOR ) { *pname = separator; } pname++; } } //----------------------------------------------------------------------------- // Purpose: This function fixes cases of filenames like materials\\blah.vmt or somepath\otherpath\\ and removes the extra double slash. //----------------------------------------------------------------------------- void V_FixDoubleSlashes( char *pStr ) { int len = V_strlen( pStr ); for ( int i=1; i < len-1; i++ ) { if ( (pStr[i] == '/' || pStr[i] == '\\') && (pStr[i+1] == '/' || pStr[i+1] == '\\') ) { // This means there's a double slash somewhere past the start of the filename. That // can happen in Hammer if they use a material in the root directory. You'll get a filename // that looks like 'materials\\blah.vmt' V_memmove( &pStr[i], &pStr[i+1], len - i ); --len; } } } //----------------------------------------------------------------------------- // Purpose: Strip off the last directory from dirName // Input : *dirName - // maxlen - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool V_StripLastDir( char *dirName, int maxlen ) { if( dirName[0] == 0 || !V_stricmp( dirName, "./" ) || !V_stricmp( dirName, ".\\" ) ) return false; int len = V_strlen( dirName ); Assert( len < maxlen ); // skip trailing slash if ( PATHSEPARATOR( dirName[len-1] ) ) { len--; } while ( len > 0 ) { if ( PATHSEPARATOR( dirName[len-1] ) ) { dirName[len] = 0; V_FixSlashes( dirName, CORRECT_PATH_SEPARATOR ); return true; } len--; } // Allow it to return an empty string and true. This can happen if something like "tf2/" is passed in. // The correct behavior is to strip off the last directory ("tf2") and return true. if( len == 0 ) { V_snprintf( dirName, maxlen, ".%c", CORRECT_PATH_SEPARATOR ); return true; } return true; } //----------------------------------------------------------------------------- // Purpose: Returns a pointer to the beginning of the unqualified file name // (no path information) // Input: in - file name (may be unqualified, relative or absolute path) // Output: pointer to unqualified file name //----------------------------------------------------------------------------- const char * V_UnqualifiedFileName( const char * in ) { // back up until the character after the first path separator we find, // or the beginning of the string const char * out = in + strlen( in ) - 1; while ( ( out > in ) && ( !PATHSEPARATOR( *( out-1 ) ) ) ) out--; return out; } //----------------------------------------------------------------------------- // Purpose: Composes a path and filename together, inserting a path separator // if need be // Input: path - path to use // filename - filename to use // dest - buffer to compose result in // destSize - size of destination buffer //----------------------------------------------------------------------------- void V_ComposeFileName( const char *path, const char *filename, char *dest, int destSize ) { V_strncpy( dest, path, destSize ); V_AppendSlash( dest, destSize ); V_strncat( dest, filename, destSize, COPY_ALL_CHARACTERS ); V_FixSlashes( dest ); } //----------------------------------------------------------------------------- // Purpose: // Input : *path - // *dest - // destSize - // Output : void V_ExtractFilePath //----------------------------------------------------------------------------- bool V_ExtractFilePath (const char *path, char *dest, int destSize ) { Assert( destSize >= 1 ); if ( destSize < 1 ) { return false; } // Last char int len = V_strlen(path); const char *src = path + (len ? len-1 : 0); // back up until a \ or the start while ( src != path && !PATHSEPARATOR( *(src-1) ) ) { src--; } int copysize = min( src - path, destSize - 1 ); memcpy( dest, path, copysize ); dest[copysize] = 0; return copysize != 0 ? true : false; } //----------------------------------------------------------------------------- // Purpose: // Input : *path - // *dest - // destSize - // Output : void V_ExtractFileExtension //----------------------------------------------------------------------------- void V_ExtractFileExtension( const char *path, char *dest, int destSize ) { *dest = NULL; const char * extension = V_GetFileExtension( path ); if ( NULL != extension ) V_strncpy( dest, extension, destSize ); } //----------------------------------------------------------------------------- // Purpose: Returns a pointer to the file extension within a file name string // Input: in - file name // Output: pointer to beginning of extension (after the "."), or NULL // if there is no extension //----------------------------------------------------------------------------- const char * V_GetFileExtension( const char * path ) { const char *src; src = path + strlen(path) - 1; // // back up until a . or the start // while (src != path && *(src-1) != '.' ) src--; // check to see if the '.' is part of a pathname if (src == path || PATHSEPARATOR( *src ) ) { return NULL; // no extension } return src; } bool V_RemoveDotSlashes( char *pFilename, char separator ) { // Remove '//' or '\\' char *pIn = pFilename; char *pOut = pFilename; bool bPrevPathSep = false; while ( *pIn ) { bool bIsPathSep = PATHSEPARATOR( *pIn ); if ( !bIsPathSep || !bPrevPathSep ) { *pOut++ = *pIn; } bPrevPathSep = bIsPathSep; ++pIn; } *pOut = 0; // Get rid of "./"'s pIn = pFilename; pOut = pFilename; while ( *pIn ) { // The logic on the second line is preventing it from screwing up "../" if ( pIn[0] == '.' && PATHSEPARATOR( pIn[1] ) && (pIn == pFilename || pIn[-1] != '.') ) { pIn += 2; } else { *pOut = *pIn; ++pIn; ++pOut; } } *pOut = 0; // Get rid of a trailing "/." (needless). int len = strlen( pFilename ); if ( len > 2 && pFilename[len-1] == '.' && PATHSEPARATOR( pFilename[len-2] ) ) { pFilename[len-2] = 0; } // Each time we encounter a "..", back up until we've read the previous directory name, // then get rid of it. pIn = pFilename; while ( *pIn ) { if ( pIn[0] == '.' && pIn[1] == '.' && (pIn == pFilename || PATHSEPARATOR(pIn[-1])) && // Preceding character must be a slash. (pIn[2] == 0 || PATHSEPARATOR(pIn[2])) ) // Following character must be a slash or the end of the string. { char *pEndOfDots = pIn + 2; char *pStart = pIn - 2; // Ok, now scan back for the path separator that starts the preceding directory. while ( 1 ) { if ( pStart < pFilename ) return false; if ( PATHSEPARATOR( *pStart ) ) break; --pStart; } // Now slide the string down to get rid of the previous directory and the ".." memmove( pStart, pEndOfDots, strlen( pEndOfDots ) + 1 ); // Start over. pIn = pFilename; } else { ++pIn; } } V_FixSlashes( pFilename, separator ); return true; } void V_AppendSlash( char *pStr, int strSize ) { int len = V_strlen( pStr ); if ( len > 0 && !PATHSEPARATOR(pStr[len-1]) ) { if ( len+1 >= strSize ) Error( "V_AppendSlash: ran out of space on %s.", pStr ); pStr[len] = CORRECT_PATH_SEPARATOR; pStr[len+1] = 0; } } void V_MakeAbsolutePath( char *pOut, int outLen, const char *pPath, const char *pStartingDir ) { if ( V_IsAbsolutePath( pPath ) ) { // pPath is not relative.. just copy it. V_strncpy( pOut, pPath, outLen ); } else { // Make sure the starting directory is absolute.. if ( pStartingDir && V_IsAbsolutePath( pStartingDir ) ) { V_strncpy( pOut, pStartingDir, outLen ); } else { if ( !_getcwd( pOut, outLen ) ) Error( "V_MakeAbsolutePath: _getcwd failed." ); if ( pStartingDir ) { V_AppendSlash( pOut, outLen ); V_strncat( pOut, pStartingDir, outLen, COPY_ALL_CHARACTERS ); } } // Concatenate the paths. V_AppendSlash( pOut, outLen ); V_strncat( pOut, pPath, outLen, COPY_ALL_CHARACTERS ); } if ( !V_RemoveDotSlashes( pOut ) ) Error( "V_MakeAbsolutePath: tried to \"..\" past the root." ); V_FixSlashes( pOut ); } //----------------------------------------------------------------------------- // Makes a relative path //----------------------------------------------------------------------------- bool V_MakeRelativePath( const char *pFullPath, const char *pDirectory, char *pRelativePath, int nBufLen ) { pRelativePath[0] = 0; const char *pPath = pFullPath; const char *pDir = pDirectory; // Strip out common parts of the path const char *pLastCommonPath = NULL; const char *pLastCommonDir = NULL; while ( *pPath && ( tolower( *pPath ) == tolower( *pDir ) || ( PATHSEPARATOR( *pPath ) && ( PATHSEPARATOR( *pDir ) || (*pDir == 0) ) ) ) ) { if ( PATHSEPARATOR( *pPath ) ) { pLastCommonPath = pPath + 1; pLastCommonDir = pDir + 1; } if ( *pDir == 0 ) { --pLastCommonDir; break; } ++pDir; ++pPath; } // Nothing in common if ( !pLastCommonPath ) return false; // For each path separator remaining in the dir, need a ../ int nOutLen = 0; bool bLastCharWasSeparator = true; for ( ; *pLastCommonDir; ++pLastCommonDir ) { if ( PATHSEPARATOR( *pLastCommonDir ) ) { pRelativePath[nOutLen++] = '.'; pRelativePath[nOutLen++] = '.'; pRelativePath[nOutLen++] = CORRECT_PATH_SEPARATOR; bLastCharWasSeparator = true; } else { bLastCharWasSeparator = false; } } // Deal with relative paths not specified with a trailing slash if ( !bLastCharWasSeparator ) { pRelativePath[nOutLen++] = '.'; pRelativePath[nOutLen++] = '.'; pRelativePath[nOutLen++] = CORRECT_PATH_SEPARATOR; } // Copy the remaining part of the relative path over, fixing the path separators for ( ; *pLastCommonPath; ++pLastCommonPath ) { if ( PATHSEPARATOR( *pLastCommonPath ) ) { pRelativePath[nOutLen++] = CORRECT_PATH_SEPARATOR; } else { pRelativePath[nOutLen++] = *pLastCommonPath; } // Check for overflow if ( nOutLen == nBufLen - 1 ) break; } pRelativePath[nOutLen] = 0; return true; } //----------------------------------------------------------------------------- // small helper function shared by lots of modules //----------------------------------------------------------------------------- bool V_IsAbsolutePath( const char *pStr ) { bool bIsAbsolute = ( pStr[0] && pStr[1] == ':' ) || pStr[0] == '/' || pStr[0] == '\\'; if ( IsX360() && !bIsAbsolute ) { bIsAbsolute = ( V_stristr( pStr, ":" ) != NULL ); } return bIsAbsolute; } // Copies at most nCharsToCopy bytes from pIn into pOut. // Returns false if it would have overflowed pOut's buffer. static bool CopyToMaxChars( char *pOut, int outSize, const char *pIn, int nCharsToCopy ) { if ( outSize == 0 ) return false; int iOut = 0; while ( *pIn && nCharsToCopy > 0 ) { if ( iOut == (outSize-1) ) { pOut[iOut] = 0; return false; } pOut[iOut] = *pIn; ++iOut; ++pIn; --nCharsToCopy; } pOut[iOut] = 0; return true; } // Returns true if it completed successfully. // If it would overflow pOut, it fills as much as it can and returns false. bool V_StrSubst( const char *pIn, const char *pMatch, const char *pReplaceWith, char *pOut, int outLen, bool bCaseSensitive ) { int replaceFromLen = strlen( pMatch ); int replaceToLen = strlen( pReplaceWith ); const char *pInStart = pIn; char *pOutPos = pOut; pOutPos[0] = 0; while ( 1 ) { int nRemainingOut = outLen - (pOutPos - pOut); const char *pTestPos = ( bCaseSensitive ? strstr( pInStart, pMatch ) : V_stristr( pInStart, pMatch ) ); if ( pTestPos ) { // Found an occurence of pMatch. First, copy whatever leads up to the string. int copyLen = pTestPos - pInStart; if ( !CopyToMaxChars( pOutPos, nRemainingOut, pInStart, copyLen ) ) return false; // Did we hit the end of the output string? if ( copyLen > nRemainingOut-1 ) return false; pOutPos += strlen( pOutPos ); nRemainingOut = outLen - (pOutPos - pOut); // Now add the replacement string. if ( !CopyToMaxChars( pOutPos, nRemainingOut, pReplaceWith, replaceToLen ) ) return false; pInStart += copyLen + replaceFromLen; pOutPos += replaceToLen; } else { // We're at the end of pIn. Copy whatever remains and get out. int copyLen = strlen( pInStart ); V_strncpy( pOutPos, pInStart, nRemainingOut ); return ( copyLen <= nRemainingOut-1 ); } } } char* AllocString( const char *pStr, int nMaxChars ) { int allocLen; if ( nMaxChars == -1 ) allocLen = strlen( pStr ) + 1; else allocLen = min( (int)strlen(pStr), nMaxChars ) + 1; char *pOut = new char[allocLen]; V_strncpy( pOut, pStr, allocLen ); return pOut; } void V_SplitString2( const char *pString, const char **pSeparators, int nSeparators, CUtlVector<char*> &outStrings ) { outStrings.Purge(); const char *pCurPos = pString; while ( 1 ) { int iFirstSeparator = -1; const char *pFirstSeparator = 0; for ( int i=0; i < nSeparators; i++ ) { const char *pTest = V_stristr( pCurPos, pSeparators[i] ); if ( pTest && (!pFirstSeparator || pTest < pFirstSeparator) ) { iFirstSeparator = i; pFirstSeparator = pTest; } } if ( pFirstSeparator ) { // Split on this separator and continue on. int separatorLen = strlen( pSeparators[iFirstSeparator] ); if ( pFirstSeparator > pCurPos ) { outStrings.AddToTail( AllocString( pCurPos, pFirstSeparator-pCurPos ) ); } pCurPos = pFirstSeparator + separatorLen; } else { // Copy the rest of the string if ( strlen( pCurPos ) ) { outStrings.AddToTail( AllocString( pCurPos, -1 ) ); } return; } } } void V_SplitString( const char *pString, const char *pSeparator, CUtlVector<char*> &outStrings ) { V_SplitString2( pString, &pSeparator, 1, outStrings ); } // This function takes a slice out of pStr and stores it in pOut. // It follows the Python slice convention: // Negative numbers wrap around the string (-1 references the last character). // Numbers are clamped to the end of the string. void V_StrSlice( const char *pStr, int firstChar, int lastCharNonInclusive, char *pOut, int outSize ) { if ( outSize == 0 ) return; int length = strlen( pStr ); // Fixup the string indices. if ( firstChar < 0 ) { firstChar = length - (-firstChar % length); } else if ( firstChar >= length ) { pOut[0] = 0; return; } if ( lastCharNonInclusive < 0 ) { lastCharNonInclusive = length - (-lastCharNonInclusive % length); } else if ( lastCharNonInclusive > length ) { lastCharNonInclusive %= length; } if ( lastCharNonInclusive <= firstChar ) { pOut[0] = 0; return; } int copyLen = lastCharNonInclusive - firstChar; if ( copyLen <= (outSize-1) ) { memcpy( pOut, &pStr[firstChar], copyLen ); pOut[copyLen] = 0; } else { memcpy( pOut, &pStr[firstChar], outSize-1 ); pOut[outSize-1] = 0; } } void V_StrLeft( const char *pStr, int nChars, char *pOut, int outSize ) { if ( nChars == 0 ) { if ( outSize != 0 ) pOut[0] = 0; return; } V_StrSlice( pStr, 0, nChars, pOut, outSize ); } void V_StrRight( const char *pStr, int nChars, char *pOut, int outSize ) { int len = strlen( pStr ); if ( nChars >= len ) { V_strncpy( pOut, pStr, outSize ); } else { V_StrSlice( pStr, -nChars, strlen( pStr ), pOut, outSize ); } } //----------------------------------------------------------------------------- // Convert multibyte to wchar + back //----------------------------------------------------------------------------- void V_strtowcs( const char *pString, int nInSize, wchar_t *pWString, int nOutSize ) { #ifdef _WIN32 if ( !MultiByteToWideChar( CP_UTF8, 0, pString, nInSize, pWString, nOutSize ) ) { *pWString = L'\0'; } #elif _LINUX if ( mbstowcs( pWString, pString, nOutSize / sizeof(wchar_t) ) <= 0 ) { *pWString = 0; } #endif } void V_wcstostr( const wchar_t *pWString, int nInSize, char *pString, int nOutSize ) { #ifdef _WIN32 if ( !WideCharToMultiByte( CP_UTF8, 0, pWString, nInSize, pString, nOutSize, NULL, NULL ) ) { *pString = '\0'; } #elif _LINUX if ( wcstombs( pString, pWString, nOutSize ) <= 0 ) { *pString = '\0'; } #endif } //-------------------------------------------------------------------------------- // backslashification //-------------------------------------------------------------------------------- static char s_BackSlashMap[]="\tt\nn\rr\"\"\\\\"; char *V_AddBackSlashesToSpecialChars( char const *pSrc ) { // first, count how much space we are going to need int nSpaceNeeded = 0; for( char const *pScan = pSrc; *pScan; pScan++ ) { nSpaceNeeded++; for(char const *pCharSet=s_BackSlashMap; *pCharSet; pCharSet += 2 ) { if ( *pCharSet == *pScan ) nSpaceNeeded++; // we need to store a bakslash } } char *pRet = new char[ nSpaceNeeded + 1 ]; // +1 for null char *pOut = pRet; for( char const *pScan = pSrc; *pScan; pScan++ ) { bool bIsSpecial = false; for(char const *pCharSet=s_BackSlashMap; *pCharSet; pCharSet += 2 ) { if ( *pCharSet == *pScan ) { *( pOut++ ) = '\\'; *( pOut++ ) = pCharSet[1]; bIsSpecial = true; break; } } if (! bIsSpecial ) { *( pOut++ ) = *pScan; } } *( pOut++ ) = 0; return pRet; }
[ "113660872@qq.com" ]
113660872@qq.com
c0675bdb8eca178c06d393abaeef54f68e3d1d67
27d485637faabbc56ceee5e8d75cd23dc66acbcc
/native/physics3d/src/reactphysics3d/engine/ConstraintSolver.cpp
1edb607ad3ac5281f95455a88739c0935c99baf1
[]
no_license
d954mas/game-space-defender
98d9d6b23279fd8fdae5e537e6e49649288007fa
ab208b9636882f990eb1325debec89fba94fcdeb
refs/heads/master
2023-04-06T17:57:54.148986
2021-04-23T09:21:45
2021-04-23T09:21:45
356,860,283
0
0
null
null
null
null
UTF-8
C++
false
false
4,232
cpp
/******************************************************************************** * ReactPhysics3D physics library, http://www.reactphysics3d.com * * Copyright (c) 2010-2019 Daniel Chappuis * ********************************************************************************* * * * This software is provided 'as-is', without any express or implied warranty. * * In no event will the authors be held liable for any damages arising from the * * use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not claim * * that you wrote the original software. If you use this software in a * * product, an acknowledgment in the product documentation would be * * appreciated but is not required. * * * * 2. Altered source versions must be plainly marked as such, and must not be * * misrepresented as being the original software. * * * * 3. This notice may not be removed or altered from any source distribution. * * * ********************************************************************************/ // Libraries #include "engine/ConstraintSolver.h" #include "utils/Profiler.h" #include "engine/Island.h" using namespace reactphysics3d; // Constructor ConstraintSolver::ConstraintSolver() : mIsWarmStartingActive(true) { #ifdef IS_PROFILING_ACTIVE mProfiler = nullptr; #endif } // Initialize the constraint solver for a given island void ConstraintSolver::initializeForIsland(decimal dt, Island* island) { RP3D_PROFILE("ConstraintSolver::initializeForIsland()", mProfiler); assert(island != nullptr); assert(island->getNbBodies() > 0); assert(island->getNbJoints() > 0); // Set the current time step mTimeStep = dt; // Initialize the constraint solver data used to initialize and solve the constraints mConstraintSolverData.timeStep = mTimeStep; mConstraintSolverData.isWarmStartingActive = mIsWarmStartingActive; // For each joint of the island Joint** joints = island->getJoints(); for (uint i=0; i<island->getNbJoints(); i++) { // Initialize the constraint before solving it joints[i]->initBeforeSolve(mConstraintSolverData); // Warm-start the constraint if warm-starting is enabled if (mIsWarmStartingActive) { joints[i]->warmstart(mConstraintSolverData); } } } // Solve the velocity constraints void ConstraintSolver::solveVelocityConstraints(Island* island) { RP3D_PROFILE("ConstraintSolver::solveVelocityConstraints()", mProfiler); assert(island != nullptr); assert(island->getNbJoints() > 0); // For each joint of the island Joint** joints = island->getJoints(); for (uint i=0; i<island->getNbJoints(); i++) { // Solve the constraint joints[i]->solveVelocityConstraint(mConstraintSolverData); } } // Solve the position constraints void ConstraintSolver::solvePositionConstraints(Island* island) { RP3D_PROFILE("ConstraintSolver::solvePositionConstraints()", mProfiler); assert(island != nullptr); assert(island->getNbJoints() > 0); // For each joint of the island Joint** joints = island->getJoints(); for (uint i=0; i < island->getNbJoints(); i++) { // Solve the constraint joints[i]->solvePositionConstraint(mConstraintSolverData); } }
[ "d954mas@gmail.com" ]
d954mas@gmail.com
b7b440d108eff4d29979565894a16c5ef6fcb755
780ade36305af731aa0acbc1e2d2c32fdd69c638
/src/zlsrchain.cpp
059fa4ff2c17d2f9ac65e5647fbf42515bdde863
[ "MIT" ]
permissive
LeisureCoinProject/LSR-HardFork
ec21d3cec756ccbc98ac1936e6674d0c81ecf76c
617c6da70da92a7d56c5ace0797c854dcd152066
refs/heads/master
2020-07-15T13:30:53.152724
2019-09-09T21:36:16
2019-09-09T21:36:16
205,573,025
0
1
null
null
null
null
UTF-8
C++
false
false
14,456
cpp
// Copyright (c) 2018 The leisurecoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "zlsrchain.h" #include "invalid.h" #include "main.h" #include "txdb.h" #include "ui_interface.h" // 6 comes from OPCODE (1) + vch.size() (1) + BIGNUM size (4) #define SCRIPT_OFFSET 6 // For Script size (BIGNUM/Uint256 size) #define BIGNUM_SIZE 4 bool BlockToMintValueVector(const CBlock& block, const libzerocoin::CoinDenomination denom, vector<CBigNum>& vValues) { for (const CTransaction& tx : block.vtx) { if(!tx.IsZerocoinMint()) continue; for (const CTxOut& txOut : tx.vout) { if(!txOut.scriptPubKey.IsZerocoinMint()) continue; CValidationState state; libzerocoin::PublicCoin coin(Params().Zerocoin_Params(false)); if(!TxOutToPublicCoin(txOut, coin, state)) return false; if (coin.getDenomination() != denom) continue; vValues.push_back(coin.getValue()); } } return true; } bool BlockToPubcoinList(const CBlock& block, std::list<libzerocoin::PublicCoin>& listPubcoins, bool fFilterInvalid) { for (const CTransaction& tx : block.vtx) { if(!tx.IsZerocoinMint()) continue; // Filter out mints that have used invalid outpoints if (fFilterInvalid) { bool fValid = true; for (const CTxIn& in : tx.vin) { if (!ValidOutPoint(in.prevout, INT_MAX)) { fValid = false; break; } } if (!fValid) continue; } uint256 txHash = tx.GetHash(); for (unsigned int i = 0; i < tx.vout.size(); i++) { //Filter out mints that use invalid outpoints - edge case: invalid spend with minted change if (fFilterInvalid && !ValidOutPoint(COutPoint(txHash, i), INT_MAX)) break; const CTxOut txOut = tx.vout[i]; if(!txOut.scriptPubKey.IsZerocoinMint()) continue; CValidationState state; libzerocoin::PublicCoin pubCoin(Params().Zerocoin_Params(false)); if(!TxOutToPublicCoin(txOut, pubCoin, state)) return false; listPubcoins.emplace_back(pubCoin); } } return true; } //return a list of zerocoin mints contained in a specific block bool BlockToZerocoinMintList(const CBlock& block, std::list<CZerocoinMint>& vMints, bool fFilterInvalid) { for (const CTransaction& tx : block.vtx) { if(!tx.IsZerocoinMint()) continue; // Filter out mints that have used invalid outpoints if (fFilterInvalid) { bool fValid = true; for (const CTxIn& in : tx.vin) { if (!ValidOutPoint(in.prevout, INT_MAX)) { fValid = false; break; } } if (!fValid) continue; } uint256 txHash = tx.GetHash(); for (unsigned int i = 0; i < tx.vout.size(); i++) { //Filter out mints that use invalid outpoints - edge case: invalid spend with minted change if (fFilterInvalid && !ValidOutPoint(COutPoint(txHash, i), INT_MAX)) break; const CTxOut txOut = tx.vout[i]; if(!txOut.scriptPubKey.IsZerocoinMint()) continue; CValidationState state; libzerocoin::PublicCoin pubCoin(Params().Zerocoin_Params(false)); if(!TxOutToPublicCoin(txOut, pubCoin, state)) return false; //version should not actually matter here since it is just a reference to the pubcoin, not to the privcoin uint8_t version = 1; CZerocoinMint mint = CZerocoinMint(pubCoin.getDenomination(), pubCoin.getValue(), 0, 0, false, version, nullptr); mint.SetTxHash(tx.GetHash()); vMints.push_back(mint); } } return true; } void FindMints(std::vector<CMintMeta> vMintsToFind, std::vector<CMintMeta>& vMintsToUpdate, std::vector<CMintMeta>& vMissingMints) { // see which mints are in our public zerocoin database. The mint should be here if it exists, unless // something went wrong for (CMintMeta meta : vMintsToFind) { uint256 txHash; if (!zerocoinDB->ReadCoinMint(meta.hashPubcoin, txHash)) { vMissingMints.push_back(meta); continue; } // make sure the txhash and block height meta data are correct for this mint CTransaction tx; uint256 hashBlock; if (!GetTransaction(txHash, tx, hashBlock, true)) { LogPrintf("%s : cannot find tx %s\n", __func__, txHash.GetHex()); vMissingMints.push_back(meta); continue; } if (!mapBlockIndex.count(hashBlock)) { LogPrintf("%s : cannot find block %s\n", __func__, hashBlock.GetHex()); vMissingMints.push_back(meta); continue; } //see if this mint is spent uint256 hashTxSpend = 0; bool fSpent = zerocoinDB->ReadCoinSpend(meta.hashSerial, hashTxSpend); //if marked as spent, check that it actually made it into the chain CTransaction txSpend; uint256 hashBlockSpend; if (fSpent && !GetTransaction(hashTxSpend, txSpend, hashBlockSpend, true)) { LogPrintf("%s : cannot find spend tx %s\n", __func__, hashTxSpend.GetHex()); meta.isUsed = false; vMintsToUpdate.push_back(meta); continue; } //The mint has been incorrectly labelled as spent in zerocoinDB and needs to be undone int nHeightTx = 0; uint256 hashSerial = meta.hashSerial; uint256 txidSpend; if (fSpent && !IsSerialInBlockchain(hashSerial, nHeightTx, txidSpend)) { LogPrintf("%s : cannot find block %s. Erasing coinspend from zerocoinDB.\n", __func__, hashBlockSpend.GetHex()); meta.isUsed = false; vMintsToUpdate.push_back(meta); continue; } // is the denomination correct? for (auto& out : tx.vout) { if (!out.IsZerocoinMint()) continue; libzerocoin::PublicCoin pubcoin(Params().Zerocoin_Params(meta.nVersion < libzerocoin::PrivateCoin::PUBKEY_VERSION)); CValidationState state; TxOutToPublicCoin(out, pubcoin, state); if (GetPubCoinHash(pubcoin.getValue()) == meta.hashPubcoin && pubcoin.getDenomination() != meta.denom) { LogPrintf("%s: found mismatched denom pubcoinhash = %s\n", __func__, meta.hashPubcoin.GetHex()); meta.denom = pubcoin.getDenomination(); vMintsToUpdate.emplace_back(meta); } } // if meta data is correct, then no need to update if (meta.txid == txHash && meta.nHeight == mapBlockIndex[hashBlock]->nHeight && meta.isUsed == fSpent) continue; //mark this mint for update meta.txid = txHash; meta.nHeight = mapBlockIndex[hashBlock]->nHeight; meta.isUsed = fSpent; LogPrintf("%s: found updates for pubcoinhash = %s\n", __func__, meta.hashPubcoin.GetHex()); vMintsToUpdate.push_back(meta); } } int GetZerocoinStartHeight() { return Params().Zerocoin_StartHeight(); } bool GetZerocoinMint(const CBigNum& bnPubcoin, uint256& txHash) { txHash = 0; return zerocoinDB->ReadCoinMint(bnPubcoin, txHash); } bool IsPubcoinInBlockchain(const uint256& hashPubcoin, uint256& txid) { txid = 0; return zerocoinDB->ReadCoinMint(hashPubcoin, txid); } bool IsSerialKnown(const CBigNum& bnSerial) { uint256 txHash = 0; return zerocoinDB->ReadCoinSpend(bnSerial, txHash); } bool IsSerialInBlockchain(const CBigNum& bnSerial, int& nHeightTx) { uint256 txHash = 0; // if not in zerocoinDB then its not in the blockchain if (!zerocoinDB->ReadCoinSpend(bnSerial, txHash)) return false; return IsTransactionInChain(txHash, nHeightTx); } bool IsSerialInBlockchain(const uint256& hashSerial, int& nHeightTx, uint256& txidSpend) { CTransaction tx; return IsSerialInBlockchain(hashSerial, nHeightTx, txidSpend, tx); } bool IsSerialInBlockchain(const uint256& hashSerial, int& nHeightTx, uint256& txidSpend, CTransaction& tx) { txidSpend = 0; // if not in zerocoinDB then its not in the blockchain if (!zerocoinDB->ReadCoinSpend(hashSerial, txidSpend)) return false; return IsTransactionInChain(txidSpend, nHeightTx, tx); } std::string ReindexZerocoinDB() { if (!zerocoinDB->WipeCoins("spends") || !zerocoinDB->WipeCoins("mints")) { return _("Failed to wipe zerocoinDB"); } uiInterface.ShowProgress(_("Reindexing zerocoin database..."), 0); CBlockIndex* pindex = chainActive[Params().Zerocoin_StartHeight()]; std::vector<std::pair<libzerocoin::CoinSpend, uint256> > vSpendInfo; std::vector<std::pair<libzerocoin::PublicCoin, uint256> > vMintInfo; while (pindex) { uiInterface.ShowProgress(_("Reindexing zerocoin database..."), std::max(1, std::min(99, (int)((double)(pindex->nHeight - Params().Zerocoin_StartHeight()) / (double)(chainActive.Height() - Params().Zerocoin_StartHeight()) * 100)))); if (pindex->nHeight % 1000 == 0) LogPrintf("Reindexing zerocoin : block %d...\n", pindex->nHeight); CBlock block; if (!ReadBlockFromDisk(block, pindex)) { return _("Reindexing zerocoin failed"); } for (const CTransaction& tx : block.vtx) { for (unsigned int i = 0; i < tx.vin.size(); i++) { if (tx.IsCoinBase()) break; if (tx.ContainsZerocoins()) { uint256 txid = tx.GetHash(); //Record Serials if (tx.IsZerocoinSpend()) { for (auto& in : tx.vin) { if (!in.scriptSig.IsZerocoinSpend()) continue; libzerocoin::CoinSpend spend = TxInToZerocoinSpend(in); vSpendInfo.push_back(make_pair(spend, txid)); } } //Record mints if (tx.IsZerocoinMint()) { for (auto& out : tx.vout) { if (!out.IsZerocoinMint()) continue; CValidationState state; libzerocoin::PublicCoin coin(Params().Zerocoin_Params(pindex->nHeight < Params().Zerocoin_Block_V2_Start())); TxOutToPublicCoin(out, coin, state); vMintInfo.push_back(make_pair(coin, txid)); } } } } } // Flush the zerocoinDB to disk every 100 blocks if (pindex->nHeight % 100 == 0) { if ((!vSpendInfo.empty() && !zerocoinDB->WriteCoinSpendBatch(vSpendInfo)) || (!vMintInfo.empty() && !zerocoinDB->WriteCoinMintBatch(vMintInfo))) return _("Error writing zerocoinDB to disk"); vSpendInfo.clear(); vMintInfo.clear(); } pindex = chainActive.Next(pindex); } uiInterface.ShowProgress("", 100); // Final flush to disk in case any remaining information exists if ((!vSpendInfo.empty() && !zerocoinDB->WriteCoinSpendBatch(vSpendInfo)) || (!vMintInfo.empty() && !zerocoinDB->WriteCoinMintBatch(vMintInfo))) return _("Error writing zerocoinDB to disk"); uiInterface.ShowProgress("", 100); return ""; } bool RemoveSerialFromDB(const CBigNum& bnSerial) { return zerocoinDB->EraseCoinSpend(bnSerial); } libzerocoin::CoinSpend TxInToZerocoinSpend(const CTxIn& txin) { // extract the CoinSpend from the txin std::vector<char, zero_after_free_allocator<char> > dataTxIn; dataTxIn.insert(dataTxIn.end(), txin.scriptSig.begin() + BIGNUM_SIZE, txin.scriptSig.end()); CDataStream serializedCoinSpend(dataTxIn, SER_NETWORK, PROTOCOL_VERSION); libzerocoin::ZerocoinParams* paramsAccumulator = Params().Zerocoin_Params(chainActive.Height() < Params().Zerocoin_Block_V2_Start()); libzerocoin::CoinSpend spend(Params().Zerocoin_Params(true), paramsAccumulator, serializedCoinSpend); return spend; } bool TxOutToPublicCoin(const CTxOut& txout, libzerocoin::PublicCoin& pubCoin, CValidationState& state) { CBigNum publicZerocoin; vector<unsigned char> vchZeroMint; vchZeroMint.insert(vchZeroMint.end(), txout.scriptPubKey.begin() + SCRIPT_OFFSET, txout.scriptPubKey.begin() + txout.scriptPubKey.size()); publicZerocoin.setvch(vchZeroMint); libzerocoin::CoinDenomination denomination = libzerocoin::AmountToZerocoinDenomination(txout.nValue); LogPrint("zero", "%s ZCPRINT denomination %d pubcoin %s\n", __func__, denomination, publicZerocoin.GetHex()); if (denomination == libzerocoin::ZQ_ERROR) return state.DoS(100, error("TxOutToPublicCoin : txout.nValue is not correct")); libzerocoin::PublicCoin checkPubCoin(Params().Zerocoin_Params(false), publicZerocoin, denomination); pubCoin = checkPubCoin; return true; } //return a list of zerocoin spends contained in a specific block, list may have many denominations std::list<libzerocoin::CoinDenomination> ZerocoinSpendListFromBlock(const CBlock& block, bool fFilterInvalid) { std::list<libzerocoin::CoinDenomination> vSpends; for (const CTransaction& tx : block.vtx) { if (!tx.IsZerocoinSpend()) continue; for (const CTxIn& txin : tx.vin) { if (!txin.scriptSig.IsZerocoinSpend()) continue; if (fFilterInvalid) { libzerocoin::CoinSpend spend = TxInToZerocoinSpend(txin); if (invalid_out::ContainsSerial(spend.getCoinSerialNumber())) continue; } libzerocoin::CoinDenomination c = libzerocoin::IntToZerocoinDenomination(txin.nSequence); vSpends.push_back(c); } } return vSpends; }
[ "ultrapoolcom@gmail.com" ]
ultrapoolcom@gmail.com
bf42945df4785e862813800dc1caa17fd90a010b
51faca0ffd1c452a427e551cd8c528a4ac80fc75
/vg/gg/B.cpp
83ad3921072d2e3f10b365d63a6373d6696d0c56
[]
no_license
xLLLxLLLx/xLLLx
37f4127a34374b27f14fe856d854c9a13a9b2e28
7ec2ddf39d903c0cdfd52268edd44b2ccbe7e73b
refs/heads/master
2020-04-18T16:19:24.099657
2019-11-03T05:11:41
2019-11-03T05:11:41
167,631,326
4
0
null
null
null
null
UTF-8
C++
false
false
572
cpp
#include <bits/stdc++.h> using namespace std; const int N = 1e6 + 10; char lx[N], ll[N]; int main() { scanf("%s%s", lx + 1, ll + 1); int lenx = strlen(lx + 1); int lenl = strlen(ll + 1); int pos = 0, tmp = 0, ans = 0; for(int i = 1; i <= lenl; ++i) { if(ll[i] == '1') { pos ^= 1; } if(lx[i] == '1') { tmp ^= 1; } } if(pos == tmp) { ans++; } for(int i = 2; i <= lenx - lenl + 1; ++i) { if(lx[i - 1] == '1') { tmp ^= 1; } if(lx[i + lenl - 1] == '1') { tmp ^= 1; } if(tmp == pos) { ans++; } } printf("%d\n", ans); return 0; }
[ "2656020973@qq.com" ]
2656020973@qq.com
909cf862f361c44bb0afd3663692ed18c20ec403
233a9c9d99557ce9e54da126c8c7cb813bb051d2
/engine/src/effect/lumaexposure.cpp
3e7f161d74fa582d9543777ce41925f8030e76e7
[]
no_license
maattam/engine
1c512b9bd43257c659489d3ab7b02575689b3ca5
562de4bf2ade38c6bc3ecd7050763f49f7fa7fbb
refs/heads/master
2022-09-29T02:47:08.499123
2014-10-26T08:36:14
2014-10-26T08:36:14
269,517,821
0
0
null
null
null
null
UTF-8
C++
false
false
2,436
cpp
// // Author : Matti Määttä // Summary : // #include "lumaexposure.h" #include "mathelp.h" using namespace Engine; using namespace Engine::Effect; LumaExposure::LumaExposure() : exposure_(), width_(0), height_(0), sampleLevel_(0) { samplePbo_[0] = samplePbo_[1] = 0; writeIndex_ = 1; readIndex_ = 0; } LumaExposure::~LumaExposure() { if(*samplePbo_ != 0) { gl->glDeleteBuffers(2, samplePbo_); } } bool LumaExposure::setInputTexture(GLint textureId, unsigned int width, unsigned int height, GLuint level) { if(width == 0 || height == 0) { return false; } width_ = width; height_ = height; sampleLevel_ = level; if(*samplePbo_ != 0) { gl->glDeleteBuffers(2, samplePbo_); } int pixels = width * height * 4; // Create PBOs gl->glGenBuffers(2, samplePbo_); gl->glBindBuffer(GL_PIXEL_PACK_BUFFER, samplePbo_[0]); gl->glBufferData(GL_PIXEL_PACK_BUFFER, pixels * sizeof(float), nullptr, GL_STREAM_READ); gl->glBindBuffer(GL_PIXEL_PACK_BUFFER, samplePbo_[1]); gl->glBufferData(GL_PIXEL_PACK_BUFFER, pixels * sizeof(float), nullptr, GL_STREAM_READ); return true; } LumaExposure::ResultType LumaExposure::result() { QVector3D sample = sampleTexture(); return calculateExposure(sample); } QVector3D LumaExposure::sampleTexture() { QVector3D result; // Swap pbos each frame writeIndex_ = (writeIndex_ + 1) % 2; readIndex_ = (readIndex_ + 1) % 2; // Read from gpu asynchronously gl->glBindBuffer(GL_PIXEL_PACK_BUFFER, samplePbo_[writeIndex_]); gl->glGetTexImage(GL_TEXTURE_2D, sampleLevel_, GL_RGBA, GL_FLOAT, nullptr); // Read previous frame's data gl->glBindBuffer(GL_PIXEL_PACK_BUFFER, samplePbo_[readIndex_]); float* pixel = static_cast<float*>(gl->glMapBuffer(GL_PIXEL_PACK_BUFFER, GL_READ_ONLY)); if(pixel != nullptr) { result = QVector3D(pixel[0], pixel[1], pixel[2]); gl->glUnmapBuffer(GL_PIXEL_PACK_BUFFER); } gl->glBindBuffer(GL_PIXEL_PACK_BUFFER, 0); return result; } float LumaExposure::calculateExposure(const QVector3D& linearSample) { const float invGamma = 1.0f / 2.2f; const QVector3D rgbToY(0.299f, 0.587f, 0.114f); // RGB to YUV; Y luminance float Y = QVector3D::dotProduct(rgbToY, linearColor(linearSample, invGamma)); exposure_ << Y; return std::exp(-2.5f * exposure_); }
[ "lesetus@gmail.com" ]
lesetus@gmail.com
f79096247c8af8d4f7bac6686442e8b73b64d841
866cd863ad081b89630bc6ae6ae726036af8a60e
/src/qt/bitcoingui.cpp
d3df07f3f5c6cf22ce5e4d7bcf0465166347988c
[ "MIT" ]
permissive
diabloblack/StrayaCash-Core
52022b3fb512ba1ab0078787cf2b590bd586bdd6
31ec3ff33ff261fa4fc23f64115a136364397a15
refs/heads/master
2020-03-22T15:33:00.754318
2019-10-08T20:50:06
2019-10-08T20:50:06
140,260,997
0
0
MIT
2019-10-08T20:50:07
2018-07-09T09:14:19
C++
UTF-8
C++
false
false
51,573
cpp
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2017 The strayacash developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "bitcoingui.h" #include "bitcoinunits.h" #include "clientmodel.h" #include "guiconstants.h" #include "guiutil.h" #include "miner.h" #include "networkstyle.h" #include "notificator.h" #include "openuridialog.h" #include "optionsdialog.h" #include "optionsmodel.h" #include "rpcconsole.h" #include "utilitydialog.h" #ifdef ENABLE_WALLET #include "walletframe.h" #include "walletmodel.h" #endif // ENABLE_WALLET #ifdef Q_OS_MAC #include "macdockiconhandler.h" #endif #include "init.h" #include "masternodelist.h" #include "ui_interface.h" #include "util.h" #include <iostream> #include <QAction> #include <QApplication> #include <QDateTime> #include <QDesktopWidget> #include <QDragEnterEvent> #include <QIcon> #include <QListWidget> #include <QMenuBar> #include <QMessageBox> #include <QMimeData> #include <QProgressBar> #include <QProgressDialog> #include <QSettings> #include <QStackedWidget> #include <QStatusBar> #include <QStyle> #include <QTimer> #include <QToolBar> #include <QVBoxLayout> #if QT_VERSION < 0x050000 #include <QTextDocument> #include <QUrl> #else #include <QUrlQuery> #endif const QString BitcoinGUI::DEFAULT_WALLET = "~Default"; BitcoinGUI::BitcoinGUI(const NetworkStyle* networkStyle, QWidget* parent) : QMainWindow(parent), clientModel(0), walletFrame(0), unitDisplayControl(0), labelStakingIcon(0), labelEncryptionIcon(0), labelConnectionsIcon(0), labelBlocksIcon(0), progressBarLabel(0), progressBar(0), progressDialog(0), appMenuBar(0), overviewAction(0), historyAction(0), masternodeAction(0), quitAction(0), sendCoinsAction(0), usedSendingAddressesAction(0), usedReceivingAddressesAction(0), signMessageAction(0), verifyMessageAction(0), bip38ToolAction(0), aboutAction(0), receiveCoinsAction(0), optionsAction(0), toggleHideAction(0), encryptWalletAction(0), backupWalletAction(0), changePassphraseAction(0), aboutQtAction(0), openRPCConsoleAction(0), openAction(0), showHelpMessageAction(0), multiSendAction(0), trayIcon(0), trayIconMenu(0), notificator(0), rpcConsole(0), prevBlocks(0), spinnerFrame(0) { /* Open CSS when configured */ this->setStyleSheet(GUIUtil::loadStyleSheet()); GUIUtil::restoreWindowGeometry("nWindow", QSize(850, 550), this); QString windowTitle = tr("strayacash") + " - "; #ifdef ENABLE_WALLET /* if compiled with wallet support, -disablewallet can still disable the wallet */ enableWallet = !GetBoolArg("-disablewallet", false); #else enableWallet = false; #endif // ENABLE_WALLET if (enableWallet) { windowTitle += tr("Wallet"); } else { windowTitle += tr("Node"); } QString userWindowTitle = QString::fromStdString(GetArg("-windowtitle", "")); if (!userWindowTitle.isEmpty()) windowTitle += " - " + userWindowTitle; windowTitle += " " + networkStyle->getTitleAddText(); #ifndef Q_OS_MAC QApplication::setWindowIcon(networkStyle->getAppIcon()); setWindowIcon(networkStyle->getAppIcon()); #else MacDockIconHandler::instance()->setIcon(networkStyle->getAppIcon()); #endif setWindowTitle(windowTitle); #if defined(Q_OS_MAC) && QT_VERSION < 0x050000 // This property is not implemented in Qt 5. Setting it has no effect. // A replacement API (QtMacUnifiedToolBar) is available in QtMacExtras. setUnifiedTitleAndToolBarOnMac(true); #endif rpcConsole = new RPCConsole(enableWallet ? this : 0); #ifdef ENABLE_WALLET if (enableWallet) { /** Create wallet frame*/ walletFrame = new WalletFrame(this); } else #endif // ENABLE_WALLET { /* When compiled without wallet or -disablewallet is provided, * the central widget is the rpc console. */ setCentralWidget(rpcConsole); } // Accept D&D of URIs setAcceptDrops(true); // Create actions for the toolbar, menu bar and tray/dock icon // Needs walletFrame to be initialized createActions(networkStyle); // Create application menu bar createMenuBar(); // Create the toolbars createToolBars(); // Create system tray icon and notification createTrayIcon(networkStyle); // Create status bar statusBar(); // Status bar notification icons QFrame* frameBlocks = new QFrame(); frameBlocks->setContentsMargins(0, 0, 0, 0); frameBlocks->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); QHBoxLayout* frameBlocksLayout = new QHBoxLayout(frameBlocks); frameBlocksLayout->setContentsMargins(3, 0, 3, 0); frameBlocksLayout->setSpacing(3); unitDisplayControl = new UnitDisplayStatusBarControl(); labelStakingIcon = new QLabel(); labelEncryptionIcon = new QLabel(); labelConnectionsIcon = new QPushButton(); labelConnectionsIcon->setFlat(true); // Make the button look like a label, but clickable labelConnectionsIcon->setStyleSheet(".QPushButton { background-color: rgba(255, 255, 255, 0);}"); labelConnectionsIcon->setMaximumSize(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE); labelBlocksIcon = new QLabel(); if (enableWallet) { frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(unitDisplayControl); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelEncryptionIcon); } frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelStakingIcon); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelConnectionsIcon); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelBlocksIcon); frameBlocksLayout->addStretch(); // Progress bar and label for blocks download progressBarLabel = new QLabel(); progressBarLabel->setVisible(true); progressBar = new GUIUtil::ProgressBar(); progressBar->setAlignment(Qt::AlignCenter); progressBar->setVisible(true); // Override style sheet for progress bar for styles that have a segmented progress bar, // as they make the text unreadable (workaround for issue #1071) // See https://qt-project.org/doc/qt-4.8/gallery.html QString curStyle = QApplication::style()->metaObject()->className(); if (curStyle == "QWindowsStyle" || curStyle == "QWindowsXPStyle") { progressBar->setStyleSheet("QProgressBar { background-color: #F8F8F8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #00CCFF, stop: 1 #33CCFF); border-radius: 7px; margin: 0px; }"); } statusBar()->addWidget(progressBarLabel); statusBar()->addWidget(progressBar); statusBar()->addPermanentWidget(frameBlocks); // Jump directly to tabs in RPC-console connect(openInfoAction, SIGNAL(triggered()), rpcConsole, SLOT(showInfo())); connect(openRPCConsoleAction, SIGNAL(triggered()), rpcConsole, SLOT(showConsole())); connect(openNetworkAction, SIGNAL(triggered()), rpcConsole, SLOT(showNetwork())); connect(openPeersAction, SIGNAL(triggered()), rpcConsole, SLOT(showPeers())); connect(openRepairAction, SIGNAL(triggered()), rpcConsole, SLOT(showRepair())); connect(openConfEditorAction, SIGNAL(triggered()), rpcConsole, SLOT(showConfEditor())); connect(openMNConfEditorAction, SIGNAL(triggered()), rpcConsole, SLOT(showMNConfEditor())); connect(showBackupsAction, SIGNAL(triggered()), rpcConsole, SLOT(showBackups())); connect(labelConnectionsIcon, SIGNAL(clicked()), rpcConsole, SLOT(showPeers())); // Get restart command-line parameters and handle restart connect(rpcConsole, SIGNAL(handleRestart(QStringList)), this, SLOT(handleRestart(QStringList))); // prevents an open debug window from becoming stuck/unusable on client shutdown connect(quitAction, SIGNAL(triggered()), rpcConsole, SLOT(hide())); // Install event filter to be able to catch status tip events (QEvent::StatusTip) this->installEventFilter(this); // Initially wallet actions should be disabled setWalletActionsEnabled(false); // Subscribe to notifications from core subscribeToCoreSignals(); QTimer* timerStakingIcon = new QTimer(labelStakingIcon); connect(timerStakingIcon, SIGNAL(timeout()), this, SLOT(setStakingStatus())); timerStakingIcon->start(10000); setStakingStatus(); } BitcoinGUI::~BitcoinGUI() { // Unsubscribe from notifications from core unsubscribeFromCoreSignals(); GUIUtil::saveWindowGeometry("nWindow", this); if (trayIcon) // Hide tray icon, as deleting will let it linger until quit (on Ubuntu) trayIcon->hide(); #ifdef Q_OS_MAC delete appMenuBar; MacDockIconHandler::cleanup(); #endif } void BitcoinGUI::createActions(const NetworkStyle* networkStyle) { QActionGroup* tabGroup = new QActionGroup(this); overviewAction = new QAction(QIcon(":/icons/overview"), tr("&Overview"), this); overviewAction->setStatusTip(tr("Show general overview of wallet")); overviewAction->setToolTip(overviewAction->statusTip()); overviewAction->setCheckable(true); #ifdef Q_OS_MAC overviewAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_1)); #else overviewAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_1)); #endif tabGroup->addAction(overviewAction); sendCoinsAction = new QAction(QIcon(":/icons/send"), tr("&Send"), this); sendCoinsAction->setStatusTip(tr("Send coins to a strayacash address")); sendCoinsAction->setToolTip(sendCoinsAction->statusTip()); sendCoinsAction->setCheckable(true); #ifdef Q_OS_MAC sendCoinsAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_2)); #else sendCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_2)); #endif tabGroup->addAction(sendCoinsAction); receiveCoinsAction = new QAction(QIcon(":/icons/receiving_addresses"), tr("&Receive"), this); receiveCoinsAction->setStatusTip(tr("Request payments (generates QR codes and strayacash: URIs)")); receiveCoinsAction->setToolTip(receiveCoinsAction->statusTip()); receiveCoinsAction->setCheckable(true); #ifdef Q_OS_MAC receiveCoinsAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_3)); #else receiveCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_3)); #endif tabGroup->addAction(receiveCoinsAction); historyAction = new QAction(QIcon(":/icons/history"), tr("&Transactions"), this); historyAction->setStatusTip(tr("Browse transaction history")); historyAction->setToolTip(historyAction->statusTip()); historyAction->setCheckable(true); #ifdef Q_OS_MAC historyAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_4)); #else historyAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_4)); #endif tabGroup->addAction(historyAction); #ifdef ENABLE_WALLET QSettings settings; if (settings.value("fShowMasternodesTab").toBool()) { masternodeAction = new QAction(QIcon(":/icons/masternodes"), tr("&Masternodes"), this); masternodeAction->setStatusTip(tr("Browse masternodes")); masternodeAction->setToolTip(masternodeAction->statusTip()); masternodeAction->setCheckable(true); #ifdef Q_OS_MAC masternodeAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_5)); #else masternodeAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_5)); #endif tabGroup->addAction(masternodeAction); connect(masternodeAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(masternodeAction, SIGNAL(triggered()), this, SLOT(gotoMasternodePage())); } // These showNormalIfMinimized are needed because Send Coins and Receive Coins // can be triggered from the tray menu, and need to show the GUI to be useful. connect(overviewAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(overviewAction, SIGNAL(triggered()), this, SLOT(gotoOverviewPage())); connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage())); connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage())); connect(historyAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(historyAction, SIGNAL(triggered()), this, SLOT(gotoHistoryPage())); #endif // ENABLE_WALLET quitAction = new QAction(QIcon(":/icons/quit"), tr("E&xit"), this); quitAction->setStatusTip(tr("Quit application")); quitAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q)); quitAction->setMenuRole(QAction::QuitRole); aboutAction = new QAction(networkStyle->getAppIcon(), tr("&About strayacash"), this); aboutAction->setStatusTip(tr("Show information about strayacash")); aboutAction->setMenuRole(QAction::AboutRole); #if QT_VERSION < 0x050000 aboutQtAction = new QAction(QIcon(":/trolltech/qmessagebox/images/qtlogo-64.png"), tr("About &Qt"), this); #else aboutQtAction = new QAction(QIcon(":/qt-project.org/qmessagebox/images/qtlogo-64.png"), tr("About &Qt"), this); #endif aboutQtAction->setStatusTip(tr("Show information about Qt")); aboutQtAction->setMenuRole(QAction::AboutQtRole); optionsAction = new QAction(QIcon(":/icons/options"), tr("&Options..."), this); optionsAction->setStatusTip(tr("Modify configuration options for strayacash")); optionsAction->setMenuRole(QAction::PreferencesRole); toggleHideAction = new QAction(networkStyle->getAppIcon(), tr("&Show / Hide"), this); toggleHideAction->setStatusTip(tr("Show or hide the main Window")); encryptWalletAction = new QAction(QIcon(":/icons/lock_closed"), tr("&Encrypt Wallet..."), this); encryptWalletAction->setStatusTip(tr("Encrypt the private keys that belong to your wallet")); encryptWalletAction->setCheckable(true); backupWalletAction = new QAction(QIcon(":/icons/filesave"), tr("&Backup Wallet..."), this); backupWalletAction->setStatusTip(tr("Backup wallet to another location")); changePassphraseAction = new QAction(QIcon(":/icons/key"), tr("&Change Passphrase..."), this); changePassphraseAction->setStatusTip(tr("Change the passphrase used for wallet encryption")); unlockWalletAction = new QAction(tr("&Unlock Wallet..."), this); unlockWalletAction->setToolTip(tr("Unlock wallet")); lockWalletAction = new QAction(tr("&Lock Wallet"), this); signMessageAction = new QAction(QIcon(":/icons/edit"), tr("Sign &message..."), this); signMessageAction->setStatusTip(tr("Sign messages with your strayacash addresses to prove you own them")); verifyMessageAction = new QAction(QIcon(":/icons/transaction_0"), tr("&Verify message..."), this); verifyMessageAction->setStatusTip(tr("Verify messages to ensure they were signed with specified strayacash addresses")); bip38ToolAction = new QAction(QIcon(":/icons/key"), tr("&BIP38 tool"), this); bip38ToolAction->setToolTip(tr("Encrypt and decrypt private keys using a passphrase")); multiSendAction = new QAction(QIcon(":/icons/edit"), tr("&MultiSend"), this); multiSendAction->setToolTip(tr("MultiSend Settings")); multiSendAction->setCheckable(true); openInfoAction = new QAction(QApplication::style()->standardIcon(QStyle::SP_MessageBoxInformation), tr("&Information"), this); openInfoAction->setStatusTip(tr("Show diagnostic information")); openRPCConsoleAction = new QAction(QIcon(":/icons/debugwindow"), tr("&Debug console"), this); openRPCConsoleAction->setStatusTip(tr("Open debugging console")); openNetworkAction = new QAction(QIcon(":/icons/connect_4"), tr("&Network Monitor"), this); openNetworkAction->setStatusTip(tr("Show network monitor")); openPeersAction = new QAction(QIcon(":/icons/connect_4"), tr("&Peers list"), this); openPeersAction->setStatusTip(tr("Show peers info")); openRepairAction = new QAction(QIcon(":/icons/options"), tr("Wallet &Repair"), this); openRepairAction->setStatusTip(tr("Show wallet repair options")); openConfEditorAction = new QAction(QIcon(":/icons/edit"), tr("Open Wallet &Configuration File"), this); openConfEditorAction->setStatusTip(tr("Open configuration file")); openMNConfEditorAction = new QAction(QIcon(":/icons/edit"), tr("Open &Masternode Configuration File"), this); openMNConfEditorAction->setStatusTip(tr("Open Masternode configuration file")); showBackupsAction = new QAction(QIcon(":/icons/browse"), tr("Show Automatic &Backups"), this); showBackupsAction->setStatusTip(tr("Show automatically created wallet backups")); usedSendingAddressesAction = new QAction(QIcon(":/icons/address-book"), tr("&Sending addresses..."), this); usedSendingAddressesAction->setStatusTip(tr("Show the list of used sending addresses and labels")); usedReceivingAddressesAction = new QAction(QIcon(":/icons/address-book"), tr("&Receiving addresses..."), this); usedReceivingAddressesAction->setStatusTip(tr("Show the list of used receiving addresses and labels")); openAction = new QAction(QApplication::style()->standardIcon(QStyle::SP_FileIcon), tr("Open &URI..."), this); openAction->setStatusTip(tr("Open a strayacash: URI or payment request")); showHelpMessageAction = new QAction(QApplication::style()->standardIcon(QStyle::SP_MessageBoxInformation), tr("&Command-line options"), this); showHelpMessageAction->setMenuRole(QAction::NoRole); showHelpMessageAction->setStatusTip(tr("Show the strayacash help message to get a list with possible strayacash command-line options")); connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit())); connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutClicked())); connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt())); connect(optionsAction, SIGNAL(triggered()), this, SLOT(optionsClicked())); connect(toggleHideAction, SIGNAL(triggered()), this, SLOT(toggleHidden())); connect(showHelpMessageAction, SIGNAL(triggered()), this, SLOT(showHelpMessageClicked())); #ifdef ENABLE_WALLET if (walletFrame) { connect(encryptWalletAction, SIGNAL(triggered(bool)), walletFrame, SLOT(encryptWallet(bool))); connect(backupWalletAction, SIGNAL(triggered()), walletFrame, SLOT(backupWallet())); connect(changePassphraseAction, SIGNAL(triggered()), walletFrame, SLOT(changePassphrase())); connect(unlockWalletAction, SIGNAL(triggered()), walletFrame, SLOT(unlockWallet())); connect(lockWalletAction, SIGNAL(triggered()), walletFrame, SLOT(lockWallet())); connect(signMessageAction, SIGNAL(triggered()), this, SLOT(gotoSignMessageTab())); connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(gotoVerifyMessageTab())); connect(bip38ToolAction, SIGNAL(triggered()), this, SLOT(gotoBip38Tool())); connect(usedSendingAddressesAction, SIGNAL(triggered()), walletFrame, SLOT(usedSendingAddresses())); connect(usedReceivingAddressesAction, SIGNAL(triggered()), walletFrame, SLOT(usedReceivingAddresses())); connect(openAction, SIGNAL(triggered()), this, SLOT(openClicked())); connect(multiSendAction, SIGNAL(triggered()), this, SLOT(gotoMultiSendDialog())); } #endif // ENABLE_WALLET } void BitcoinGUI::createMenuBar() { #ifdef Q_OS_MAC // Create a decoupled menu bar on Mac which stays even if the window is closed appMenuBar = new QMenuBar(); #else // Get the main window's menu bar on other platforms appMenuBar = menuBar(); #endif // Configure the menus QMenu* file = appMenuBar->addMenu(tr("&File")); if (walletFrame) { file->addAction(openAction); file->addAction(backupWalletAction); file->addAction(signMessageAction); file->addAction(verifyMessageAction); file->addSeparator(); file->addAction(usedSendingAddressesAction); file->addAction(usedReceivingAddressesAction); file->addSeparator(); } file->addAction(quitAction); QMenu* settings = appMenuBar->addMenu(tr("&Settings")); if (walletFrame) { settings->addAction(encryptWalletAction); settings->addAction(changePassphraseAction); settings->addAction(unlockWalletAction); settings->addAction(lockWalletAction); settings->addAction(bip38ToolAction); settings->addAction(multiSendAction); settings->addSeparator(); } settings->addAction(optionsAction); if (walletFrame) { QMenu* tools = appMenuBar->addMenu(tr("&Tools")); tools->addAction(openInfoAction); tools->addAction(openRPCConsoleAction); tools->addAction(openNetworkAction); tools->addAction(openPeersAction); tools->addAction(openRepairAction); tools->addSeparator(); tools->addAction(openConfEditorAction); tools->addAction(openMNConfEditorAction); tools->addAction(showBackupsAction); } QMenu* help = appMenuBar->addMenu(tr("&Help")); help->addAction(showHelpMessageAction); help->addSeparator(); help->addAction(aboutAction); help->addAction(aboutQtAction); } void BitcoinGUI::createToolBars() { if (walletFrame) { QToolBar* toolbar = new QToolBar(tr("Tabs toolbar")); toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); toolbar->addAction(overviewAction); toolbar->addAction(sendCoinsAction); toolbar->addAction(receiveCoinsAction); toolbar->addAction(historyAction); QSettings settings; if (settings.value("fShowMasternodesTab").toBool()) { toolbar->addAction(masternodeAction); } toolbar->setMovable(false); // remove unused icon in upper left corner overviewAction->setChecked(true); /** Create additional container for toolbar and walletFrame and make it the central widget. This is a workaround mostly for toolbar styling on Mac OS but should work fine for every other OSes too. */ QVBoxLayout* layout = new QVBoxLayout; layout->addWidget(toolbar); layout->addWidget(walletFrame); layout->setSpacing(0); layout->setContentsMargins(QMargins()); QWidget* containerWidget = new QWidget(); containerWidget->setLayout(layout); setCentralWidget(containerWidget); } } void BitcoinGUI::setClientModel(ClientModel* clientModel) { this->clientModel = clientModel; if (clientModel) { // Create system tray menu (or setup the dock menu) that late to prevent users from calling actions, // while the client has not yet fully loaded createTrayIconMenu(); // Keep up to date with client setNumConnections(clientModel->getNumConnections()); connect(clientModel, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int))); setNumBlocks(clientModel->getNumBlocks()); connect(clientModel, SIGNAL(numBlocksChanged(int)), this, SLOT(setNumBlocks(int))); // Receive and report messages from client model connect(clientModel, SIGNAL(message(QString, QString, unsigned int)), this, SLOT(message(QString, QString, unsigned int))); // Show progress dialog connect(clientModel, SIGNAL(showProgress(QString, int)), this, SLOT(showProgress(QString, int))); rpcConsole->setClientModel(clientModel); #ifdef ENABLE_WALLET if (walletFrame) { walletFrame->setClientModel(clientModel); } #endif // ENABLE_WALLET unitDisplayControl->setOptionsModel(clientModel->getOptionsModel()); } else { // Disable possibility to show main window via action toggleHideAction->setEnabled(false); if (trayIconMenu) { // Disable context menu on tray icon trayIconMenu->clear(); } } } #ifdef ENABLE_WALLET bool BitcoinGUI::addWallet(const QString& name, WalletModel* walletModel) { if (!walletFrame) return false; setWalletActionsEnabled(true); return walletFrame->addWallet(name, walletModel); } bool BitcoinGUI::setCurrentWallet(const QString& name) { if (!walletFrame) return false; return walletFrame->setCurrentWallet(name); } void BitcoinGUI::removeAllWallets() { if (!walletFrame) return; setWalletActionsEnabled(false); walletFrame->removeAllWallets(); } #endif // ENABLE_WALLET void BitcoinGUI::setWalletActionsEnabled(bool enabled) { overviewAction->setEnabled(enabled); sendCoinsAction->setEnabled(enabled); receiveCoinsAction->setEnabled(enabled); historyAction->setEnabled(enabled); QSettings settings; if (settings.value("fShowMasternodesTab").toBool()) { masternodeAction->setEnabled(enabled); } encryptWalletAction->setEnabled(enabled); backupWalletAction->setEnabled(enabled); changePassphraseAction->setEnabled(enabled); signMessageAction->setEnabled(enabled); verifyMessageAction->setEnabled(enabled); bip38ToolAction->setEnabled(enabled); usedSendingAddressesAction->setEnabled(enabled); usedReceivingAddressesAction->setEnabled(enabled); openAction->setEnabled(enabled); } void BitcoinGUI::createTrayIcon(const NetworkStyle* networkStyle) { #ifndef Q_OS_MAC trayIcon = new QSystemTrayIcon(this); QString toolTip = tr("strayacash client") + " " + networkStyle->getTitleAddText(); trayIcon->setToolTip(toolTip); trayIcon->setIcon(networkStyle->getAppIcon()); trayIcon->show(); #endif notificator = new Notificator(QApplication::applicationName(), trayIcon, this); } void BitcoinGUI::createTrayIconMenu() { #ifndef Q_OS_MAC // return if trayIcon is unset (only on non-Mac OSes) if (!trayIcon) return; trayIconMenu = new QMenu(this); trayIcon->setContextMenu(trayIconMenu); connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason))); #else // Note: On Mac, the dock icon is used to provide the tray's functionality. MacDockIconHandler* dockIconHandler = MacDockIconHandler::instance(); dockIconHandler->setMainWindow((QMainWindow*)this); trayIconMenu = dockIconHandler->dockMenu(); #endif // Configuration of the tray icon (or dock icon) icon menu trayIconMenu->addAction(toggleHideAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(sendCoinsAction); trayIconMenu->addAction(receiveCoinsAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(signMessageAction); trayIconMenu->addAction(verifyMessageAction); trayIconMenu->addAction(bip38ToolAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(optionsAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(openInfoAction); trayIconMenu->addAction(openRPCConsoleAction); trayIconMenu->addAction(openNetworkAction); trayIconMenu->addAction(openPeersAction); trayIconMenu->addAction(openRepairAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(openConfEditorAction); trayIconMenu->addAction(openMNConfEditorAction); trayIconMenu->addAction(showBackupsAction); #ifndef Q_OS_MAC // This is built-in on Mac trayIconMenu->addSeparator(); trayIconMenu->addAction(quitAction); #endif } #ifndef Q_OS_MAC void BitcoinGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason) { if (reason == QSystemTrayIcon::Trigger) { // Click on system tray icon triggers show/hide of the main window toggleHidden(); } } #endif void BitcoinGUI::optionsClicked() { if (!clientModel || !clientModel->getOptionsModel()) return; OptionsDialog dlg(this, enableWallet); dlg.setModel(clientModel->getOptionsModel()); dlg.exec(); } void BitcoinGUI::aboutClicked() { if (!clientModel) return; HelpMessageDialog dlg(this, true); dlg.exec(); } void BitcoinGUI::showHelpMessageClicked() { HelpMessageDialog* help = new HelpMessageDialog(this, false); help->setAttribute(Qt::WA_DeleteOnClose); help->show(); } #ifdef ENABLE_WALLET void BitcoinGUI::openClicked() { OpenURIDialog dlg(this); if (dlg.exec()) { emit receivedURI(dlg.getURI()); } } void BitcoinGUI::gotoOverviewPage() { overviewAction->setChecked(true); if (walletFrame) walletFrame->gotoOverviewPage(); } void BitcoinGUI::gotoHistoryPage() { historyAction->setChecked(true); if (walletFrame) walletFrame->gotoHistoryPage(); } void BitcoinGUI::gotoMasternodePage() { QSettings settings; if (settings.value("fShowMasternodesTab").toBool()) { masternodeAction->setChecked(true); if (walletFrame) walletFrame->gotoMasternodePage(); } } void BitcoinGUI::gotoReceiveCoinsPage() { receiveCoinsAction->setChecked(true); if (walletFrame) walletFrame->gotoReceiveCoinsPage(); } void BitcoinGUI::gotoSendCoinsPage(QString addr) { sendCoinsAction->setChecked(true); if (walletFrame) walletFrame->gotoSendCoinsPage(addr); } void BitcoinGUI::gotoSignMessageTab(QString addr) { if (walletFrame) walletFrame->gotoSignMessageTab(addr); } void BitcoinGUI::gotoVerifyMessageTab(QString addr) { if (walletFrame) walletFrame->gotoVerifyMessageTab(addr); } void BitcoinGUI::gotoBip38Tool() { if (walletFrame) walletFrame->gotoBip38Tool(); } void BitcoinGUI::gotoMultiSendDialog() { multiSendAction->setChecked(true); if (walletFrame) walletFrame->gotoMultiSendDialog(); } #endif // ENABLE_WALLET void BitcoinGUI::setNumConnections(int count) { QString icon; switch (count) { case 0: icon = ":/icons/connect_0"; break; case 1: case 2: case 3: icon = ":/icons/connect_1"; break; case 4: case 5: case 6: icon = ":/icons/connect_2"; break; case 7: case 8: case 9: icon = ":/icons/connect_3"; break; default: icon = ":/icons/connect_4"; break; } QIcon connectionItem = QIcon(icon).pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE); labelConnectionsIcon->setIcon(connectionItem); labelConnectionsIcon->setToolTip(tr("%n active connection(s) to strayacash network", "", count)); } void BitcoinGUI::setNumBlocks(int count) { if (!clientModel) return; // Prevent orphan statusbar messages (e.g. hover Quit in main menu, wait until chain-sync starts -> garbelled text) statusBar()->clearMessage(); // Acquire current block source enum BlockSource blockSource = clientModel->getBlockSource(); switch (blockSource) { case BLOCK_SOURCE_NETWORK: progressBarLabel->setText(tr("Synchronizing with network...")); break; case BLOCK_SOURCE_DISK: progressBarLabel->setText(tr("Importing blocks from disk...")); break; case BLOCK_SOURCE_REINDEX: progressBarLabel->setText(tr("Reindexing blocks on disk...")); break; case BLOCK_SOURCE_NONE: // Case: not Importing, not Reindexing and no network connection progressBarLabel->setText(tr("No block source available...")); break; } QString tooltip; QDateTime lastBlockDate = clientModel->getLastBlockDate(); QDateTime currentDate = QDateTime::currentDateTime(); int secs = lastBlockDate.secsTo(currentDate); tooltip = tr("Processed %n blocks of transaction history.", "", count); // Set icon state: spinning if catching up, tick otherwise // if(secs < 25*60) // 90*60 for bitcoin but we are 4x times faster if (masternodeSync.IsBlockchainSynced()) { QString strSyncStatus; tooltip = tr("Up to date") + QString(".<br>") + tooltip; if (masternodeSync.IsSynced()) { progressBarLabel->setVisible(false); progressBar->setVisible(false); labelBlocksIcon->setPixmap(QIcon(":/icons/synced").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE)); } else { int nAttempt; int progress = 0; labelBlocksIcon->setPixmap(QIcon(QString( ":/movies/spinner-%1") .arg(spinnerFrame, 3, 10, QChar('0'))) .pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE)); spinnerFrame = (spinnerFrame + 1) % SPINNER_FRAMES; #ifdef ENABLE_WALLET if (walletFrame) walletFrame->showOutOfSyncWarning(false); #endif // ENABLE_WALLET nAttempt = masternodeSync.RequestedMasternodeAttempt < MASTERNODE_SYNC_THRESHOLD ? masternodeSync.RequestedMasternodeAttempt + 1 : MASTERNODE_SYNC_THRESHOLD; progress = nAttempt + (masternodeSync.RequestedMasternodeAssets - 1) * MASTERNODE_SYNC_THRESHOLD; progressBar->setMaximum(4 * MASTERNODE_SYNC_THRESHOLD); progressBar->setFormat(tr("Synchronizing additional data: %p%")); progressBar->setValue(progress); } strSyncStatus = QString(masternodeSync.GetSyncStatus().c_str()); progressBarLabel->setText(strSyncStatus); tooltip = strSyncStatus + QString("<br>") + tooltip; } else { // Represent time from last generated block in human readable text QString timeBehindText; const int HOUR_IN_SECONDS = 60 * 60; const int DAY_IN_SECONDS = 24 * 60 * 60; const int WEEK_IN_SECONDS = 7 * 24 * 60 * 60; const int YEAR_IN_SECONDS = 31556952; // Average length of year in Gregorian calendar if (secs < 2 * DAY_IN_SECONDS) { timeBehindText = tr("%n hour(s)", "", secs / HOUR_IN_SECONDS); } else if (secs < 2 * WEEK_IN_SECONDS) { timeBehindText = tr("%n day(s)", "", secs / DAY_IN_SECONDS); } else if (secs < YEAR_IN_SECONDS) { timeBehindText = tr("%n week(s)", "", secs / WEEK_IN_SECONDS); } else { int years = secs / YEAR_IN_SECONDS; int remainder = secs % YEAR_IN_SECONDS; timeBehindText = tr("%1 and %2").arg(tr("%n year(s)", "", years)).arg(tr("%n week(s)", "", remainder / WEEK_IN_SECONDS)); } progressBarLabel->setVisible(true); progressBar->setFormat(tr("%1 behind").arg(timeBehindText)); progressBar->setMaximum(1000000000); progressBar->setValue(clientModel->getVerificationProgress() * 1000000000.0 + 0.5); progressBar->setVisible(true); tooltip = tr("Catching up...") + QString("<br>") + tooltip; if (count != prevBlocks) { labelBlocksIcon->setPixmap(QIcon(QString( ":/movies/spinner-%1") .arg(spinnerFrame, 3, 10, QChar('0'))) .pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE)); spinnerFrame = (spinnerFrame + 1) % SPINNER_FRAMES; } prevBlocks = count; #ifdef ENABLE_WALLET if (walletFrame) walletFrame->showOutOfSyncWarning(true); #endif // ENABLE_WALLET tooltip += QString("<br>"); tooltip += tr("Last received block was generated %1 ago.").arg(timeBehindText); tooltip += QString("<br>"); tooltip += tr("Transactions after this will not yet be visible."); } // Don't word-wrap this (fixed-width) tooltip tooltip = QString("<nobr>") + tooltip + QString("</nobr>"); labelBlocksIcon->setToolTip(tooltip); progressBarLabel->setToolTip(tooltip); progressBar->setToolTip(tooltip); } void BitcoinGUI::message(const QString& title, const QString& message, unsigned int style, bool* ret) { QString strTitle = tr("strayacash"); // default title // Default to information icon int nMBoxIcon = QMessageBox::Information; int nNotifyIcon = Notificator::Information; QString msgType; // Prefer supplied title over style based title if (!title.isEmpty()) { msgType = title; } else { switch (style) { case CClientUIInterface::MSG_ERROR: msgType = tr("Error"); break; case CClientUIInterface::MSG_WARNING: msgType = tr("Warning"); break; case CClientUIInterface::MSG_INFORMATION: msgType = tr("Information"); break; default: break; } } // Append title to "strayacash - " if (!msgType.isEmpty()) strTitle += " - " + msgType; // Check for error/warning icon if (style & CClientUIInterface::ICON_ERROR) { nMBoxIcon = QMessageBox::Critical; nNotifyIcon = Notificator::Critical; } else if (style & CClientUIInterface::ICON_WARNING) { nMBoxIcon = QMessageBox::Warning; nNotifyIcon = Notificator::Warning; } // Display message if (style & CClientUIInterface::MODAL) { // Check for buttons, use OK as default, if none was supplied QMessageBox::StandardButton buttons; if (!(buttons = (QMessageBox::StandardButton)(style & CClientUIInterface::BTN_MASK))) buttons = QMessageBox::Ok; showNormalIfMinimized(); QMessageBox mBox((QMessageBox::Icon)nMBoxIcon, strTitle, message, buttons, this); int r = mBox.exec(); if (ret != NULL) *ret = r == QMessageBox::Ok; } else notificator->notify((Notificator::Class)nNotifyIcon, strTitle, message); } void BitcoinGUI::changeEvent(QEvent* e) { QMainWindow::changeEvent(e); #ifndef Q_OS_MAC // Ignored on Mac if (e->type() == QEvent::WindowStateChange) { if (clientModel && clientModel->getOptionsModel() && clientModel->getOptionsModel()->getMinimizeToTray()) { QWindowStateChangeEvent* wsevt = static_cast<QWindowStateChangeEvent*>(e); if (!(wsevt->oldState() & Qt::WindowMinimized) && isMinimized()) { QTimer::singleShot(0, this, SLOT(hide())); e->ignore(); } } } #endif } void BitcoinGUI::closeEvent(QCloseEvent* event) { #ifndef Q_OS_MAC // Ignored on Mac if (clientModel && clientModel->getOptionsModel()) { if (!clientModel->getOptionsModel()->getMinimizeOnClose()) { QApplication::quit(); } } #endif QMainWindow::closeEvent(event); } #ifdef ENABLE_WALLET void BitcoinGUI::incomingTransaction(const QString& date, int unit, const CAmount& amount, const QString& type, const QString& address) { // On new transaction, make an info balloon message((amount) < 0 ? (pwalletMain->fMultiSendNotify == true ? tr("Sent MultiSend transaction") : tr("Sent transaction")) : tr("Incoming transaction"), tr("Date: %1\n" "Amount: %2\n" "Type: %3\n" "Address: %4\n") .arg(date) .arg(BitcoinUnits::formatWithUnit(unit, amount, true)) .arg(type) .arg(address), CClientUIInterface::MSG_INFORMATION); pwalletMain->fMultiSendNotify = false; } #endif // ENABLE_WALLET void BitcoinGUI::dragEnterEvent(QDragEnterEvent* event) { // Accept only URIs if (event->mimeData()->hasUrls()) event->acceptProposedAction(); } void BitcoinGUI::dropEvent(QDropEvent* event) { if (event->mimeData()->hasUrls()) { foreach (const QUrl& uri, event->mimeData()->urls()) { emit receivedURI(uri.toString()); } } event->acceptProposedAction(); } bool BitcoinGUI::eventFilter(QObject* object, QEvent* event) { // Catch status tip events if (event->type() == QEvent::StatusTip) { // Prevent adding text from setStatusTip(), if we currently use the status bar for displaying other stuff if (progressBarLabel->isVisible() || progressBar->isVisible()) return true; } return QMainWindow::eventFilter(object, event); } void BitcoinGUI::setStakingStatus() { if (pwalletMain) fMultiSend = pwalletMain->isMultiSendEnabled(); if (nLastCoinStakeSearchInterval) { labelStakingIcon->show(); labelStakingIcon->setPixmap(QIcon(":/icons/staking_active").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE)); labelStakingIcon->setToolTip(tr("Staking is active\n MultiSend: %1").arg(fMultiSend ? tr("Active") : tr("Not Active"))); } else { labelStakingIcon->show(); labelStakingIcon->setPixmap(QIcon(":/icons/staking_inactive").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE)); labelStakingIcon->setToolTip(tr("Staking is not active\n MultiSend: %1").arg(fMultiSend ? tr("Active") : tr("Not Active"))); } } #ifdef ENABLE_WALLET bool BitcoinGUI::handlePaymentRequest(const SendCoinsRecipient& recipient) { // URI has to be valid if (walletFrame && walletFrame->handlePaymentRequest(recipient)) { showNormalIfMinimized(); gotoSendCoinsPage(); return true; } return false; } void BitcoinGUI::setEncryptionStatus(int status) { switch (status) { case WalletModel::Unencrypted: labelEncryptionIcon->hide(); encryptWalletAction->setChecked(false); changePassphraseAction->setEnabled(false); unlockWalletAction->setVisible(false); lockWalletAction->setVisible(false); encryptWalletAction->setEnabled(true); break; case WalletModel::Unlocked: labelEncryptionIcon->show(); labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_open").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE)); labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b>")); encryptWalletAction->setChecked(true); changePassphraseAction->setEnabled(true); unlockWalletAction->setVisible(false); lockWalletAction->setVisible(true); encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported break; case WalletModel::UnlockedForAnonymizationOnly: labelEncryptionIcon->show(); labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_open").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE)); labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b> for anonimization and staking only")); encryptWalletAction->setChecked(true); changePassphraseAction->setEnabled(true); unlockWalletAction->setVisible(true); lockWalletAction->setVisible(true); encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported break; case WalletModel::Locked: labelEncryptionIcon->show(); labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_closed").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE)); labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>locked</b>")); encryptWalletAction->setChecked(true); changePassphraseAction->setEnabled(true); unlockWalletAction->setVisible(true); lockWalletAction->setVisible(false); encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported break; } } #endif // ENABLE_WALLET void BitcoinGUI::showNormalIfMinimized(bool fToggleHidden) { if (!clientModel) return; // activateWindow() (sometimes) helps with keyboard focus on Windows if (isHidden()) { show(); activateWindow(); } else if (isMinimized()) { showNormal(); activateWindow(); } else if (GUIUtil::isObscured(this)) { raise(); activateWindow(); } else if (fToggleHidden) hide(); } void BitcoinGUI::toggleHidden() { showNormalIfMinimized(true); } void BitcoinGUI::detectShutdown() { if (ShutdownRequested()) { if (rpcConsole) rpcConsole->hide(); qApp->quit(); } } void BitcoinGUI::showProgress(const QString& title, int nProgress) { if (nProgress == 0) { progressDialog = new QProgressDialog(title, "", 0, 100); progressDialog->setWindowModality(Qt::ApplicationModal); progressDialog->setMinimumDuration(0); progressDialog->setCancelButton(0); progressDialog->setAutoClose(false); progressDialog->setValue(0); } else if (nProgress == 100) { if (progressDialog) { progressDialog->close(); progressDialog->deleteLater(); } } else if (progressDialog) progressDialog->setValue(nProgress); } static bool ThreadSafeMessageBox(BitcoinGUI* gui, const std::string& message, const std::string& caption, unsigned int style) { bool modal = (style & CClientUIInterface::MODAL); // The SECURE flag has no effect in the Qt GUI. // bool secure = (style & CClientUIInterface::SECURE); style &= ~CClientUIInterface::SECURE; bool ret = false; // In case of modal message, use blocking connection to wait for user to click a button QMetaObject::invokeMethod(gui, "message", modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(caption)), Q_ARG(QString, QString::fromStdString(message)), Q_ARG(unsigned int, style), Q_ARG(bool*, &ret)); return ret; } void BitcoinGUI::subscribeToCoreSignals() { // Connect signals to client uiInterface.ThreadSafeMessageBox.connect(boost::bind(ThreadSafeMessageBox, this, _1, _2, _3)); } void BitcoinGUI::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.ThreadSafeMessageBox.disconnect(boost::bind(ThreadSafeMessageBox, this, _1, _2, _3)); } /** Get restart command-line parameters and request restart */ void BitcoinGUI::handleRestart(QStringList args) { if (!ShutdownRequested()) emit requestedRestart(args); } UnitDisplayStatusBarControl::UnitDisplayStatusBarControl() : optionsModel(0), menu(0) { createContextMenu(); setToolTip(tr("Unit to show amounts in. Click to select another unit.")); } /** So that it responds to button clicks */ void UnitDisplayStatusBarControl::mousePressEvent(QMouseEvent* event) { onDisplayUnitsClicked(event->pos()); } /** Creates context menu, its actions, and wires up all the relevant signals for mouse events. */ void UnitDisplayStatusBarControl::createContextMenu() { menu = new QMenu(); foreach (BitcoinUnits::Unit u, BitcoinUnits::availableUnits()) { QAction* menuAction = new QAction(QString(BitcoinUnits::name(u)), this); menuAction->setData(QVariant(u)); menu->addAction(menuAction); } connect(menu, SIGNAL(triggered(QAction*)), this, SLOT(onMenuSelection(QAction*))); } /** Lets the control know about the Options Model (and its signals) */ void UnitDisplayStatusBarControl::setOptionsModel(OptionsModel* optionsModel) { if (optionsModel) { this->optionsModel = optionsModel; // be aware of a display unit change reported by the OptionsModel object. connect(optionsModel, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit(int))); // initialize the display units label with the current value in the model. updateDisplayUnit(optionsModel->getDisplayUnit()); } } /** When Display Units are changed on OptionsModel it will refresh the display text of the control on the status bar */ void UnitDisplayStatusBarControl::updateDisplayUnit(int newUnits) { if (Params().NetworkID() == CBaseChainParams::MAIN) { setPixmap(QIcon(":/icons/unit_" + BitcoinUnits::id(newUnits)).pixmap(39, STATUSBAR_ICONSIZE)); } else { setPixmap(QIcon(":/icons/unit_t" + BitcoinUnits::id(newUnits)).pixmap(39, STATUSBAR_ICONSIZE)); } } /** Shows context menu with Display Unit options by the mouse coordinates */ void UnitDisplayStatusBarControl::onDisplayUnitsClicked(const QPoint& point) { QPoint globalPos = mapToGlobal(point); menu->exec(globalPos); } /** Tells underlying optionsModel to update its current display unit. */ void UnitDisplayStatusBarControl::onMenuSelection(QAction* action) { if (action) { optionsModel->setDisplayUnit(action->data()); } }
[ "david@adelaidecreative.com.au" ]
david@adelaidecreative.com.au
4f2063d1aad014f91d518da2b9e1f1486c9327d2
d7caf4d6fd5d4e5d442c1742708e69061cb3e789
/VUobjprog3 su vector/main.cpp
b007e6da8cd6557566043e523203b78589a90278
[]
no_license
rokas28/vector
6f3aed85773f9c171238c00b3df194c4e963207c
54b9db8b0ff8934dd115f6bdb0f1f583e4bd677f
refs/heads/master
2020-05-20T07:59:54.383866
2019-05-22T13:23:50
2019-05-22T13:23:50
185,463,745
0
0
null
null
null
null
UTF-8
C++
false
false
3,098
cpp
#include "headers/main_header.h" #include "headers/studentas.h" #include "headers/zmogus.h" int main() { vector<Studentas> stud; vector<Studentas> vargsiukaii; std::chrono::time_point<std::chrono::high_resolution_clock> start, end; std::chrono::duration<float> duration; int ilgVar = 0; int ilgPav = 0; static const int N = 100000; fileGenerate(N); start_c(start); std::vector<Studentas> stud1; std::vector<Studentas> vargsiukaii1; failoSkaitymas(stud1,ilgVar,ilgPav,N); end_c(end); std::chrono::duration<double> time5 = end-start; cout << "Irasymas i std::vector uztruko " << time5.count() << "sec" << endl; //ailoSkaitymas(stud,ilgVar,ilgPav,N); start_c(start); skirstymas(stud1,vargsiukaii1,N); //vargsiukaii = vargsiukai(stud); end_c(end); std::chrono::duration<double> time6 = end-start; cout << "std::vector rusiavimas uztruko " << time6.count() << "sec" << endl; start_c(start); isvedimas(stud1,vargsiukaii1,ilgVar,ilgPav); end_c(end); std::chrono::duration<double> time7 = end-start; cout << "std::vector isvedimas uztruko " << time7.count() << "sec" << endl << endl; stud1.resize(1); std::chrono::time_point<std::chrono::high_resolution_clock> start1, end1; std::chrono::duration<float> duration1; unsigned int sz = 100000; int n = 0; start1 = std::chrono::high_resolution_clock::now(); std::vector<int> b; for (int i = 1; i <= sz; ++i){ if(b.capacity() == b.size()){ n++; } b.push_back(i); } end1 = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> time10 = end1-start1; cout << "std::vector uztruko su int tipo duomenimis " << time10.count() << "sec" << endl; cout << "std::vector perskirste kartu: " << n << endl; cout << endl << endl; failoSkaitymas(stud,ilgVar,ilgPav,N); end_c(end); std::chrono::duration<double> time1 = end-start; cout << "Irasymas i vec::vector uztruko " << time1.count() << "sec" << endl; //failoSkaitymas(stud,ilgVar,ilgPav,N); start_c(start); skirstymas(stud,vargsiukaii,N); //vargsiukaii = vargsiukai(stud); end_c(end); std::chrono::duration<double> time2 = end-start; cout << "vec::vector rusiavimas uztruko " << time2.count() << "sec" << endl; start_c(start); isvedimas(stud,vargsiukaii,ilgVar,ilgPav); end_c(end); std::chrono::duration<double> time3 = end-start; cout << "vec::vector isvedimas uztruko " << time3.count() << "sec" << endl; cout << endl; n = 0; start1 = std::chrono::high_resolution_clock::now(); vec::vector<int> a; for (int i = 1; i <= sz; i++){ if(a.capacity() == a.size()){ n++; } a.push_back(i); } end1 = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> time9 = end1-start1; cout << "vec::vector uztruko su int tipo duomenimis " << time9.count() << "sec" << endl; cout << "vec::vector perskirste kartu: " << n << endl; return 0; }
[ "rokas.tamulevicius28@gmail.com" ]
rokas.tamulevicius28@gmail.com
39cfc114e9d4e1d2533af722f8fb385836efc1d2
bf28b4c936056f77ed416636a5f8b2e946e3d6f0
/Source - Juan Rodriguez/Battleship - Juan Rodriguez/main.cpp
185c303db002bebdec44a5b735449b48c7d71fc1
[]
no_license
timrodz/cpp-Battleships
59d2db455b53e688cf2e30f7f05590dd87929b05
d8b0289cf79031355916d1e951a94ef6544436e4
refs/heads/master
2021-05-30T21:10:05.683399
2015-11-10T05:12:14
2015-11-10T05:12:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,491
cpp
// // Bachelor of Software Engineering // Media Design School // Auckland // New Zealand // // (c) 2005 - 2015 Media Design School // // File name : main.cpp // Description : This file contains the main loop with all the game's states // Author : Juan Rodriguez // Mail : juan.rod6618@mediadesignschool.com // // Library includes #include <iostream> #include <string> #include <windows.h> // Local includes #include "Game.h" #include "GameState.h" int main() { Game game; GameState gameState; enum eState { MENU = 0, SETUP = 1, GAME = 2, GAMEOVER = 3, QUIT = 4, CREDITS = 5 }; // Options for each menu int iMenuOption = 0; int iSortOption = 0; //int winner = -1; char cGameOverOption = '\0'; // Initial state gameState.setSortMode(MENU); while (true) { // Menu while (gameState.getSortMode() == MENU) { gameState.drawState(MENU); iMenuOption = game.setMenu(); if (iMenuOption == 1) { gameState.setSortMode(SETUP); } else if (iMenuOption == 2) { gameState.setSortMode(CREDITS); } else if (iMenuOption == 3) { gameState.setSortMode(GAMEOVER); } } // Menu // Setup while (gameState.getSortMode() == SETUP) { gameState.drawState(SETUP); iSortOption = game.setSetupMode(); if (iSortOption == 1) { game.sortAutomatic(); gameState.setSortMode(GAME); } else if (iSortOption == 2) { game.sortManual(); gameState.setSortMode(GAME); } else if (iSortOption == 0) { gameState.setSortMode(MENU); } if (game.getSortMode() == "X") { gameState.setSortMode(SETUP); } } // !Setup // Game while (gameState.getSortMode() == GAME) { gameState.drawState(GAME); game.updateGame(); if (game.getSortMode() == "X") { gameState.setSortMode(SETUP); } else { gameState.setSortMode(GAMEOVER); } } // !Game // Game over while (gameState.getSortMode() == GAMEOVER) { gameState.drawState(GAMEOVER); cGameOverOption = game.setGameOver().at(0); if (cGameOverOption == 'Y') { gameState.setSortMode(MENU); } else if (cGameOverOption == 'N') { gameState.setSortMode(QUIT); } } // !Game over // Credits while (gameState.getSortMode() == CREDITS) { gameState.drawState(CREDITS); gameState.setSortMode(MENU); } // !Credits // Quit if (gameState.getSortMode() == QUIT) { gameState.drawState(QUIT); break; } // !Quit } // !Main loop game.~Game(); return 0; }
[ "timrodz@gmail.com" ]
timrodz@gmail.com
49cf01b2004bd6071972c224acf96809390ce9a0
2870300e12314f8d64f73fe7e457065e5b002aee
/面向对象程序设计基础/homework2up-datedcode/problem2/student.cpp
09ff4516abecac3161e4bd3f1a2c15a83cf7412c
[ "MIT" ]
permissive
xuanquanfeipu/Personal-Homework
316e2d52750ff3857f2ff90e9a9bde5ac005b2ed
2d0a27010da8c24aecc161c0ba17fa01febd45e7
refs/heads/master
2020-05-07T16:27:59.260782
2020-04-15T01:42:34
2020-04-15T01:42:34
180,683,559
0
1
MIT
2020-04-15T01:42:35
2019-04-11T00:22:21
C++
UTF-8
C++
false
false
801
cpp
#include <bits/stdc++.h> #include "student.h" /** * [student::init description] * @Author n+e * @DateTime 2017-04-02 * @param str original information in this string * change info in str into id & email */ void student::init(std::string str) { std::stringstream ss(str); ss >> id >> email; } /** * reload the ofstream */ std::ostream& operator<<(std::ostream& out, const student& stu) { out << "ID: " << stu.id << "\tEmail: " << stu.email << std::endl; return out; } Assigner::Assigner() { total = 0; } /** * [Assigner::load description] * @Author n+e * @DateTime 2017-04-02 * load info from the file. */ void Assigner::load() { std::ifstream in("ContactEmail.txt"); std::string tmp; std::getline(in, tmp); while (std::getline(in, tmp)) stu[total++].init(tmp); }
[ "463003665@qq.com" ]
463003665@qq.com
5219b15d769fe73c5b98c8973ba8fd19eab17c7d
050c8a810d34fe125aecae582f9adfd0625356c6
/A. Neverending competitions/main.cpp
4c146cf948c6778f9e57b1e943c479ef721e1f82
[]
no_license
georgerapeanu/c-sources
adff7a268121ae8c314e846726267109ba1c62e6
af95d3ce726325dcd18b3d94fe99969006b8e138
refs/heads/master
2022-12-24T22:57:39.526205
2022-12-21T16:05:01
2022-12-21T16:05:01
144,864,608
11
0
null
null
null
null
UTF-8
C++
false
false
360
cpp
#include <cstdio> using namespace std; char C[20]; char home[20]; int a,b; int N; int main() { scanf("%d\n",&N); gets(home); for(int i=1;i<=N;i++) { gets(C); if(C[0]==home[0]&&C[1]==home[1]&&C[2]==home[2]) a++; else b++; } if(a==b) puts("home"); else puts("contest"); return 0; }
[ "alexandrurapeanu@yahoo.com" ]
alexandrurapeanu@yahoo.com
f632f4fdb5c7b4d8976e5b610ebb9759e546345c
18a6f49856cc2932ddb17f3b3f868712935fdbd6
/emulator_hw/hardware_model/atom.h
eb6a12fc5602e687f7b6647f5096c47d781af969
[ "MIT" ]
permissive
thekyria/elabtsaot2
2ed8db937dc0ed0a1df00b2baaff86c09327689a
dc4d20be9f6dd8c80b9ae8fe39d35927e0488677
refs/heads/master
2022-12-22T11:23:03.914263
2022-12-10T15:15:19
2022-12-10T15:15:19
97,841,144
4
1
null
null
null
null
UTF-8
C++
false
false
2,989
h
/*! \file atom.h \brief Definition file for class Atom This class is part of the elab-tsaot project in the Electronics Laboratory of the Ecole Polytechnique Federal de Lausanne. \author Theodoros Kyriakidis, thekyria at gmail dot com, Electronics Laboratory EPFL */ #ifndef ATOM_H #define ATOM_H #include "node.h" #include "emulatorbranch.h" #include "dac.h" #include <vector> #include <stdlib.h> namespace elabtsaot{ /*! Enumeration for the positions of branches around the node of the atom EMBRPOS_ UL U UR \ | / L - N - R / | \ DL D DR */ enum EmbrPosition { EMBRPOS_U = 0, //!< denotes U EmulatorBranch of the atom EMBRPOS_UR = 1, //!< denotes UR EmulatorBranch of the atom EMBRPOS_R = 2, //!< denotes R EmulatorBranch of the atom EMBRPOS_DR = 3, //!< denotes DR EmulatorBranch of the atom EMBRPOS_D = 4, //!< denotes D EmulatorBranch of the atom EMBRPOS_DL = 5, //!< denotes DL EmulatorBranch of the atom EMBRPOS_L = 6, //!< denotes L EmulatorBranch of the atom EMBRPOS_UL = 7 //!< denotes UL EmulatorBranch of the atom }; /*! Class representing an atom of the hardware emulator An atom is the building blog of the analog part of a hardware emulator slice. Atoms consist of nodes -measuerement and injection points to the analog grid- surrounded by emulator branches -physically connecting nodes of adjacent atoms of the analog grid-. Atom nodes are physically connected with nodes of adjacent atoms by the emulator branches. Atom representation - the node appears as the central dot 'o' and the emulator branches as dashes '-, |, /' surrounding the node. | / | / |/ ---o--- The analog grid has a real and an imaginary part. \sa Node, EmulatorBranch \warning This class is part of the emulator_hw classes that provide a software representation of the hardware emulator developed at ELAB. As such, changes in hardware are reflected in the software classes. For more information on the hardware of the project contact: guillaume dot lanz at epfl dot ch (hw team leader) \author thekyria \date May 2014 */ class Atom{ public: Atom(); int reset( bool complete ); size_t getEmbrCount() const; //!< number of emulator branches physically present on the Atom void calibrate(Atom const& cal_am); //! Get the minimum OVER the maximum achievable R of potentiometers in the atom (embrs and node) double getMinMaxAchievableR() const; // TODO: do that only for "used" resistors Node node; //!< node of the atom inline EmulatorBranch const& embr(size_t pos, bool real) const{return real ?embr_real[pos]:embr_imag[pos];} std::vector<EmulatorBranch> embr_real; //!< Branches of real part of the grid std::vector<EmulatorBranch> embr_imag; //!< Branches of imag part of the grid std::vector<bool> embr_exist; //!< whether branches (real and im) physically exist }; } // end of namespace elabtsaot #endif // ATOM_H
[ "thekyria@gmail.com" ]
thekyria@gmail.com
fee49f0fef723a9d24965949ac6a6a2f71a34fa1
5a0a4583a7d88c2dd34df2d67b1556e38cba9d68
/kap41Container_lst168-41multiset-equalrange.cpp
0104fc84383f08d73d051d340be131e2c5b89e67
[]
no_license
Paul-Arts/cplus
bde0adc63b2d8f32bb6d209696699d0e08c38511
7f90a98bd05f69e8861df99d08011cf042883884
refs/heads/master
2020-12-01T02:00:50.339970
2019-12-28T00:52:26
2019-12-28T00:52:26
230,536,999
0
0
null
null
null
null
UTF-8
C++
false
false
1,345
cpp
#include <set> //# #include <iostream> //# #include <string> #include <iterator> // distance struct Person { std::string name; friend bool operator<(const Person &a, const Person &b) {// nur erster Buchstabe return a.name.size()==0 ? true : (b.name.size()==0 ? false : a.name[0] < b.name[0]); } }; // ... using std::multiset; using std::cout; //# template<typename Elem, typename Comp> //# std::ostream& operator<<=(std::ostream&os, const multiset<Elem,Comp>&data) { //# for(auto &e : data) os << e << ' '; return os << '\n'; } //# int main() { //# multiset<int> data{ 1, 4,4, 2,2,2, 7, 9 }; auto wo = data.equal_range(2); cout << "Anzahl 2en: " << std::distance(wo.first, wo.second) << '\n'; // Ausgabe: Anzahl 2en: 3 //= Anzahl 2en: 3 wo = data.equal_range(5); cout << "Anzahl 5en: " << std::distance(wo.first, wo.second) << '\n'; // Ausgabe: Anzahl 5en: 0 //= Anzahl 5en: 0 multiset<Person> raum{ Person{"Karl"}, Person{"Kurt"}, Person{"Peter"}, Person{"Karl"}, Person{"Ken"} }; auto ks = raum.equal_range(Person{"K"}); for( ; ks.first != ks.second; ++ks.first) { cout << ks.first->name << ' '; } cout << '\n'; // Ausgabe: Karl Kurt Karl Ken //= Karl Kurt Karl Ken } //#
[ "paul@netwerk" ]
paul@netwerk
8deabbd5e7c478e5ef625a5efc2c12512a88d811
2bacd512d280b284a31106157ccde45b469e659c
/leetcode_C++/leetcode_C++/code_153.cpp
96515afcf2f6ffa90948fc17256f4c3aec4235d8
[]
no_license
hapiii/leetcode
b4e7f1b04f17cb14008f0923bb550b973fa56331
cb8ab990afd1e70b08d19079bee71aeef0b0e477
refs/heads/master
2023-07-08T22:11:55.076411
2023-06-28T07:28:43
2023-06-28T07:28:43
193,800,277
0
0
null
null
null
null
UTF-8
C++
false
false
1,439
cpp
// // code_153.cpp // leetcode_C++ // // Created by hapii on 2020/1/5. // Copyright © 2020 hapii. All rights reserved. // #include <stdio.h> #include <vector> #include <iostream> using namespace std; /* 假设按照升序排序的数组在预先未知的某个点上进行了旋转。 ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。 请找出其中最小的元素。 你可以假设数组中不存在重复元素。 输入: [2,3,4,5,1] 输出: 1 输入: [5,6,1,2,3,4] 输出: 1 */ class code_153 { public: void test(){ vector<int> v1; v1.push_back(5); v1.push_back(6); v1.push_back(1); v1.push_back(2); v1.push_back(3); v1.push_back(4); findMin(v1); } int findMin(vector<int>& nums) { int left = 0,right = nums.size()-1; int center,temp; int end = nums[0]; while (left <= right) { center = left+ (right-left)/2; if(end>nums[center]){ end = nums[center]; } if (nums[left] < nums[center] ) { left = center; }else if (nums[center] < nums[right] ) { right = center; }else{ temp = nums[left]<nums[right]?nums[left]:nums[right]; return end<temp?end:temp; } } return end; } };
[ "869932084@qq.com" ]
869932084@qq.com
35289ab1b9476bbd672f320459035c70334472cc
b4c2427ece02bc1bc1f5e6279539ac884efcb323
/Codeforces/codeforces939B.cpp
23897a6faeba3d1b4beb54f63f20d2a6b894b7fd
[]
no_license
sohag16030/ACM-Programming
eb7210be3685c3f7e5ea855c1598f5e7f3044463
39943162ed7b08d34b2b07b1a866b039c6ec2cc7
refs/heads/master
2023-01-31T11:08:46.389769
2020-12-14T08:57:24
2020-12-14T08:57:24
218,221,513
0
0
null
null
null
null
UTF-8
C++
false
false
860
cpp
/*"BISMILLAHIR RAHMANIR RAHIM....." "YOUR OUTPUT WILL BE REWARDED,NOT YOUR EFFORTS...TRY,TRY AND TRY" CREATOR:SHOHAG(ICT,MBSTU).......*/ #include<bits/stdc++.h> #define pf printf #define sf scanf #define sz 100001 #define ll long long #define pb push_back #define mp make_pair #define ff first #define ss second #define all(x) x.begin(),x.end() using namespace std; ll n,m,k,i,j,t,f,t1,t2,t3,t4,t5,r,l,c,sum=0,cnt=0,x,y,a[sz],b[sz],g,z,rem,mod,mx; string s,s1,s2,s3,s4; map<ll,ll>M; map<ll,ll>::iterator it; vector<pair<ll,ll> >v; vector<ll>v1,v2,v3; vector<ll>v4[51]; int main() { cin>>n>>k; ll mn=1e19+5; for(i=1; i<=k; i++) { cin>>t; t1=n%t; c=n/t; if(t1<mn) { mn=t1; j=i; m=c; } } cout<<j<<' '<<m; return 0; }
[ "shohag.mbstu.it16030@gmail.com" ]
shohag.mbstu.it16030@gmail.com
6bb6c57e05cb4011039f62d13bdf1bebc884f88c
56c654fbd6fe1382b13d0369e55da91197e912fa
/Labs/dp/4B.cpp
bb7d5a3876ffc8b260128eadc30c4c21fb04f5d2
[]
no_license
teptind/AlgoLabs
08886f5344b94bb5aabdb1e8586e25116f7c1d98
8e2aaa8e313ceabb80f9d4975ec8ff1e4ad0e24e
refs/heads/master
2022-01-12T15:47:13.055771
2019-07-22T15:33:13
2019-07-22T15:33:13
198,248,771
0
0
null
null
null
null
UTF-8
C++
false
false
1,560
cpp
#include <bits/stdc++.h> #include <time.h> using namespace std; #define ll long long #define ld long double #define uint unsigned int #define ull unsigned long long void print(vector<int> &t) { for (int i = 0; i < (int)t.size(); ++i) cout << t[i] << " "; cout << "\n"; } void print2(vector<vector<int> > &t, int n) { cout << n << " " << t.size() << endl; for (int i = 0; i < (int)t.size(); ++i) print(t[i]); cout << "\n"; } int INF = 2e9; int main() { // freopen("file.in", "r", stdin); freopen("lis.in", "r", stdin); freopen("lis.out", "w", stdout); int n; cin >> n; vector<int> e(n + 1, INF); vector<int> eplace(n + 1, -1); vector<int> prev(n, -1); vector<int> ans; e[0] = -INF; eplace[0] = -1; vector<int> a(n); for (int i = 0; i < n; ++i) cin >> a[i]; for (int i = 0; i < n; ++i) { // print(e); int c = (int)(lower_bound(e.begin(), e.end(), a[i]) - e.begin()) - 1; // cout << a[i] << " " << c << endl; if (a[i] < e[c + 1]) { e[c + 1] = a[i]; eplace[c + 1] = i; prev[i] = eplace[c]; } } // print(e); // print(eplace); int mx = 0; for (int i = 1; i < n + 1; ++i) { if (e[i] != INF) mx = eplace[i]; } // print(prev); int p = mx; // cout << p << endl; while (p != -1) { ans.push_back(a[p]); p = prev[p]; } reverse(ans.begin(), ans.end()); cout << ans.size() << endl; print(ans); return 0; }
[ "teptind@gmail.com" ]
teptind@gmail.com
cb9c904e6b34c3de17d71d439073b83983fa2407
8ed111e74f9316e24ba5b6cd17447d45d16a9c41
/books/main.cpp
8732239aadde82686045a35028f0a9c91f2c47a0
[]
no_license
robobenklein/cs102
d1b0ec3746c7d05207adac6714d15dfc0b571c5c
6d32b9efd59793fdfc09729338dc542737dcd97c
refs/heads/master
2021-04-30T22:22:14.138494
2017-01-11T15:22:39
2017-01-11T15:22:39
66,581,734
0
0
null
null
null
null
UTF-8
C++
false
false
686
cpp
#include <iostream> #include <stdio.h> using namespace std; char bookType(int element); int main(int argc, char** argv) { double cost_books[5] = { 12.00, 7.00, 10.00, 0.60, 0.50 }; char selling_book, book; double total_cost = 0.0; int take_book = 0; cin >> selling_book; for(int i = 0; i < 5; i++) { book = bookType(i); if(selling_book == book) { total_cost += cost_books[i]; take_book += 1; } } if(take_book != 1) { cout << "we do not take that type of book" << endl; } } char bookType(int element) { char type_books[5] = { 'b', 's', 'm', 'd', 'c' }; return type_books[element]; }
[ "robobenklein@gmail.com" ]
robobenklein@gmail.com
ef8e04e1e25abf5b094410cf901c5c1cb40749c6
191bf92db1a9f6df7c30e37a8f0a14d1c220a3bd
/445A.cpp
aa04889214dfe73bed789a7c4f0af419806566fa
[]
no_license
doomsday861/Allofit
958fa379296e1a4c9a78b25ab0fd7c222bb1f81a
94d644e52a64ff2949ea731c569478e721fc71bf
refs/heads/master
2023-01-04T12:35:10.447467
2022-12-28T09:30:18
2022-12-28T09:30:18
250,110,669
0
1
null
2021-01-11T09:20:21
2020-03-25T22:59:54
C++
UTF-8
C++
false
false
1,185
cpp
/** * 445A **/ #include<bits/stdc++.h> #define ll long long #define testcase ll t;cin>>t;while(t--) #define pb push_back #define fi first #define se second #define vll vector<ll> #define for0(i, n) for (ll i = 0; i < (ll)(n); ++i) #define for1(i, n) for (ll i = 1; i <= (ll)(n); ++i) #define run ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); using namespace std; ll r,c; ll lr[] ={1,-1,0,0}; ll lc[] ={0,0,1,-1}; char ar[100][100]; bool isval(ll i,ll j) { return(i>=0 && i<r && j>=0 && j<c); } ll checkround(ll a,ll b) { bool bl=0,w=0; for0(i,4) { ll x = a+lr[i]; ll y = b+lc[i]; if(isval(x,y)) { // if(a==2 && b==2) // cout<<x<<" "<<y<<endl; if(ar[x][y]=='W') w=1; if(ar[x][y]=='B') bl=1; } } // if(a==2 && b==2) // cout<<bl<<" "<<w<<endl; if(bl && w) return -1; if(bl) return 2; if(w) return 1; if(!bl && !w) return 1; } int main() { run cin>>r>>c; for0(i,r) { for0(j,c) { cin>>ar[i][j]; } } for0(i,r) { for0(j,c) { if(ar[i][j]=='.') { if((i+j)&1) ar[i][j] = 'B'; else ar[i][j] = 'W'; } } } for0(i,r) { for0(j,c) { cout<<ar[i][j]; } cout<<endl; } return 0; }
[ "kartikeyasrivastava861@gmail.com" ]
kartikeyasrivastava861@gmail.com
ca41efc18cbd4495d6d065dd0b1b9fcceca3820e
5c6449138e768c140d4c43b16e56cf07ceaaedbf
/linux/my_application.cc
26c8f24538377203b5eac33671967da1ff7e930b
[]
no_license
rrkas/conics_master
524291c51f28b7917d4bd268149d0cdcbae5f9ab
3a2fd73fb27eb9170abd42dbfae43c1c39aacfdb
refs/heads/master
2023-01-01T05:46:00.119612
2020-10-27T18:43:33
2020-10-27T18:43:33
305,645,485
0
0
null
null
null
null
UTF-8
C++
false
false
1,538
cc
#include "my_application.h" #include <flutter_linux/flutter_linux.h> #include "flutter/generated_plugin_registrant.h" struct _MyApplication { GtkApplication parent_instance; }; G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) // Implements GApplication::activate. static void my_application_activate(GApplication* application) { GtkWindow* window = GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); GtkHeaderBar *header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); gtk_widget_show(GTK_WIDGET(header_bar)); gtk_header_bar_set_title(header_bar, "conics_master"); gtk_header_bar_set_show_close_button(header_bar, TRUE); gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); gtk_window_set_default_size(window, 1280, 720); gtk_widget_show(GTK_WIDGET(window)); g_autoptr(FlDartProject) project = fl_dart_project_new(); FlView* view = fl_view_new(project); gtk_widget_show(GTK_WIDGET(view)); gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); fl_register_plugins(FL_PLUGIN_REGISTRY(view)); gtk_widget_grab_focus(GTK_WIDGET(view)); } static void my_application_class_init(MyApplicationClass* klass) { G_APPLICATION_CLASS(klass)->activate = my_application_activate; } static void my_application_init(MyApplication* self) {} MyApplication* my_application_new() { return MY_APPLICATION(g_object_new(my_application_get_type(), "application-id", APPLICATION_ID, nullptr)); }
[ "rrka97wal@gmail.com" ]
rrka97wal@gmail.com
a177104fb0e82be355af54a130b5ec9b419dfd90
ce9964faef6ee75b71c417e34113578777cd86b2
/chrome/browser/android/vr_shell/vr_shell_gl.h
79ccd02f095a2db17e6511a12e96d3338297590a
[ "BSD-3-Clause" ]
permissive
alijuma/chromium
4d8eed877b655d39388d5e5def1b7514f05170ea
db8f04787fe546230612bd32f499194d3219f15c
refs/heads/master
2023-01-07T18:37:00.605447
2017-11-07T23:13:02
2017-11-07T23:13:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,209
h
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_ANDROID_VR_SHELL_VR_SHELL_GL_H_ #define CHROME_BROWSER_ANDROID_VR_SHELL_VR_SHELL_GL_H_ #include <memory> #include <utility> #include <vector> #include "base/cancelable_callback.h" #include "base/containers/queue.h" #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/single_thread_task_runner.h" #include "chrome/browser/android/vr_shell/android_vsync_helper.h" #include "chrome/browser/android/vr_shell/vr_controller.h" #include "chrome/browser/vr/content_input_delegate.h" #include "chrome/browser/vr/controller_mesh.h" #include "chrome/browser/vr/model/controller_model.h" #include "chrome/browser/vr/ui_input_manager.h" #include "chrome/browser/vr/ui_renderer.h" #include "device/vr/vr_service.mojom.h" #include "mojo/public/cpp/bindings/binding.h" #include "third_party/gvr-android-sdk/src/libraries/headers/vr/gvr/capi/include/gvr.h" #include "third_party/gvr-android-sdk/src/libraries/headers/vr/gvr/capi/include/gvr_types.h" #include "ui/gfx/geometry/quaternion.h" #include "ui/gfx/geometry/rect_f.h" #include "ui/gfx/geometry/size_f.h" #include "ui/gfx/native_widget_types.h" namespace gl { class GLContext; class GLFenceEGL; class GLSurface; class ScopedJavaSurface; class SurfaceTexture; } // namespace gl namespace gpu { struct MailboxHolder; } // namespace gpu namespace vr { class BrowserUiInterface; class FPSMeter; class SlidingAverage; class Ui; } // namespace vr namespace vr_shell { class MailboxToSurfaceBridge; class GlBrowserInterface; class VrController; class VrShell; struct WebVrBounds { WebVrBounds(const gfx::RectF& left, const gfx::RectF& right, const gfx::Size& size) : left_bounds(left), right_bounds(right), source_size(size) {} gfx::RectF left_bounds; gfx::RectF right_bounds; gfx::Size source_size; }; // This class manages all GLThread owned objects and GL rendering for VrShell. // It is not threadsafe and must only be used on the GL thread. class VrShellGl : public device::mojom::VRPresentationProvider { public: VrShellGl(GlBrowserInterface* browser_interface, std::unique_ptr<vr::Ui> ui, gvr_context* gvr_api, bool reprojected_rendering, bool daydream_support, bool start_in_web_vr_mode); ~VrShellGl() override; void Initialize(); void InitializeGl(gfx::AcceleratedWidget window); void OnTriggerEvent(); void OnPause(); void OnResume(); base::WeakPtr<vr::BrowserUiInterface> GetBrowserUiWeakPtr(); scoped_refptr<base::SingleThreadTaskRunner> GetTaskRunner() { return task_runner_; } void SetWebVrMode(bool enabled); void CreateOrResizeWebVRSurface(const gfx::Size& size); void CreateContentSurface(); void ContentBoundsChanged(int width, int height); void ContentPhysicalBoundsChanged(int width, int height); void UIBoundsChanged(int width, int height); void UIPhysicalBoundsChanged(int width, int height); base::WeakPtr<VrShellGl> GetWeakPtr(); void SetControllerMesh(std::unique_ptr<vr::ControllerMesh> mesh); void ConnectPresentingService( device::mojom::VRSubmitFrameClientPtrInfo submit_client_info, device::mojom::VRPresentationProviderRequest request, device::mojom::VRDisplayInfoPtr display_info); void set_is_exiting(bool exiting) { is_exiting_ = exiting; } void OnSwapContents(int new_content_id); private: void GvrInit(gvr_context* gvr_api); void InitializeRenderer(); // Returns true if successfully resized. bool ResizeForWebVR(int16_t frame_index); void UpdateSamples(); void UpdateEyeInfos(const gfx::Transform& head_pose, int viewport_offset, const gfx::Size& render_size, vr::RenderInfo* out_render_info); void DrawFrame(int16_t frame_index, base::TimeTicks current_time); void DrawIntoAcquiredFrame(int16_t frame_index, base::TimeTicks current_time); void DrawFrameSubmitWhenReady(int16_t frame_index, const gfx::Transform& head_pose, std::unique_ptr<gl::GLFenceEGL> fence); void DrawFrameSubmitNow(int16_t frame_index, const gfx::Transform& head_pose); bool ShouldDrawWebVr(); void DrawWebVr(); bool WebVrPoseByteIsValid(int pose_index_byte); void UpdateController(const gfx::Transform& head_pose, base::TimeTicks current_time); void SendImmediateExitRequestIfNecessary(); void HandleControllerInput(const gfx::Point3F& laser_origin, const gfx::Vector3dF& head_direction, base::TimeTicks current_time); void HandleControllerAppButtonActivity( const gfx::Vector3dF& controller_direction); void CreateUiSurface(); void OnContentFrameAvailable(); void OnWebVRFrameAvailable(); void ScheduleOrCancelWebVrFrameTimeout(); void OnWebVrTimeoutImminent(); void OnWebVrFrameTimedOut(); int64_t GetPredictedFrameTimeNanos(); void OnVSync(base::TimeTicks frame_time); // VRPresentationProvider void GetVSync(GetVSyncCallback callback) override; void SubmitFrame(int16_t frame_index, const gpu::MailboxHolder& mailbox) override; void SubmitFrameWithTextureHandle(int16_t frame_index, mojo::ScopedHandle texture_handle) override; void UpdateLayerBounds(int16_t frame_index, const gfx::RectF& left_bounds, const gfx::RectF& right_bounds, const gfx::Size& source_size) override; void ForceExitVr(); void SendVSync(base::TimeTicks time, GetVSyncCallback callback); void ClosePresentationBindings(); // samplerExternalOES texture data for WebVR content image. int webvr_texture_id_ = 0; // Set from feature flag. bool webvr_vsync_align_; scoped_refptr<gl::GLSurface> surface_; scoped_refptr<gl::GLContext> context_; scoped_refptr<gl::SurfaceTexture> content_surface_texture_; scoped_refptr<gl::SurfaceTexture> webvr_surface_texture_; std::unique_ptr<gl::ScopedJavaSurface> content_surface_; std::unique_ptr<gvr::GvrApi> gvr_api_; std::unique_ptr<gvr::BufferViewportList> buffer_viewport_list_; std::unique_ptr<gvr::BufferViewport> buffer_viewport_; std::unique_ptr<gvr::BufferViewport> webvr_browser_ui_left_viewport_; std::unique_ptr<gvr::BufferViewport> webvr_browser_ui_right_viewport_; std::unique_ptr<gvr::BufferViewport> webvr_left_viewport_; std::unique_ptr<gvr::BufferViewport> webvr_right_viewport_; std::unique_ptr<gvr::SwapChain> swap_chain_; gvr::Frame acquired_frame_; base::queue<std::pair<uint8_t, WebVrBounds>> pending_bounds_; int premature_received_frames_ = 0; base::queue<uint16_t> pending_frames_; std::unique_ptr<MailboxToSurfaceBridge> mailbox_bridge_; // The default size for the render buffers. gfx::Size render_size_default_; gfx::Size render_size_webvr_ui_; bool cardboard_ = false; gfx::Quaternion controller_quat_; gfx::Size content_tex_physical_size_ = {0, 0}; gfx::Size webvr_surface_size_ = {0, 0}; std::vector<base::TimeTicks> webvr_time_pose_; std::vector<base::TimeTicks> webvr_time_js_submit_; std::vector<bool> webvr_frame_oustanding_; std::vector<gfx::Transform> webvr_head_pose_; std::unique_ptr<vr::Ui> ui_; bool web_vr_mode_ = false; bool ready_to_draw_ = false; bool paused_ = true; const bool surfaceless_rendering_; bool daydream_support_; bool is_exiting_ = false; std::unique_ptr<VrController> controller_; scoped_refptr<base::SingleThreadTaskRunner> task_runner_; base::TimeTicks pending_time_; bool pending_vsync_ = false; GetVSyncCallback callback_; mojo::Binding<device::mojom::VRPresentationProvider> binding_; device::mojom::VRSubmitFrameClientPtr submit_client_; GlBrowserInterface* browser_; uint8_t frame_index_ = 0; // Larger than frame_index_ so it can be initialized out-of-band. uint16_t last_frame_index_ = -1; uint64_t webvr_frames_received_ = 0; // Attributes for gesture detection while holding app button. gfx::Vector3dF controller_start_direction_; std::unique_ptr<vr::FPSMeter> fps_meter_; std::unique_ptr<vr::SlidingAverage> webvr_js_time_; std::unique_ptr<vr::SlidingAverage> webvr_render_time_; gfx::Point3F pointer_start_; vr::RenderInfo render_info_primary_; AndroidVSyncHelper vsync_helper_; base::CancelableCallback<void()> webvr_frame_timeout_; base::CancelableCallback<void()> webvr_spinner_timeout_; base::CancelableCallback< void(int16_t, const gfx::Transform&, std::unique_ptr<gl::GLFenceEGL>)> webvr_delayed_frame_submit_; std::vector<gvr::BufferSpec> specs_; bool content_frame_available_ = false; bool skips_redraw_when_not_dirty_; gfx::Transform last_used_head_pose_; base::WeakPtrFactory<VrShellGl> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(VrShellGl); }; } // namespace vr_shell #endif // CHROME_BROWSER_ANDROID_VR_SHELL_VR_SHELL_GL_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
f82ee0ec3c8adf50996f76e60dff8ecf5fcd3816
ad523ccbe6c5a76d6599375c52055303474610cd
/src/net/third_party/quiche/src/quic/masque/masque_server_backend.h
6fbb6231c07ff2eb3e3ee0888511c426ba5edf81
[ "BSD-3-Clause" ]
permissive
carter1029/naiveproxy
cf49b3356d681320fbbea6d8ed64eb8fa07fd109
c2e8c4676edbd7cc4bd9b1f7da1bd6f34c771480
refs/heads/master
2023-03-17T10:02:08.057873
2021-03-03T17:09:51
2021-03-03T17:10:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,507
h
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef QUICHE_QUIC_MASQUE_MASQUE_SERVER_BACKEND_H_ #define QUICHE_QUIC_MASQUE_MASQUE_SERVER_BACKEND_H_ #include "quic/platform/api/quic_export.h" #include "quic/tools/quic_memory_cache_backend.h" namespace quic { // QUIC server backend that understands MASQUE requests, but otherwise answers // HTTP queries using an in-memory cache. class QUIC_NO_EXPORT MasqueServerBackend : public QuicMemoryCacheBackend { public: // Interface meant to be implemented by the owner of the MasqueServerBackend // instance. class QUIC_NO_EXPORT BackendClient { public: virtual std::unique_ptr<QuicBackendResponse> HandleMasqueRequest( const std::string& masque_path, const spdy::Http2HeaderBlock& request_headers, const std::string& request_body, QuicSimpleServerBackend::RequestHandler* request_handler) = 0; virtual ~BackendClient() = default; }; explicit MasqueServerBackend(const std::string& server_authority, const std::string& cache_directory); // Disallow copy and assign. MasqueServerBackend(const MasqueServerBackend&) = delete; MasqueServerBackend& operator=(const MasqueServerBackend&) = delete; // From QuicMemoryCacheBackend. void FetchResponseFromBackend( const spdy::Http2HeaderBlock& request_headers, const std::string& request_body, QuicSimpleServerBackend::RequestHandler* request_handler) override; void CloseBackendResponseStream( QuicSimpleServerBackend::RequestHandler* request_handler) override; // Register backend client that can handle MASQUE requests. void RegisterBackendClient(QuicConnectionId connection_id, BackendClient* backend_client); // Unregister backend client. void RemoveBackendClient(QuicConnectionId connection_id); private: // Handle MASQUE request. bool MaybeHandleMasqueRequest( const spdy::Http2HeaderBlock& request_headers, const std::string& request_body, QuicSimpleServerBackend::RequestHandler* request_handler); std::string server_authority_; QuicHashMap<std::string, std::unique_ptr<QuicBackendResponse>> active_response_map_; QuicHashMap<QuicConnectionId, BackendClient*, QuicConnectionIdHash> backend_clients_; }; } // namespace quic #endif // QUICHE_QUIC_MASQUE_MASQUE_SERVER_BACKEND_H_
[ "kizdiv@gmail.com" ]
kizdiv@gmail.com
8c171b3886d7c5f3516735686112ac05f4c81d19
78ef6727092c8ef5ac7900717c602b8c27b8e03b
/src/Shared/Timer.cpp
f6735846b802166ea7673b94c780117659fa49f6
[]
no_license
PubFork/uaf
fef542c983e5a1a25bf1593cb2fc4534523c46fb
98fa9da100fdfccdaa4e9725203fbd0aca9b656d
refs/heads/master
2023-08-12T18:45:44.652484
2021-10-04T22:39:32
2021-10-04T22:39:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,730
cpp
/****************************************************************************** * Filename: Timer.cpp * Copyright (c) 2000, UAF Development Team (email CocoaSpud@hotmail.com) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ******************************************************************************/ #include "..\Shared\stdafx.h" #ifdef UAFEDITOR #else #endif #include "externs.h" #include "Timer.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif CTimer::CTimer(UINT TargetRes) { TIMECAPS tc; if (timeGetDevCaps(&tc, sizeof(TIMECAPS)) != TIMERR_NOERROR) ASSERT(0); m_TimerId = 0; m_Active = FALSE; m_Periodic = FALSE; m_Resolution = min(max(tc.wPeriodMin, TargetRes), tc.wPeriodMax); timeBeginPeriod(m_Resolution); } CTimer::~CTimer() { StopTimer(); timeEndPeriod(m_Resolution); } BOOL CTimer::StartOneTimeTimer(UINT MsInterval) { if (m_Active) return FALSE; m_Periodic = FALSE; m_TimerId = timeSetEvent(MsInterval, m_Resolution, TimerCallback, reinterpret_cast<DWORD>(this), TIME_ONESHOT ); if(!m_TimerId) return FALSE; else m_Active = TRUE; return TRUE; } BOOL CTimer::StartPeriodicTimer(UINT MsInterval) { if (m_Active) return FALSE; m_Periodic = TRUE; m_TimerId = timeSetEvent(MsInterval, m_Resolution, TimerCallback, reinterpret_cast<DWORD>(this), TIME_PERIODIC ); if(!m_TimerId) return FALSE; else m_Active = TRUE; return TRUE; } VOID CTimer::StopTimer() { if (m_Active) { timeKillEvent(m_TimerId); m_TimerId = 0; m_Active = FALSE; } } void CALLBACK TimerCallback(UINT TimerId, UINT msg, DWORD UserData, DWORD dw1, DWORD dw2) { CTimer* pTimerObj = reinterpret_cast<CTimer*>(UserData); if (!pTimerObj->m_Periodic) pTimerObj->m_Active = FALSE; pTimerObj->OnTimerEvent(TimerId); }
[ "andrew_steeley@hotmail.com" ]
andrew_steeley@hotmail.com
3375997cb0cda771757f69cd066099a8cb755eb9
0d0e78c6262417fb1dff53901c6087b29fe260a0
/emr/src/v20190103/model/LoginSettings.cpp
5ad3b4b7ee9bbc09dc1636c1433949c34d9b42af
[ "Apache-2.0" ]
permissive
li5ch/tencentcloud-sdk-cpp
ae35ffb0c36773fd28e1b1a58d11755682ade2ee
12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4
refs/heads/master
2022-12-04T15:33:08.729850
2020-07-20T00:52:24
2020-07-20T00:52:24
281,135,686
1
0
Apache-2.0
2020-07-20T14:14:47
2020-07-20T14:14:46
null
UTF-8
C++
false
false
3,048
cpp
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/emr/v20190103/model/LoginSettings.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Emr::V20190103::Model; using namespace rapidjson; using namespace std; LoginSettings::LoginSettings() : m_passwordHasBeenSet(false), m_publicKeyIdHasBeenSet(false) { } CoreInternalOutcome LoginSettings::Deserialize(const Value &value) { string requestId = ""; if (value.HasMember("Password") && !value["Password"].IsNull()) { if (!value["Password"].IsString()) { return CoreInternalOutcome(Error("response `LoginSettings.Password` IsString=false incorrectly").SetRequestId(requestId)); } m_password = string(value["Password"].GetString()); m_passwordHasBeenSet = true; } if (value.HasMember("PublicKeyId") && !value["PublicKeyId"].IsNull()) { if (!value["PublicKeyId"].IsString()) { return CoreInternalOutcome(Error("response `LoginSettings.PublicKeyId` IsString=false incorrectly").SetRequestId(requestId)); } m_publicKeyId = string(value["PublicKeyId"].GetString()); m_publicKeyIdHasBeenSet = true; } return CoreInternalOutcome(true); } void LoginSettings::ToJsonObject(Value &value, Document::AllocatorType& allocator) const { if (m_passwordHasBeenSet) { Value iKey(kStringType); string key = "Password"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_password.c_str(), allocator).Move(), allocator); } if (m_publicKeyIdHasBeenSet) { Value iKey(kStringType); string key = "PublicKeyId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_publicKeyId.c_str(), allocator).Move(), allocator); } } string LoginSettings::GetPassword() const { return m_password; } void LoginSettings::SetPassword(const string& _password) { m_password = _password; m_passwordHasBeenSet = true; } bool LoginSettings::PasswordHasBeenSet() const { return m_passwordHasBeenSet; } string LoginSettings::GetPublicKeyId() const { return m_publicKeyId; } void LoginSettings::SetPublicKeyId(const string& _publicKeyId) { m_publicKeyId = _publicKeyId; m_publicKeyIdHasBeenSet = true; } bool LoginSettings::PublicKeyIdHasBeenSet() const { return m_publicKeyIdHasBeenSet; }
[ "jimmyzhuang@tencent.com" ]
jimmyzhuang@tencent.com
ac2317ad11be5b38555fbe76b58ca062ab1b074f
2a7e77565c33e6b5d92ce6702b4a5fd96f80d7d0
/fuzzedpackages/ctgt/src/RcppExports.cpp
8a8c96b1c0c2a2ddbebd62315b5bbb5c9debf78a
[]
no_license
akhikolla/testpackages
62ccaeed866e2194652b65e7360987b3b20df7e7
01259c3543febc89955ea5b79f3a08d3afe57e95
refs/heads/master
2023-02-18T03:50:28.288006
2021-01-18T13:23:32
2021-01-18T13:23:32
329,981,898
7
1
null
null
null
null
UTF-8
C++
false
false
1,987
cpp
// Generated by using Rcpp::compileAttributes() -> do not edit by hand // Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 #include <Rcpp.h> using namespace Rcpp; // getL std::vector<double> getL(std::vector<double> ub, std::vector<double> lb, double level); RcppExport SEXP _ctgt_getL(SEXP ubSEXP, SEXP lbSEXP, SEXP levelSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< std::vector<double> >::type ub(ubSEXP); Rcpp::traits::input_parameter< std::vector<double> >::type lb(lbSEXP); Rcpp::traits::input_parameter< double >::type level(levelSEXP); rcpp_result_gen = Rcpp::wrap(getL(ub, lb, level)); return rcpp_result_gen; END_RCPP } // pv double pv(double x, std::vector<double> lam); RcppExport SEXP _ctgt_pv(SEXP xSEXP, SEXP lamSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< double >::type x(xSEXP); Rcpp::traits::input_parameter< std::vector<double> >::type lam(lamSEXP); rcpp_result_gen = Rcpp::wrap(pv(x, lam)); return rcpp_result_gen; END_RCPP } // criticalvalue double criticalvalue(std::vector<double> lam, double alpha); RcppExport SEXP _ctgt_criticalvalue(SEXP lamSEXP, SEXP alphaSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< std::vector<double> >::type lam(lamSEXP); Rcpp::traits::input_parameter< double >::type alpha(alphaSEXP); rcpp_result_gen = Rcpp::wrap(criticalvalue(lam, alpha)); return rcpp_result_gen; END_RCPP } static const R_CallMethodDef CallEntries[] = { {"_ctgt_getL", (DL_FUNC) &_ctgt_getL, 3}, {"_ctgt_pv", (DL_FUNC) &_ctgt_pv, 2}, {"_ctgt_criticalvalue", (DL_FUNC) &_ctgt_criticalvalue, 2}, {NULL, NULL, 0} }; RcppExport void R_init_ctgt(DllInfo *dll) { R_registerRoutines(dll, NULL, CallEntries, NULL, NULL); R_useDynamicSymbols(dll, FALSE); }
[ "akhilakollasrinu424jf@gmail.com" ]
akhilakollasrinu424jf@gmail.com
b9baa7ac9882c8b5da51a73736c3b2ff1a3d255b
55f6614cbd9bf96fcc1e384808d476040378af9b
/Trabajos/Arduino/Sensor_de_Proximidad.ino
b52c37414ebd841c3ecc1ce532439a979916cf49
[]
no_license
ProcessingTEC/proyectos-rgonzaleztec
e62cefe4526a08bb2185f15088ddaa76ad794afb
0a58eddb34fee83316e59f2df16ee61823c2ec87
refs/heads/master
2021-01-19T01:17:50.412585
2016-06-27T22:08:25
2016-06-27T22:08:25
61,155,081
0
0
null
null
null
null
UTF-8
C++
false
false
1,915
ino
int vcc = 2; //attach pin 2 to vcc int trig = 3; // attach pin 3 to Trig int echo = 4; //attach pin 4 to Echo int gnd = 5; //attach pin 5 to GND void setup() { //pinMode (vcc,OUTPUT); //pinMode (gnd,OUTPUT); // initialize serial communication: Serial.begin(9600); } void loop() { digitalWrite(vcc, HIGH); // establish variables for duration of the ping, // and the distance result in inches and centimeters: long duration, inches, cm; // The PING))) is triggered by a HIGH pulse of 2 or more microseconds. // Give a short LOW pulse beforehand to ensure a clean HIGH pulse: pinMode(trig, OUTPUT); digitalWrite(trig, LOW); delayMicroseconds(2); digitalWrite(trig, HIGH); delayMicroseconds(5); digitalWrite(trig, LOW); // The same pin is used to read the signal from the PING))): a HIGH // pulse whose duration is the time (in microseconds) from the sending // of the ping to the reception of its echo off of an object. pinMode(echo,INPUT); duration = pulseIn(echo, HIGH); // convert the time into a distance inches = microsecondsToInches(duration); cm = microsecondsToCentimeters(duration); Serial.print(inches); Serial.print(','); //Serial.print("in, "); Serial.print(cm); //Serial.print("cm"); Serial.println(); delay(400); } long microsecondsToInches(long microseconds) { // According to Parallax's datasheet for the PING))), there are // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per // second). This gives the distance travelled by the ping, outbound // and return, so we divide by 2 to get the distance of the obstacle. // See: http://www.parallax.com/dl/docs/prod/acc/28015-PI... return microseconds / 74 / 2; } long microsecondsToCentimeters(long microseconds) { // The speed of sound is 340 m/s or 29 microseconds per centimeter. // The ping travels out and back, so to find the distance of the // object we take half of the distance travelled. return microseconds / 29 / 2; }
[ "noreply@github.com" ]
ProcessingTEC.noreply@github.com
35feb02284142e02f4b9532a0d3a3d2f600c11ca
89dedd7f3c7acc81d12e2bcb2e716f9af9e5fa04
/third_party/WebKit/Source/core/css/cssom/CSSStyleImageValueTest.cpp
efe58c462290ec6bddcf1104af1b5c043336ef50
[ "BSD-2-Clause", "LGPL-2.1-only", "LGPL-2.0-only", "BSD-3-Clause", "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "GPL-2.0-only", "LicenseRef-scancode-other-copyleft" ]
permissive
bino7/chromium
8d26f84a1b6e38a73d1b97fea6057c634eff68cb
4666a6bb6fdcb1114afecf77bdaa239d9787b752
refs/heads/master
2022-12-22T14:31:53.913081
2016-09-06T10:05:11
2016-09-06T10:05:11
67,410,510
1
3
BSD-3-Clause
2022-12-17T03:08:52
2016-09-05T10:11:59
null
UTF-8
C++
false
false
1,690
cpp
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "core/css/cssom/CSSStyleImageValue.h" #include "testing/gtest/include/gtest/gtest.h" namespace blink { namespace { class FakeCSSStyleImageValue : public CSSStyleImageValue { public: FakeCSSStyleImageValue(CSSImageValue* imageValue, bool cachePending, LayoutSize layoutSize) : CSSStyleImageValue(imageValue) , m_cachePending(cachePending) , m_layoutSize(layoutSize) { } bool m_cachePending; LayoutSize m_layoutSize; CSSValue* toCSSValue() const override { return nullptr; } bool isCachePending() const override { return m_cachePending; } LayoutSize imageLayoutSize() const override { return m_layoutSize; } }; TEST(CSSStyleImageValueTest, PendingCache) { FakeCSSStyleImageValue* styleImageValue = new FakeCSSStyleImageValue(CSSImageValue::create(""), true, LayoutSize(100, 100)); bool isNull; EXPECT_EQ(styleImageValue->intrinsicWidth(isNull), 0); EXPECT_EQ(styleImageValue->intrinsicHeight(isNull), 0); EXPECT_EQ(styleImageValue->intrinsicRatio(isNull), 0); EXPECT_TRUE(isNull); } TEST(CSSStyleImageValueTest, ValidLoadedImage) { FakeCSSStyleImageValue* styleImageValue = new FakeCSSStyleImageValue(CSSImageValue::create(""), false, LayoutSize(480, 120)); bool isNull; EXPECT_EQ(styleImageValue->intrinsicWidth(isNull), 480); EXPECT_EQ(styleImageValue->intrinsicHeight(isNull), 120); EXPECT_EQ(styleImageValue->intrinsicRatio(isNull), 4); EXPECT_FALSE(isNull); } } // namespace } // namespace blink
[ "bino.zh@gmail.com" ]
bino.zh@gmail.com
8165bfc3f554f58cd93bbe91773d4a5123a91572
b84585f10e6f093644f616fb60339c6f46e5fcea
/paddle/fluid/operators/pad3d_op.cc
7b9a4ab1557bf0ce0ed2bd348298373f0ba672cf
[ "Apache-2.0" ]
permissive
awesome-archive/Paddle
f35592079108f8295923ad63705f418ca97cfd81
7bfcea5da0cc31d71c6f445c132cd673eb16bd2e
refs/heads/develop
2022-03-07T05:26:56.378834
2022-03-03T04:21:02
2022-03-03T04:21:02
81,780,022
0
0
Apache-2.0
2022-03-03T04:21:03
2017-02-13T03:15:18
C++
UTF-8
C++
false
false
40,595
cc
/* Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <algorithm> #include <memory> #include <string> #include <vector> #include "paddle/fluid/framework/op_registry.h" #include "paddle/phi/kernels/funcs/math_function.h" namespace paddle { namespace operators { using framework::Tensor; template <typename T> void ConstPad3DFuncNCDHW(const T* in_data, T* out_data, const int in_depth, const int in_height, const int in_width, const int out_depth, const int out_height, const int out_width, const int pad_front, const int pad_top, const int pad_left, const int out_d, const int out_h, const int out_w, const T value) { int in_d = out_d - pad_front; int in_h = out_h - pad_top; int in_w = out_w - pad_left; out_data[out_d * out_height * out_width + out_h * out_width + out_w] = (in_d < 0 || in_h < 0 || in_w < 0 || in_d >= in_depth || in_h >= in_height || in_w >= in_width) ? value : in_data[in_d * in_height * in_width + in_h * in_width + in_w]; } template <typename T> void ConstPad3DFuncNDHWC(const T* in_data, T* out_data, const int channels, const int in_depth, const int in_height, const int in_width, const int out_depth, const int out_height, const int out_width, const int pad_front, const int pad_top, const int pad_left, const int out_d, const int out_h, const int out_w, const T value) { int in_d = out_d - pad_front; int in_h = out_h - pad_top; int in_w = out_w - pad_left; const int out_index = (out_d * out_height * out_width + out_h * out_width + out_w) * channels; if (in_d < 0 || in_h < 0 || in_w < 0 || in_d >= in_depth || in_h >= in_height || in_w >= in_width) { for (int c = 0; c < channels; ++c) { out_data[out_index + c] = value; } } else { const int in_index = (in_d * in_height * in_width + in_h * in_width + in_w) * channels; for (int c = 0; c < channels; ++c) { out_data[out_index + c] = in_data[in_index + c]; } } } template <typename T> void ReflectPad3DFuncNCDHW(const T* in_data, T* out_data, const int in_depth, const int in_height, const int in_width, const int out_depth, const int out_height, const int out_width, const int pad_front, const int pad_top, const int pad_left, const int out_d, const int out_h, const int out_w, const T value) { int in_d = out_d - pad_front; int in_h = out_h - pad_top; int in_w = out_w - pad_left; in_d = std::max(in_d, -in_d); // reflect by 0 in_d = std::min(in_d, 2 * in_depth - in_d - 2); // reflect by in_depth in_h = std::max(in_h, -in_h); // reflect by 0 in_h = std::min(in_h, 2 * in_height - in_h - 2); // reflect by in_height in_w = std::max(in_w, -in_w); // reflect by 0 in_w = std::min(in_w, 2 * in_width - in_w - 2); // reflect by in_width out_data[out_d * out_height * out_width + out_h * out_width + out_w] = in_data[in_d * in_height * in_width + in_h * in_width + in_w]; } template <typename T> void ReflectPad3DFuncNDHWC(const T* in_data, T* out_data, const int channels, const int in_depth, const int in_height, const int in_width, const int out_depth, const int out_height, const int out_width, const int pad_front, const int pad_top, const int pad_left, const int out_d, const int out_h, const int out_w, const T value) { int in_d = out_d - pad_front; int in_h = out_h - pad_top; int in_w = out_w - pad_left; in_d = std::max(in_d, -in_d); in_d = std::min(in_d, 2 * in_depth - in_d - 2); in_h = std::max(in_h, -in_h); in_h = std::min(in_h, 2 * in_height - in_h - 2); in_w = std::max(in_w, -in_w); in_w = std::min(in_w, 2 * in_width - in_w - 2); const int out_index = (out_d * out_height * out_width + out_h * out_width + out_w) * channels; const int in_index = (in_d * in_height * in_width + in_h * in_width + in_w) * channels; for (int c = 0; c < channels; ++c) { out_data[out_index + c] = in_data[in_index + c]; } } template <typename T> void ReplicatePad3DFuncNCDHW(const T* in_data, T* out_data, const int in_depth, const int in_height, const int in_width, const int out_depth, const int out_height, const int out_width, const int pad_front, const int pad_top, const int pad_left, const int out_d, const int out_h, const int out_w, const T value) { int in_d = std::min(in_depth - 1, std::max(out_d - pad_front, 0)); int in_h = std::min(in_height - 1, std::max(out_h - pad_top, 0)); int in_w = std::min(in_width - 1, std::max(out_w - pad_left, 0)); out_data[out_d * out_height * out_width + out_h * out_width + out_w] = in_data[in_d * in_height * in_width + in_h * in_width + in_w]; } template <typename T> void ReplicatePad3DFuncNDHWC(const T* in_data, T* out_data, const int channels, const int in_depth, const int in_height, const int in_width, const int out_depth, const int out_height, const int out_width, const int pad_front, const int pad_top, const int pad_left, const int out_d, const int out_h, const int out_w, const T value) { int in_d = std::min(in_depth - 1, std::max(out_d - pad_front, 0)); int in_h = std::min(in_height - 1, std::max(out_h - pad_top, 0)); int in_w = std::min(in_width - 1, std::max(out_w - pad_left, 0)); const int out_index = (out_d * out_height * out_width + out_h * out_width + out_w) * channels; const int in_index = (in_d * in_height * in_width + in_h * in_width + in_w) * channels; for (int c = 0; c < channels; ++c) { out_data[out_index + c] = in_data[in_index + c]; } } template <typename T> void CircularPad3DFuncNCDHW(const T* in_data, T* out_data, const int in_depth, const int in_height, const int in_width, const int out_depth, const int out_height, const int out_width, const int pad_front, const int pad_top, const int pad_left, const int out_d, const int out_h, const int out_w, const T value) { int in_d = ((out_d - pad_front) % in_depth + in_depth) % in_depth; int in_h = ((out_h - pad_top) % in_height + in_height) % in_height; int in_w = ((out_w - pad_left) % in_width + in_width) % in_width; out_data[out_d * out_height * out_width + out_h * out_width + out_w] = in_data[in_d * in_height * in_width + in_h * in_width + in_w]; } template <typename T> void CircularPad3DFuncNDHWC(const T* in_data, T* out_data, const int channels, const int in_depth, const int in_height, const int in_width, const int out_depth, const int out_height, const int out_width, const int pad_front, const int pad_top, const int pad_left, const int out_d, const int out_h, const int out_w, const T value) { int in_d = ((out_d - pad_front) % in_depth + in_depth) % in_depth; int in_h = ((out_h - pad_top) % in_height + in_height) % in_height; int in_w = ((out_w - pad_left) % in_width + in_width) % in_width; const int out_index = (out_d * out_height * out_width + out_h * out_width + out_w) * channels; const int in_index = (in_d * in_height * in_width + in_h * in_width + in_w) * channels; for (int c = 0; c < channels; ++c) { out_data[out_index + c] = in_data[in_index + c]; } } template <typename T> void Pad3DNCDHW(const T* in_data, const int num, const int channels, const int in_depth, const int in_height, const int in_width, const int out_depth, const int out_height, const int out_width, const int pad_front, const int pad_top, const int pad_left, T value, T* out_data, void (*pad_func)(const T*, T*, const int, const int, const int, const int, const int, const int, const int, const int, const int, const int, const int, const int, const T)) { for (int n = 0; n < num; ++n) { for (int c = 0; c < channels; ++c) { for (int out_d = 0; out_d < out_depth; ++out_d) { for (int out_h = 0; out_h < out_height; ++out_h) { for (int out_w = 0; out_w < out_width; ++out_w) { pad_func(in_data, out_data, in_depth, in_height, in_width, out_depth, out_height, out_width, pad_front, pad_top, pad_left, out_d, out_h, out_w, value); } } } in_data += in_depth * in_height * in_width; out_data += out_depth * out_height * out_width; } } } template <typename T> void Pad3DNDHWC(const T* in_data, const int num, const int channels, const int in_depth, const int in_height, const int in_width, const int out_depth, const int out_height, const int out_width, const int pad_front, const int pad_top, const int pad_left, T value, T* out_data, void (*pad_func)(const T*, T*, const int, const int, const int, const int, const int, const int, const int, const int, const int, const int, const int, const int, const int, const T)) { for (int n = 0; n < num; ++n) { for (int out_d = 0; out_d < out_depth; ++out_d) { for (int out_h = 0; out_h < out_height; ++out_h) { for (int out_w = 0; out_w < out_width; ++out_w) { pad_func(in_data, out_data, channels, in_depth, in_height, in_width, out_depth, out_height, out_width, pad_front, pad_top, pad_left, out_d, out_h, out_w, value); } } } in_data += in_depth * in_height * in_width * channels; out_data += out_depth * out_height * out_width * channels; } } template <typename T> void ConstPad3DGradNCDHW(T* d_in_data, const T* d_out_data, const int in_depth, const int in_height, const int in_width, const int out_depth, const int out_height, const int out_width, const int pad_front, const int pad_top, const int pad_left, const int out_d, const int out_h, const int out_w) { int in_d = out_d - pad_front; int in_h = out_h - pad_top; int in_w = out_w - pad_left; if (!(in_d < 0 || in_h < 0 || in_w < 0 || in_d >= in_depth || in_h >= in_height || in_w >= in_width)) { d_in_data[in_d * in_height * in_width + in_h * in_width + in_w] = d_out_data[out_d * out_height * out_width + out_h * out_width + out_w]; } } template <typename T> void ConstPad3DGradNDHWC(T* d_in_data, const T* d_out_data, const int channels, const int in_depth, const int in_height, const int in_width, const int out_depth, const int out_height, const int out_width, const int pad_front, const int pad_top, const int pad_left, const int out_d, const int out_h, const int out_w) { int in_d = out_d - pad_front; int in_h = out_h - pad_top; int in_w = out_w - pad_left; const int out_index = (out_d * out_height * out_width + out_h * out_width + out_w) * channels; if (!(in_d < 0 || in_h < 0 || in_w < 0 || in_d >= in_depth || in_h >= in_height || in_w >= in_width)) { const int in_index = (in_d * in_height * in_width + in_h * in_width + in_w) * channels; for (int c = 0; c < channels; ++c) { d_in_data[in_index + c] = d_out_data[out_index + c]; } } } template <typename T> void ReflectPad3DGradNCDHW(T* d_in_data, const T* d_out_data, const int in_depth, const int in_height, const int in_width, const int out_depth, const int out_height, const int out_width, const int pad_front, const int pad_top, const int pad_left, const int out_d, const int out_h, const int out_w) { int in_d = out_d - pad_front; int in_h = out_h - pad_top; int in_w = out_w - pad_left; in_d = std::max(in_d, -in_d); // reflect by 0 in_d = std::min(in_d, 2 * in_depth - in_d - 2); // reflect by in_depth in_h = std::max(in_h, -in_h); // reflect by 0 in_h = std::min(in_h, 2 * in_height - in_h - 2); // reflect by in_height in_w = std::max(in_w, -in_w); // reflect by 0 in_w = std::min(in_w, 2 * in_width - in_w - 2); // reflect by in_width d_in_data[in_d * in_height * in_width + in_h * in_width + in_w] += d_out_data[out_d * out_height * out_width + out_h * out_width + out_w]; } template <typename T> void ReflectPad3DGradNDHWC(T* d_in_data, const T* d_out_data, const int channels, const int in_depth, const int in_height, const int in_width, const int out_depth, const int out_height, const int out_width, const int pad_front, const int pad_top, const int pad_left, const int out_d, const int out_h, const int out_w) { int in_d = out_d - pad_front; int in_h = out_h - pad_top; int in_w = out_w - pad_left; in_d = std::max(in_d, -in_d); in_d = std::min(in_d, 2 * in_depth - in_d - 2); in_h = std::max(in_h, -in_h); in_h = std::min(in_h, 2 * in_height - in_h - 2); in_w = std::max(in_w, -in_w); in_w = std::min(in_w, 2 * in_width - in_w - 2); const int out_index = (out_d * out_height * out_width + out_h * out_width + out_w) * channels; const int in_index = (in_d * in_height * in_width + in_h * in_width + in_w) * channels; for (int c = 0; c < channels; ++c) { d_in_data[in_index + c] += d_out_data[out_index + c]; } } template <typename T> void ReplicatePad3DGradNCDHW(T* d_in_data, const T* d_out_data, const int in_depth, const int in_height, const int in_width, const int out_depth, const int out_height, const int out_width, const int pad_front, const int pad_top, const int pad_left, const int out_d, const int out_h, const int out_w) { int in_d = std::min(in_depth - 1, std::max(out_d - pad_front, 0)); int in_h = std::min(in_height - 1, std::max(out_h - pad_top, 0)); int in_w = std::min(in_width - 1, std::max(out_w - pad_left, 0)); d_in_data[in_d * in_height * in_width + in_h * in_width + in_w] += d_out_data[out_d * out_height * out_width + out_h * out_width + out_w]; } template <typename T> void ReplicatePad3DGradNDHWC(T* d_in_data, const T* d_out_data, const int channels, const int in_depth, const int in_height, const int in_width, const int out_depth, const int out_height, const int out_width, const int pad_front, const int pad_top, const int pad_left, const int out_d, const int out_h, const int out_w) { int in_d = std::min(in_depth - 1, std::max(out_d - pad_front, 0)); int in_h = std::min(in_height - 1, std::max(out_h - pad_top, 0)); int in_w = std::min(in_width - 1, std::max(out_w - pad_left, 0)); const int out_index = (out_d * out_height * out_width + out_h * out_width + out_w) * channels; const int in_index = (in_d * in_height * in_width + in_h * in_width + in_w) * channels; for (int c = 0; c < channels; ++c) { d_in_data[in_index + c] += d_out_data[out_index + c]; } } template <typename T> void CircularPad3DGradNCDHW(T* d_in_data, const T* d_out_data, const int in_depth, const int in_height, const int in_width, const int out_depth, const int out_height, const int out_width, const int pad_front, const int pad_top, const int pad_left, const int out_d, const int out_h, const int out_w) { int in_d = ((out_d - pad_front) % in_depth + in_depth) % in_depth; int in_h = ((out_h - pad_top) % in_height + in_height) % in_height; int in_w = ((out_w - pad_left) % in_width + in_width) % in_width; d_in_data[in_d * in_height * in_width + in_h * in_width + in_w] += d_out_data[out_d * out_height * out_width + out_h * out_width + out_w]; } template <typename T> void CircularPad3DGradNDHWC(T* d_in_data, const T* d_out_data, const int channels, const int in_depth, const int in_height, const int in_width, const int out_depth, const int out_height, const int out_width, const int pad_front, const int pad_top, const int pad_left, const int out_d, const int out_h, const int out_w) { int in_d = ((out_d - pad_front) % in_depth + in_depth) % in_depth; int in_h = ((out_h - pad_top) % in_height + in_height) % in_height; int in_w = ((out_w - pad_left) % in_width + in_width) % in_width; const int out_index = (out_d * out_height * out_width + out_h * out_width + out_w) * channels; const int in_index = (in_d * in_height * in_width + in_h * in_width + in_w) * channels; for (int c = 0; c < channels; ++c) { d_in_data[in_index + c] += d_out_data[out_index + c]; } } template <typename T> void Pad3DGradNCDHW(T* d_in_data, const int num, const int channels, const int in_depth, const int in_height, const int in_width, const int out_depth, const int out_height, const int out_width, const int pad_front, const int pad_top, const int pad_left, const T* d_out_data, void (*pad_func)(T*, const T*, const int, const int, const int, const int, const int, const int, const int, const int, const int, const int, const int, const int)) { for (int n = 0; n < num; ++n) { for (int c = 0; c < channels; ++c) { for (int out_d = 0; out_d < out_depth; ++out_d) { for (int out_h = 0; out_h < out_height; ++out_h) { for (int out_w = 0; out_w < out_width; ++out_w) { pad_func(d_in_data, d_out_data, in_depth, in_height, in_width, out_depth, out_height, out_width, pad_front, pad_top, pad_left, out_d, out_h, out_w); } } } d_in_data += in_depth * in_height * in_width; d_out_data += out_depth * out_height * out_width; } } } template <typename T> void Pad3DGradNDHWC(T* d_in_data, const int num, const int channels, const int in_depth, const int in_height, const int in_width, const int out_depth, const int out_height, const int out_width, const int pad_front, const int pad_top, const int pad_left, const T* d_out_data, void (*pad_func)(T*, const T*, const int, const int, const int, const int, const int, const int, const int, const int, const int, const int, const int, const int, const int)) { for (int n = 0; n < num; ++n) { for (int out_d = 0; out_d < out_depth; ++out_d) { for (int out_h = 0; out_h < out_height; ++out_h) { for (int out_w = 0; out_w < out_width; ++out_w) { pad_func(d_in_data, d_out_data, channels, in_depth, in_height, in_width, out_depth, out_height, out_width, pad_front, pad_top, pad_left, out_d, out_h, out_w); } } } d_in_data += in_depth * in_height * in_width * channels; d_out_data += out_depth * out_height * out_width * channels; } } static inline std::vector<int> GetPaddings( const framework::ExecutionContext& context) { std::vector<int> paddings(6); auto* paddings_t = context.Input<Tensor>("Paddings"); if (paddings_t) { auto paddings_data = paddings_t->data<int>(); std::memcpy(paddings.data(), paddings_data, paddings.size() * sizeof(int)); } else { auto pads = context.Attr<std::vector<int>>("paddings"); std::copy(pads.begin(), pads.end(), paddings.data()); } return paddings; } template <typename T> class Pad3dCPUKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& context) const override { std::vector<int> pads = GetPaddings(context); auto mode = context.Attr<std::string>("mode"); auto data_format = context.Attr<std::string>("data_format"); T value = static_cast<T>(context.Attr<float>("value")); auto* x = context.Input<Tensor>("X"); auto in_dims = x->dims(); const T* in_data = x->data<T>(); auto* out = context.Output<Tensor>("Out"); if (data_format == "NCDHW") { out->Resize({in_dims[0], in_dims[1], in_dims[2] + pads[4] + pads[5], in_dims[3] + pads[2] + pads[3], in_dims[4] + pads[0] + pads[1]}); } else { out->Resize({in_dims[0], in_dims[1] + pads[4] + pads[5], in_dims[2] + pads[2] + pads[3], in_dims[3] + pads[0] + pads[1], in_dims[4]}); } auto out_dims = out->dims(); T* out_data = out->mutable_data<T>(context.GetPlace()); int channels = in_dims[1]; int in_depth = in_dims[2]; int in_height = in_dims[3]; int in_width = in_dims[4]; int out_depth = out_dims[2]; int out_height = out_dims[3]; int out_width = out_dims[4]; if (data_format == "NDHWC") { channels = in_dims[4]; in_depth = in_dims[1]; in_height = in_dims[2]; in_width = in_dims[3]; out_depth = out_dims[1]; out_height = out_dims[2]; out_width = out_dims[3]; } if (mode == "reflect") { PADDLE_ENFORCE_GT(in_depth, pads[4], platform::errors::InvalidArgument( "The depth of Input(X)'s dimension should be " "greater than pad_front" " in reflect mode" ", but received depth(%d) and pad_front(%d).", in_depth, pads[4])); PADDLE_ENFORCE_GT(in_depth, pads[5], platform::errors::InvalidArgument( "The depth of Input(X)'s dimension should be " "greater than pad_back" " in reflect mode" ", but received depth(%d) and pad_back(%d).", in_depth, pads[5])); PADDLE_ENFORCE_GT(in_height, pads[2], platform::errors::InvalidArgument( "The height of Input(X)'s dimension should be " "greater than pad_top" " in reflect mode" ", but received depth(%d) and pad_top(%d).", in_height, pads[2])); PADDLE_ENFORCE_GT(in_height, pads[3], platform::errors::InvalidArgument( "The height of Input(X)'s dimension should be " "greater than pad_bottom" " in reflect mode" ", but received depth(%d) and pad_bottom(%d).", in_height, pads[3])); PADDLE_ENFORCE_GT(in_width, pads[0], platform::errors::InvalidArgument( "The width of Input(X)'s dimension should be " "greater than pad_left" " in reflect mode" ", but received depth(%d) and pad_left(%d).", in_width, pads[0])); PADDLE_ENFORCE_GT(in_width, pads[1], platform::errors::InvalidArgument( "The width of Input(X)'s dimension should be " "greater than pad_right" " in reflect mode" ", but received depth(%d) and pad_right(%d).", in_width, pads[1])); } else if (mode == "circular" || mode == "replicate") { PADDLE_ENFORCE_NE(in_depth * in_height * in_width, 0, platform::errors::InvalidArgument( "The input tensor size can not be 0 for circular " "or replicate padding mode.")); } const int pad_left = pads[0]; const int pad_top = pads[2]; const int pad_front = pads[4]; const int num = in_dims[0]; if (data_format == "NCDHW") { std::map<std::string, void (*)(const T*, T*, const int, const int, const int, const int, const int, const int, const int, const int, const int, const int, const int, const int, const T)> func_map; func_map["reflect"] = ReflectPad3DFuncNCDHW; func_map["replicate"] = ReplicatePad3DFuncNCDHW; func_map["circular"] = CircularPad3DFuncNCDHW; func_map["constant"] = ConstPad3DFuncNCDHW; Pad3DNCDHW(in_data, num, channels, in_depth, in_height, in_width, out_depth, out_height, out_width, pad_front, pad_top, pad_left, value, out_data, func_map[mode]); } else { std::map<std::string, void (*)(const T*, T*, const int, const int, const int, const int, const int, const int, const int, const int, const int, const int, const int, const int, const int, const T)> func_map; func_map["reflect"] = ReflectPad3DFuncNDHWC; func_map["replicate"] = ReplicatePad3DFuncNDHWC; func_map["circular"] = CircularPad3DFuncNDHWC; func_map["constant"] = ConstPad3DFuncNDHWC; Pad3DNDHWC(in_data, num, channels, in_depth, in_height, in_width, out_depth, out_height, out_width, pad_front, pad_top, pad_left, value, out_data, func_map[mode]); } } }; template <typename T> class Pad3dGradCPUKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& context) const override { std::vector<int> pads = GetPaddings(context); auto mode = context.Attr<std::string>("mode"); auto data_format = context.Attr<std::string>("data_format"); auto* d_out = context.Input<Tensor>(framework::GradVarName("Out")); auto* d_in = context.Output<Tensor>(framework::GradVarName("X")); auto d_in_dims = d_in->dims(); auto d_out_dims = d_out->dims(); const T* d_out_data = d_out->data<T>(); T* d_in_data = d_in->mutable_data<T>(context.GetPlace()); phi::funcs::SetConstant<platform::CPUDeviceContext, T> set_zero; set_zero(context.template device_context<platform::CPUDeviceContext>(), d_in, static_cast<T>(0)); const int pad_left = pads[0]; const int pad_top = pads[2]; const int pad_front = pads[4]; const int num = d_in_dims[0]; if (data_format == "NCDHW") { const int channels = d_in_dims[1]; const int in_depth = d_in_dims[2]; const int in_height = d_in_dims[3]; const int in_width = d_in_dims[4]; const int out_depth = d_out_dims[2]; const int out_height = d_out_dims[3]; const int out_width = d_out_dims[4]; std::map<std::string, void (*)(T*, const T*, const int, const int, const int, const int, const int, const int, const int, const int, const int, const int, const int, const int)> func_map; func_map["reflect"] = ReflectPad3DGradNCDHW; func_map["replicate"] = ReplicatePad3DGradNCDHW; func_map["circular"] = CircularPad3DGradNCDHW; func_map["constant"] = ConstPad3DGradNCDHW; Pad3DGradNCDHW(d_in_data, num, channels, in_depth, in_height, in_width, out_depth, out_height, out_width, pad_front, pad_top, pad_left, d_out_data, func_map[mode]); } else { const int channels = d_in_dims[4]; const int in_depth = d_in_dims[1]; const int in_height = d_in_dims[2]; const int in_width = d_in_dims[3]; const int out_depth = d_out_dims[1]; const int out_height = d_out_dims[2]; const int out_width = d_out_dims[3]; std::map<std::string, void (*)(T*, const T*, const int, const int, const int, const int, const int, const int, const int, const int, const int, const int, const int, const int, const int)> func_map; func_map["reflect"] = ReflectPad3DGradNDHWC; func_map["replicate"] = ReplicatePad3DGradNDHWC; func_map["circular"] = CircularPad3DGradNDHWC; func_map["constant"] = ConstPad3DGradNDHWC; Pad3DGradNDHWC(d_in_data, num, channels, in_depth, in_height, in_width, out_depth, out_height, out_width, pad_front, pad_top, pad_left, d_out_data, func_map[mode]); } } }; class Pad3dOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "Pad3d"); OP_INOUT_CHECK(ctx->HasOutput("Out"), "Output", "Out", "Pad3d"); auto x_dim = ctx->GetInputDim("X"); PADDLE_ENFORCE_EQ(x_dim.size(), 5, platform::errors::InvalidArgument( "The size of Input(X)'s dimension should be equal to " "5, but received %d. ", x_dim.size())); std::vector<int64_t> out_dims(x_dim.size()); auto data_format = ctx->Attrs().Get<std::string>("data_format"); out_dims[0] = x_dim[0]; if (ctx->HasInput("Paddings")) { auto paddings_dim = ctx->GetInputDim("Paddings"); PADDLE_ENFORCE_EQ(paddings_dim.size(), 1, platform::errors::InvalidArgument( "Size of Input(Paddings)'s dimension should be " "equal to 1, but received %d.", paddings_dim.size())); if (ctx->IsRuntime()) { PADDLE_ENFORCE_EQ(paddings_dim[0], 6, platform::errors::InvalidArgument( "Shape of Input(Paddings) should be equal to " "[6], but received [%d].", paddings_dim[0])); } out_dims[1] = x_dim[1]; out_dims[2] = x_dim[2]; out_dims[3] = x_dim[3]; } else { auto paddings = ctx->Attrs().Get<std::vector<int>>("paddings"); PADDLE_ENFORCE_EQ( paddings.size(), 6, platform::errors::InvalidArgument( "Size of paddings should be equal to 4, but received %d.", static_cast<int>(paddings.size()))); if (data_format == "NCDHW") { out_dims[1] = x_dim[1]; // channel out_dims[2] = ((!ctx->IsRuntime()) && (x_dim[2] < 0)) ? x_dim[2] : (x_dim[2] + paddings[4] + paddings[5]); // depth out_dims[3] = ((!ctx->IsRuntime()) && (x_dim[3] < 0)) ? x_dim[3] : (x_dim[3] + paddings[2] + paddings[3]); // height out_dims[4] = ((!ctx->IsRuntime()) && (x_dim[4] < 0)) ? x_dim[4] : (x_dim[4] + paddings[0] + paddings[1]); // width } else { // NDHWC out_dims[4] = x_dim[4]; // channel out_dims[1] = ((!ctx->IsRuntime()) && (x_dim[1] < 0)) ? x_dim[1] : (x_dim[1] + paddings[4] + paddings[5]); // depth out_dims[2] = ((!ctx->IsRuntime()) && (x_dim[2] < 0)) ? x_dim[2] : (x_dim[2] + paddings[2] + paddings[3]); // height out_dims[3] = ((!ctx->IsRuntime()) && (x_dim[3] < 0)) ? x_dim[3] : (x_dim[3] + paddings[0] + paddings[1]); // width } } ctx->SetOutputDim("Out", phi::make_ddim(out_dims)); ctx->ShareLoD("X", /*->*/ "Out"); } protected: framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { return framework::OpKernelType( OperatorWithKernel::IndicateVarDataType(ctx, "X"), ctx.GetPlace()); } }; class Pad3dOpMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddInput("X", "The input of pad3d op. " "The input should be a 5-D tensor with formate NCDHW or NDHWC."); AddOutput("Out", "The output of pad3d op. " "A tensor with the same shape as X."); AddInput("Paddings", "A 1-D tensor to describe the padding rules." "paddings=[0, 1, 2, 3, 4, 5] means " "padding 0 column to left, 1 column to right, " "2 row to top, 3 row to bottom, 4 depth to front " "and 5 depth to back. Size of paddings must be 6.") .AsDispensable(); AddAttr<std::vector<int>>( "paddings", "(vector<int>) " "A list<int> to describe the padding rules." "paddings=[0, 1, 2, 3, 4, 5] means " "padding 0 column to left, 1 column to right, " "2 row to top, 3 row to bottom, 4 depth to front " "and 5 depth to back. Size of paddings must be 6."); AddAttr<float>("value", "(float, default 0.0) " "The value to fill the padded areas in constant mode.") .SetDefault(0.0f); AddAttr<std::string>( "mode", "(string, default constant) " "Four modes: constant(default), reflect, replicate, circular.") .SetDefault("constant"); AddAttr<std::string>( "data_format", "(string, default NCDHW) Only used in " "An optional string from: \"NDHWC\", \"NCDHW\". " "Defaults to \"NDHWC\". Specify the data format of the input data.") .SetDefault("NCDHW"); AddComment(R"DOC( Pad3d Operator. Pad 3-d images according to 'paddings' and 'mode'. If mode is 'reflect', paddings[0] and paddings[1] must be no greater than width-1. The height and depth dimension have the same condition. Given that X is a channel of image from input: X = [[[[[1, 2, 3], [4, 5, 6]]]]] Case 0: paddings = [2, 2, 1, 1, 0, 0], mode = 'constant' pad_value = 0 Out = [[[[[0. 0. 0. 0. 0. 0. 0.] [0. 0. 1. 2. 3. 0. 0.] [0. 0. 4. 5. 6. 0. 0.] [0. 0. 0. 0. 0. 0. 0.]]]]] Case 1: paddings = [2, 2, 1, 1, 0, 0], mode = 'reflect' Out = [[[[[6. 5. 4. 5. 6. 5. 4.] [3. 2. 1. 2. 3. 2. 1.] [6. 5. 4. 5. 6. 5. 4.] [3. 2. 1. 2. 3. 2. 1.]]]]] Case 2: paddings = [2, 2, 1, 1, 0, 0], mode = 'replicate' Out = [[[[[1. 1. 1. 2. 3. 3. 3.] [1. 1. 1. 2. 3. 3. 3.] [4. 4. 4. 5. 6. 6. 6.] [4. 4. 4. 5. 6. 6. 6.]]]]] Case 3: paddings = [2, 2, 1, 1, 0, 0], mode = 'circular' Out = [[[[[5. 6. 4. 5. 6. 4. 5.] [2. 3. 1. 2. 3. 1. 2.] [5. 6. 4. 5. 6. 4. 5.] [2. 3. 1. 2. 3. 1. 2.]]]]] )DOC"); } }; class Pad3dOpGrad : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "Pad3d@Grad"); OP_INOUT_CHECK(ctx->HasInput(framework::GradVarName("Out")), "Input", framework::GradVarName("Out"), "Pad3d@Grad"); auto x_dims = ctx->GetInputDim("X"); auto x_grad_name = framework::GradVarName("X"); if (ctx->HasOutput(x_grad_name)) { ctx->SetOutputDim(x_grad_name, x_dims); } } protected: framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { return framework::OpKernelType(OperatorWithKernel::IndicateVarDataType( ctx, framework::GradVarName("Out")), ctx.GetPlace()); } }; template <typename T> class Pad3dOpGradMaker : public framework::SingleGradOpMaker<T> { public: using framework::SingleGradOpMaker<T>::SingleGradOpMaker; protected: void Apply(GradOpPtr<T> bind) const override { bind->SetInput("X", this->Input("X")); if (this->HasInput("Paddings")) { bind->SetInput("Paddings", this->Input("Paddings")); } bind->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out")); bind->SetOutput(framework::GradVarName("X"), this->InputGrad("X")); bind->SetAttrMap(this->Attrs()); bind->SetType("pad3d_grad"); } }; template <typename T> class Pad3dOpDoubleGradMaker : public framework::SingleGradOpMaker<T> { public: using framework::SingleGradOpMaker<T>::SingleGradOpMaker; void Apply(GradOpPtr<T> grad_op) const override { if (this->HasInput("Paddings")) { grad_op->SetInput("Paddings", this->Input("Paddings")); } grad_op->SetType("pad3d"); grad_op->SetInput("X", this->OutputGrad(framework::GradVarName("X"))); grad_op->SetOutput("Out", this->InputGrad(framework::GradVarName("Out"))); grad_op->SetAttrMap(this->Attrs()); } }; DECLARE_NO_NEED_BUFFER_VARS_INFERER(Pad3dOpGradNoNeedBufferVarsInferer, "X"); } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR(pad3d, ops::Pad3dOp, ops::Pad3dOpMaker, ops::Pad3dOpGradMaker<paddle::framework::OpDesc>, ops::Pad3dOpGradMaker<paddle::imperative::OpBase>); REGISTER_OPERATOR(pad3d_grad, ops::Pad3dOpGrad, ops::Pad3dOpDoubleGradMaker<paddle::framework::OpDesc>, ops::Pad3dOpDoubleGradMaker<paddle::imperative::OpBase>, ops::Pad3dOpGradNoNeedBufferVarsInferer); REGISTER_OP_CPU_KERNEL(pad3d, ops::Pad3dCPUKernel<float>, ops::Pad3dCPUKernel<double>, ops::Pad3dCPUKernel<int>, ops::Pad3dCPUKernel<int64_t>); REGISTER_OP_CPU_KERNEL(pad3d_grad, ops::Pad3dGradCPUKernel<float>, ops::Pad3dGradCPUKernel<double>);
[ "noreply@github.com" ]
awesome-archive.noreply@github.com
af735fbcd5a2072b97970fdd7c01934055879640
42d1ea48097be47ec9fc1f2a07559a219ea42da0
/IDS.cpp
5d8ed203d002d27e5b97d9d7138194f76c09bea7
[]
no_license
DreamwalkerSisyphe/CS480-Project1
d5cab3dfdd1acabf21fa724029583fb3b2d1332b
597e44918b7d81c82df42534ecf3e3c84b109cbc
refs/heads/master
2022-04-27T05:20:05.317524
2020-02-12T07:35:33
2020-02-12T07:35:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,126
cpp
#include <vector> #include <iostream> #include <algorithm> #include "helpers.cpp" bool DFS(vector<int> start, int i, vector<bool> &visited, vector<int> &parent){ if(goalState(start)){ return true; } if(i <= 0){ return false; } int parentIndex = permToInt(start); vector<vector<int>> neighbors = getNeighbors(start, parent); for(vector<int> n: neighbors){ int index = permToInt(n); if((index+1) > visited.size()) visited.resize(index+1, false); if((index+1) > parent.size()) parent.resize(index+1, -1); if(!visited[index]){ visited[index] = true; parent[index] = parentIndex; } if(DFS(n, i-1, visited, parent)) return true; } return false; } bool IDS(vector<int> start, vector<bool> &visited, vector<int> &parent){ int index = permToInt(start); visited.resize(index+1, false); parent.resize(index+1, -1); if (goalState(start)){ return true; } int i = 1; while (!DFS(start, i, visited, parent)){ i++; } return true; }
[ "arickli@blue.cs.sonoma.edu" ]
arickli@blue.cs.sonoma.edu
3709468201f76d83c44b71dcfebf8d1e0f780913
4c5eec9830a56be20f145bdba89a2ab31460850f
/code/Game/AABB.h
690bb23b6b32e3ce64a78749ed1f8e4cefc75a6e
[ "MIT" ]
permissive
warzes/Game
cc0577422360628b704a9f3dcf65b4eead3e0861
bd539c086ef5c6f6d04f0290d7b15313dec264a4
refs/heads/main
2023-03-11T17:55:04.652282
2021-02-24T07:12:18
2021-02-24T07:12:18
329,565,308
0
0
null
null
null
null
UTF-8
C++
false
false
747
h
#pragma once #include "Vector2.h" class AABB { public: AABB(float x1, float y1, float x2, float y2); bool Intersects(const AABB& other); bool FitsIn(const AABB& other) const; /* Gets the distance between center of rectangles. */ glm::vec2 GetDistance(const AABB& other) const; float GetWidth() const { return maxX - minX; } float GetHeight() const { return maxY - minY; } glm::vec2 GetMin() const { return glm::vec2(minX, minY); } glm::vec2 GetMax() const { return glm::vec2(maxX, maxY); } glm::vec2 GetCenter() const { return glm::vec2(minX + (maxX - minX) / 2, minY + (maxY - minY) / 2); } glm::vec2 GetIntersectionDepth(const AABB& other) const; float minX = 0.0f; float minY = 0.0f; float maxX = 0.0f; float maxY = 0.0f; };
[ "warzes@mail.ru" ]
warzes@mail.ru
5a68b458c7a5094121d481c05e1ba471fba01a28
80f9841cf9388345e64570a4b4e873515084942f
/MFC-4.MenuDemo/MFC-4.MenuDemoView.h
8e17c7098073761fd843b02330c9d8fe7e3a10c6
[]
no_license
Bbabang-1227/ProjectMFC
02fe1e1535836ba0d6fd3cbfd5d6cb827441aa61
7d2f135df40446b2981f73d53ae01d4b3701d820
refs/heads/main
2023-05-06T13:55:56.306190
2021-06-02T00:17:42
2021-06-02T00:17:42
370,299,235
1
0
null
null
null
null
UTF-8
C++
false
false
1,155
h
 // MFC-4.MenuDemoView.h: CMFC4MenuDemoView 클래스의 인터페이스 // #pragma once class CMFC4MenuDemoView : public CView { protected: // serialization에서만 만들어집니다. CMFC4MenuDemoView() noexcept; DECLARE_DYNCREATE(CMFC4MenuDemoView) // 특성입니다. public: CMFC4MenuDemoDoc* GetDocument() const; // 작업입니다. public: // 재정의입니다. public: virtual void OnDraw(CDC* pDC); // 이 뷰를 그리기 위해 재정의되었습니다. virtual BOOL PreCreateWindow(CREATESTRUCT& cs); protected: virtual BOOL OnPreparePrinting(CPrintInfo* pInfo); virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo); virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo); // 구현입니다. public: virtual ~CMFC4MenuDemoView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // 생성된 메시지 맵 함수 protected: DECLARE_MESSAGE_MAP() }; #ifndef _DEBUG // MFC-4.MenuDemoView.cpp의 디버그 버전 inline CMFC4MenuDemoDoc* CMFC4MenuDemoView::GetDocument() const { return reinterpret_cast<CMFC4MenuDemoDoc*>(m_pDocument); } #endif
[ "guswns2811@gmail.com" ]
guswns2811@gmail.com
63a475c4dd848d69ae697ede6e52170182f624a6
ec3a754ac21137a04250ef7dc9e5152e94fb7bd3
/damBreakFine/processor1/0.9/alpha.water
64e8ec85bc4a2eddd0686791437faf85c218662f
[]
no_license
johnathoncobabe/425
2336a62cd0f575b777cd549a886a15b5799b6c72
e1ee61fb87a1078683d71a1d15131713c435cfae
refs/heads/master
2021-01-10T10:00:11.128510
2015-10-02T17:54:40
2015-10-02T17:54:40
43,466,206
0
0
null
null
null
null
UTF-8
C++
false
false
1,545
water
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 2.4.0 | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "0.9"; object alpha.water; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 0 0 0 0 0 0]; internalField uniform 0; boundaryField { leftWall { type zeroGradient; } rightWall { type zeroGradient; } lowerWall { type zeroGradient; } atmosphere { type inletOutlet; inletValue nonuniform 0(); value nonuniform 0(); } defaultFaces { type empty; } procBoundary1to0 { type processor; value uniform 0; } procBoundary1to3 { type processor; value uniform 0; } } // ************************************************************************* //
[ "johnathoncobabe@gmail.com" ]
johnathoncobabe@gmail.com
04573af14602c3a4b1d1b993c52061e777abf4e1
81c959f7894efc60a2747bf5136429d914b92f96
/cc/test/test_compositor_frame_sink.cc
2b3c260cfeebe4bede854e13f398b2f163428981
[ "BSD-3-Clause" ]
permissive
emilio/chromium
89f175c679c63e9e2b11e23c0764b02851235cfe
ab3d36b33fb3412d562033d68c716ddae6e4c3bd
refs/heads/master
2023-03-10T04:49:52.623535
2017-03-10T02:57:25
2017-03-10T02:57:25
84,578,466
2
0
null
2017-03-10T16:21:05
2017-03-10T16:21:05
null
UTF-8
C++
false
false
7,828
cc
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "cc/test/test_compositor_frame_sink.h" #include <stdint.h> #include <utility> #include "base/memory/ptr_util.h" #include "cc/output/begin_frame_args.h" #include "cc/output/compositor_frame_sink_client.h" #include "cc/output/copy_output_request.h" #include "cc/output/direct_renderer.h" #include "cc/output/output_surface.h" #include "cc/output/texture_mailbox_deleter.h" #include "cc/surfaces/compositor_frame_sink_support.h" namespace cc { static constexpr FrameSinkId kCompositorFrameSinkId(1, 1); TestCompositorFrameSink::TestCompositorFrameSink( scoped_refptr<ContextProvider> compositor_context_provider, scoped_refptr<ContextProvider> worker_context_provider, SharedBitmapManager* shared_bitmap_manager, gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager, const RendererSettings& renderer_settings, scoped_refptr<base::SingleThreadTaskRunner> task_runner, bool synchronous_composite, bool force_disable_reclaim_resources) : CompositorFrameSink(std::move(compositor_context_provider), std::move(worker_context_provider), gpu_memory_buffer_manager, shared_bitmap_manager), synchronous_composite_(synchronous_composite), renderer_settings_(renderer_settings), task_runner_(std::move(task_runner)), frame_sink_id_(kCompositorFrameSinkId), surface_manager_(new SurfaceManager), local_surface_id_allocator_(new LocalSurfaceIdAllocator()), external_begin_frame_source_(this), weak_ptr_factory_(this) { // Since this CompositorFrameSink and the Display are tightly coupled and in // the same process/thread, the LayerTreeHostImpl can reclaim resources from // the Display. But we allow tests to disable this to mimic an out-of-process // Display. capabilities_.can_force_reclaim_resources = !force_disable_reclaim_resources; // Always use sync tokens so that code paths in resource provider that deal // with sync tokens are tested. capabilities_.delegated_sync_points_required = true; } TestCompositorFrameSink::~TestCompositorFrameSink() { DCHECK(copy_requests_.empty()); } void TestCompositorFrameSink::RequestCopyOfOutput( std::unique_ptr<CopyOutputRequest> request) { copy_requests_.push_back(std::move(request)); } bool TestCompositorFrameSink::BindToClient(CompositorFrameSinkClient* client) { if (!CompositorFrameSink::BindToClient(client)) return false; std::unique_ptr<OutputSurface> display_output_surface = test_client_->CreateDisplayOutputSurface(context_provider()); bool display_context_shared_with_compositor = display_output_surface->context_provider() == context_provider(); std::unique_ptr<DisplayScheduler> scheduler; if (!synchronous_composite_) { if (renderer_settings_.disable_display_vsync) { begin_frame_source_.reset(new BackToBackBeginFrameSource( base::MakeUnique<DelayBasedTimeSource>(task_runner_.get()))); } else { begin_frame_source_.reset(new DelayBasedBeginFrameSource( base::MakeUnique<DelayBasedTimeSource>(task_runner_.get()))); begin_frame_source_->SetAuthoritativeVSyncInterval( base::TimeDelta::FromMilliseconds(1000.f / renderer_settings_.refresh_rate)); } scheduler.reset(new DisplayScheduler( task_runner_.get(), display_output_surface->capabilities().max_frames_pending)); } display_.reset( new Display(shared_bitmap_manager(), gpu_memory_buffer_manager(), renderer_settings_, frame_sink_id_, begin_frame_source_.get(), std::move(display_output_surface), std::move(scheduler), base::MakeUnique<TextureMailboxDeleter>(task_runner_.get()))); // We want the Display's OutputSurface to hear about lost context, and when // this shares a context with it we should not be listening for lost context // callbacks on the context here. if (display_context_shared_with_compositor && context_provider()) context_provider()->SetLostContextCallback(base::Closure()); support_ = base::MakeUnique<CompositorFrameSinkSupport>( this, surface_manager_.get(), frame_sink_id_, false /* is_root */, true /* handles_frame_sink_id_invalidation */, true /* needs_sync_points */); client_->SetBeginFrameSource(&external_begin_frame_source_); display_->Initialize(this, surface_manager_.get()); display_->renderer_for_testing()->SetEnlargePassTextureAmountForTesting( enlarge_pass_texture_amount_); display_->SetVisible(true); return true; } void TestCompositorFrameSink::DetachFromClient() { client_->SetBeginFrameSource(nullptr); support_ = nullptr; display_ = nullptr; local_surface_id_allocator_ = nullptr; surface_manager_ = nullptr; test_client_ = nullptr; CompositorFrameSink::DetachFromClient(); } void TestCompositorFrameSink::SubmitCompositorFrame(CompositorFrame frame) { test_client_->DisplayReceivedCompositorFrame(frame); if (!delegated_local_surface_id_.is_valid()) { delegated_local_surface_id_ = local_surface_id_allocator_->GenerateId(); } display_->SetLocalSurfaceId(delegated_local_surface_id_, frame.metadata.device_scale_factor); gfx::Size frame_size = frame.render_pass_list.back()->output_rect.size(); display_->Resize(frame_size); support_->SubmitCompositorFrame(delegated_local_surface_id_, std::move(frame)); for (std::unique_ptr<CopyOutputRequest>& copy_request : copy_requests_) { support_->RequestCopyOfSurface(std::move(copy_request)); } copy_requests_.clear(); if (!display_->has_scheduler()) { display_->DrawAndSwap(); // Post this to get a new stack frame so that we exit this function before // calling the client to tell it that it is done. task_runner_->PostTask( FROM_HERE, base::Bind(&TestCompositorFrameSink::SendCompositorFrameAckToClient, weak_ptr_factory_.GetWeakPtr())); } } void TestCompositorFrameSink::ForceReclaimResources() { if (capabilities_.can_force_reclaim_resources && delegated_local_surface_id_.is_valid()) { support_->ForceReclaimResources(); } } void TestCompositorFrameSink::DidReceiveCompositorFrameAck() { // In synchronous mode, we manually send acks and this method should not be // used. if (!display_->has_scheduler()) return; client_->DidReceiveCompositorFrameAck(); } void TestCompositorFrameSink::OnBeginFrame(const BeginFrameArgs& args) { external_begin_frame_source_.OnBeginFrame(args); } void TestCompositorFrameSink::ReclaimResources( const ReturnedResourceArray& resources) { client_->ReclaimResources(resources); } void TestCompositorFrameSink::WillDrawSurface( const LocalSurfaceId& local_surface_id, const gfx::Rect& damage_rect) {} void TestCompositorFrameSink::DisplayOutputSurfaceLost() { client_->DidLoseCompositorFrameSink(); } void TestCompositorFrameSink::DisplayWillDrawAndSwap( bool will_draw_and_swap, const RenderPassList& render_passes) { test_client_->DisplayWillDrawAndSwap(will_draw_and_swap, render_passes); } void TestCompositorFrameSink::DisplayDidDrawAndSwap() { test_client_->DisplayDidDrawAndSwap(); } void TestCompositorFrameSink::OnNeedsBeginFrames(bool needs_begin_frames) { support_->SetNeedsBeginFrame(needs_begin_frames); } void TestCompositorFrameSink::OnDidFinishFrame(const BeginFrameAck& ack) {} void TestCompositorFrameSink::SendCompositorFrameAckToClient() { client_->DidReceiveCompositorFrameAck(); } } // namespace cc
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
1652b74677ec6d61293f8b3dc64badd297907dc0
a94d3c812e33bc8306e16899cffc098b50bb32b9
/Tutorial07/CModelo.h
127750a1ad8f6c454401bd69eacb02f06592979c
[]
no_license
VICTORMCP785/Graficas_1
178382333966180f5c3176b09078c63c091856b8
3ba538048ba705569ff8810c270fd34fe504ca7a
refs/heads/master
2022-11-24T00:37:27.168225
2020-07-24T00:32:02
2020-07-24T00:32:02
251,649,124
0
0
null
null
null
null
UTF-8
C++
false
false
320
h
#pragma once #include "CMesh.h" #include <vector> class CModelo { /* CModelo { Lista de meshes Transform Propio get y set mesh }; */ public: CModelo(); ~CModelo(); std::vector <CMesh> m_Meshes; CTransform m_Transform; void Init(); void Set(CMesh Mesh); CMesh Get(unsigned int NumMesh); private: };
[ "idv18c.vcota@uartesdigitales.edu.mx" ]
idv18c.vcota@uartesdigitales.edu.mx
0423cdfce85df9caa670ab6f03d7e3782e9bb817
058355106fcf57b746afc5e9979281477c8bd34c
/.history/51.n-queens_20200725114732.cpp
32c85585c57466475e2c9e72455a9c40a64314b3
[]
no_license
Subzero-10/leetcode
ff24f133f984b86eac686ed9b9cccbefb15c9dd8
701ec3dd4020970ecb55734de0355c8666849578
refs/heads/master
2022-12-24T19:03:16.482923
2020-10-11T09:25:29
2020-10-11T09:25:29
291,388,415
0
0
null
null
null
null
UTF-8
C++
false
false
2,881
cpp
/* * @lc app=leetcode id=51 lang=cpp * * [51] N-Queens * * https://leetcode.com/problems/n-queens/description/ * * algorithms * Hard (44.01%) * Likes: 1920 * Dislikes: 73 * Total Accepted: 204.2K * Total Submissions: 441K * Testcase Example: '4' * * The n-queens puzzle is the problem of placing n queens on an n×n chessboard * such that no two queens attack each other. * * * * Given an integer n, return all distinct solutions to the n-queens puzzle. * * Each solution contains a distinct board configuration of the n-queens' * placement, where 'Q' and '.' both indicate a queen and an empty space * respectively. * * Example: * * * Input: 4 * Output: [ * ⁠[".Q..", // Solution 1 * ⁠ "...Q", * ⁠ "Q...", * ⁠ "..Q."], * * ⁠["..Q.", // Solution 2 * ⁠ "Q...", * ⁠ "...Q", * ⁠ ".Q.."] * ] * Explanation: There exist two distinct solutions to the 4-queens puzzle as * shown above. * * */ // @lc code=start class Solution { public: vector<vector<string>> solveNQueens(int n) { string queen(n,'Q'); vector<string> chessboard(n,queen); vector<vector<string>> output; haveQ(0,0,n,chessboard,output); return output; } bool haveQ(int i, int j, int n, vector<string>& chessboardtem,vector<vector<string>>& output) { string dot(n,'.'); if (i==n) { output.push_back(chessboardtem); return false; } if (chessboardtem[i] == dot) { return false; } else { for (i; i < n; i++) { for (j; j < n; j++) { vector<string> chessboardtem1(chessboardtem); if (chessboardtem[i][j] == 'Q') { modifyBoard(i, j, n, chessboardtem1); } else { continue; } haveQ(i+1,0,n,chessboardtem1,output); } return false; } return true; } } void modifyBoard(int i, int j, int n, vector<string>& chessboardtem) { for (int k = 0; k < n; k++) { chessboardtem[k][j] = '.'; chessboardtem[i][k] = '.'; if (i-k>=0&&j-k>=0) { chessboardtem[i-k][j-k] = '.'; } if (i-k>=0&&j+k<n) { chessboardtem[i-k][j+k] = '.'; } if (i+k<n&&j+k<n) { chessboardtem[i+k][j+k] = '.'; } if (i+k<n&&j-k>=0) { chessboardtem[i+k][j-k] = '.'; } } chessboardtem[i][j] = 'Q'; } }; // @lc code=end
[ "shizheng961111@gmail.com" ]
shizheng961111@gmail.com
e1af420e2398d947712468d53a7d06e7650602be
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/squid/gumtree/squid_repos_function_2171_squid-3.4.14.cpp
0591f5c1d0e2633df243ce6b9393dcbfb7908370
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
417
cpp
static void storeDigestRebuildResume(void) { assert(sd_state.rebuild_lock); assert(!sd_state.rewrite_lock); sd_state.theSearch = Store::Root().search(NULL, NULL); /* resize or clear */ if (!storeDigestResize()) cacheDigestClear(store_digest); /* not clean()! */ memset(&sd_stats, 0, sizeof(sd_stats)); eventAdd("storeDigestRebuildStep", storeDigestRebuildStep, NULL, 0.0, 1); }
[ "993273596@qq.com" ]
993273596@qq.com
eec0c94f45553fb50d4f32f0e424a94164ac0d13
95d81d0143275d51577ff6493afd80db392475a3
/ch15/15.35/OrQuery.cpp
ac0e095b0b437143892c98f3f976f39269786861
[ "Apache-2.0" ]
permissive
CSLP/Cpp-Primer-5th-Exercises
aa5bb0bc0c8ff4326bf08f60d97dd0e407dc895a
29ea2e3f4bd32674eb518f431bb1b10aecfaa216
refs/heads/master
2020-04-29T04:26:54.668388
2020-01-16T07:19:27
2020-01-16T07:19:27
175,847,389
0
0
Apache-2.0
2019-03-15T15:37:29
2019-03-15T15:37:28
null
UTF-8
C++
false
false
683
cpp
#include "OrQuery.h" #include "TextQuery.h" #include "QueryResult.h" #if DEBUG_LEVEL >= 1 #include <iostream> #endif QueryResult OrQuery::eval(const TextQuery &t) const { #if DEBUG_LEVEL >= 1 std::cout << "OrQuery::eval" << std::endl; #endif // TODO return QueryResult(); } Query operator|(const Query &lhs, const Query &rhs) { #if DEBUG_LEVEL >= 1 std::cout << "Query operator|(const Query &, const Query &)" << std::endl; #endif // NOTE we cannot use `std::make_shared` here, because the type of the // dynamically created object and the type of the object pointed by shared // pointer are different. return std::shared_ptr<Query_base>(new OrQuery(lhs, rhs)); }
[ "jaege@163.com" ]
jaege@163.com
9ce46fe2f4bca532df22d358201f0cf8125f512d
ea81cc90ebb2e6307cb539eb9c1c96a033d16818
/include/cilantro/spectral_clustering.hpp
1931431dfc9a886e22791fe1ffd7821e855f644b
[ "MIT" ]
permissive
3d-scan/cilantro
e833ca686a81fcfe7ebff934790345ea7613df71
c3efb0e3fc00f1ab1a095d372a26f2e0eb872e31
refs/heads/master
2021-05-01T07:54:18.325838
2018-02-09T06:43:40
2018-02-09T06:43:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
19,643
hpp
#pragma once #include <memory> #include <cilantro/kmeans.hpp> #include <cilantro/3rd_party/spectra/SymEigsSolver.h> #include <cilantro/3rd_party/spectra/SymGEigsSolver.h> namespace cilantro { template <typename ScalarT> class SpectraDiagonalInverseBop { private: const int dim_; Eigen::Matrix<ScalarT,Eigen::Dynamic,1> diag_vals_; Eigen::Matrix<ScalarT,Eigen::Dynamic,1> diag_vals_inv_; public: SpectraDiagonalInverseBop(const Eigen::Matrix<ScalarT,Eigen::Dynamic,Eigen::Dynamic>& D) : dim_(D.rows()), diag_vals_(D.diagonal()), diag_vals_inv_(diag_vals_.cwiseInverse()) {} SpectraDiagonalInverseBop(const Eigen::SparseMatrix<ScalarT>& D) : dim_(D.rows()), diag_vals_(D.diagonal()), diag_vals_inv_(diag_vals_.cwiseInverse()) {} inline int rows() const { return dim_; } inline int cols() const { return dim_; } // y_out = inv(B) * x_in void solve(const ScalarT* x_in, ScalarT* y_out) const { Eigen::Map<const Eigen::Matrix<ScalarT,Eigen::Dynamic,1>> x(x_in, dim_); Eigen::Map<Eigen::Matrix<ScalarT,Eigen::Dynamic,1>> y(y_out, dim_); y.noalias() = diag_vals_inv_.cwiseProduct(x); } // y_out = B * x_in void mat_prod(const ScalarT* x_in, ScalarT* y_out) const { Eigen::Map<const Eigen::Matrix<ScalarT,Eigen::Dynamic,1>> x(x_in, dim_); Eigen::Map<Eigen::Matrix<ScalarT,Eigen::Dynamic,1>> y(y_out, dim_); y.noalias() = diag_vals_.cwiseProduct(x); } }; enum struct GraphLaplacianType {UNNORMALIZED, NORMALIZED_SYMMETRIC, NORMALIZED_RANDOM_WALK}; // If positive, EigenDim is the embedding dimension (and also the number of clusters). // Set to Eigen::Dynamic for runtime setting. template <typename ScalarT, ptrdiff_t EigenDim = Eigen::Dynamic> class SpectralClustering { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW // Dense input // Number of clusters (embedding dimension) set at compile time (EigenDim template parameter) template <ptrdiff_t Dim = EigenDim, class = typename std::enable_if<Dim != Eigen::Dynamic>::type> SpectralClustering(const Eigen::Ref<const Eigen::Matrix<ScalarT,Eigen::Dynamic,Eigen::Dynamic>> &affinities, const GraphLaplacianType &laplacian_type = GraphLaplacianType::NORMALIZED_RANDOM_WALK, size_t kmeans_max_iter = 100, ScalarT kmeans_conv_tol = std::numeric_limits<ScalarT>::epsilon(), bool kmeans_use_kd_tree = false) { compute_dense_(affinities, EigenDim, false, laplacian_type, kmeans_max_iter, kmeans_conv_tol, kmeans_use_kd_tree); } // Dense input // Number of clusters (embedding dimension) set at runtime (EigenDim == Eigen::Dynamic) // If estimate_num_clusters == true, chooses number of clusters in [1, max_num_clusters] based on eigenvalue // distribution. Otherwise, returns max_num_clusters clusters. template <ptrdiff_t Dim = EigenDim, class = typename std::enable_if<Dim == Eigen::Dynamic>::type> SpectralClustering(const Eigen::Ref<const Eigen::Matrix<ScalarT,Eigen::Dynamic,Eigen::Dynamic>> &affinities, size_t max_num_clusters, bool estimate_num_clusters = false, const GraphLaplacianType &laplacian_type = GraphLaplacianType::NORMALIZED_RANDOM_WALK, size_t kmeans_max_iter = 100, ScalarT kmeans_conv_tol = std::numeric_limits<ScalarT>::epsilon(), bool kmeans_use_kd_tree = false) { if (max_num_clusters > 0 && max_num_clusters < affinities.rows()) { compute_dense_(affinities, max_num_clusters, estimate_num_clusters, laplacian_type, kmeans_max_iter, kmeans_conv_tol, kmeans_use_kd_tree); } else { compute_dense_(affinities, 2, false, laplacian_type, kmeans_max_iter, kmeans_conv_tol, kmeans_use_kd_tree); } } // Sparse input // Number of clusters (embedding dimension) set at compile time (EigenDim template parameter) template <ptrdiff_t Dim = EigenDim, class = typename std::enable_if<Dim != Eigen::Dynamic>::type> SpectralClustering(const Eigen::SparseMatrix<ScalarT> &affinities, const GraphLaplacianType &laplacian_type = GraphLaplacianType::NORMALIZED_RANDOM_WALK, size_t kmeans_max_iter = 100, ScalarT kmeans_conv_tol = std::numeric_limits<ScalarT>::epsilon(), bool kmeans_use_kd_tree = false) { compute_sparse_(affinities, EigenDim, false, laplacian_type, kmeans_max_iter, kmeans_conv_tol, kmeans_use_kd_tree); } // Sparse input // Number of clusters (embedding dimension) set at runtime (EigenDim == Eigen::Dynamic) // If estimate_num_clusters == true, chooses number of clusters in [1, max_num_clusters] based on eigenvalue // distribution. Otherwise, returns max_num_clusters clusters. template <ptrdiff_t Dim = EigenDim, class = typename std::enable_if<Dim == Eigen::Dynamic>::type> SpectralClustering(const Eigen::SparseMatrix<ScalarT> &affinities, size_t max_num_clusters, bool estimate_num_clusters = false, const GraphLaplacianType &laplacian_type = GraphLaplacianType::NORMALIZED_RANDOM_WALK, size_t kmeans_max_iter = 100, ScalarT kmeans_conv_tol = std::numeric_limits<ScalarT>::epsilon(), bool kmeans_use_kd_tree = false) { if (max_num_clusters > 0 && max_num_clusters < affinities.rows()) { compute_sparse_(affinities, max_num_clusters, estimate_num_clusters, laplacian_type, kmeans_max_iter, kmeans_conv_tol, kmeans_use_kd_tree); } else { compute_sparse_(affinities, 2, false, laplacian_type, kmeans_max_iter, kmeans_conv_tol, kmeans_use_kd_tree); } } ~SpectralClustering() {} inline const VectorSet<ScalarT,EigenDim>& getEmbeddedPoints() const { return embedded_points_; } inline const Vector<ScalarT,Eigen::Dynamic>& getComputedEigenValues() const { return eigenvalues_; } inline const std::vector<std::vector<size_t>>& getClusterPointIndices() const { return clusterer_->getClusterPointIndices(); } inline const std::vector<size_t>& getClusterIndexMap() const { return clusterer_->getClusterIndexMap(); } inline size_t getNumberOfClusters() const { return embedded_points_.rows(); } inline const KMeans<ScalarT,EigenDim>& getClusterer() const { return *clusterer_; } private: Vector<ScalarT,Eigen::Dynamic> eigenvalues_; VectorSet<ScalarT,EigenDim> embedded_points_; std::shared_ptr<KMeans<ScalarT,EigenDim>> clusterer_; void compute_dense_(const Eigen::Ref<const Eigen::Matrix<ScalarT,Eigen::Dynamic,Eigen::Dynamic>> &affinities, size_t max_num_clusters, bool estimate_num_clusters, const GraphLaplacianType &laplacian_type, size_t kmeans_max_iter, ScalarT kmeans_conv_tol, bool kmeans_use_kd_tree) { size_t num_clusters = max_num_clusters; size_t num_eigenvalues = (estimate_num_clusters) ? std::min(max_num_clusters+1, (size_t)(affinities.rows()-1)) : max_num_clusters; ScalarT conv_tol = (std::is_same<ScalarT,float>::value) ? 1e-7 : 1e-10; size_t n_conv = 0; size_t max_iter = 1000; switch (laplacian_type) { case GraphLaplacianType::UNNORMALIZED: { Eigen::Matrix<ScalarT,Eigen::Dynamic,Eigen::Dynamic> L = affinities.colwise().sum().asDiagonal(); L -= affinities; Spectra::DenseSymMatProd<ScalarT> op(L); Spectra::SymEigsSolver<ScalarT, Spectra::SMALLEST_MAGN, Spectra::DenseSymMatProd<ScalarT>> eig(&op, num_eigenvalues, std::min(2*num_eigenvalues, (size_t)affinities.rows())); eig.init(); do { n_conv = eig.compute(max_iter, conv_tol, Spectra::SMALLEST_MAGN); max_iter *= 2; } while (n_conv != num_eigenvalues); eigenvalues_ = eig.eigenvalues(); for (size_t i = 0; i < eigenvalues_.rows(); i++) { if (eigenvalues_[i] < 0.0) eigenvalues_[i] = 0.0; } if (estimate_num_clusters) { num_clusters = estimate_number_of_clusters_(eigenvalues_, max_num_clusters); } embedded_points_ = eig.eigenvectors(num_clusters).transpose(); break; } case GraphLaplacianType::NORMALIZED_SYMMETRIC: { Eigen::Matrix<ScalarT,Eigen::Dynamic,Eigen::Dynamic> Dtm12 = affinities.colwise().sum().array().rsqrt().matrix().asDiagonal(); Eigen::Matrix<ScalarT,Eigen::Dynamic,Eigen::Dynamic> L = Eigen::Matrix<ScalarT,Eigen::Dynamic,Eigen::Dynamic>::Identity(affinities.rows(),affinities.cols()) - Dtm12*affinities*Dtm12; Spectra::DenseSymMatProd<ScalarT> op(L); Spectra::SymEigsSolver<ScalarT, Spectra::SMALLEST_MAGN, Spectra::DenseSymMatProd<ScalarT>> eig(&op, num_eigenvalues, std::min(2*num_eigenvalues, (size_t)affinities.rows())); eig.init(); do { n_conv = eig.compute(max_iter, conv_tol, Spectra::SMALLEST_MAGN); max_iter *= 2; } while (n_conv != num_eigenvalues); eigenvalues_ = eig.eigenvalues(); for (size_t i = 0; i < eigenvalues_.rows(); i++) { if (eigenvalues_[i] < 0.0) eigenvalues_[i] = 0.0; } if (estimate_num_clusters) { num_clusters = estimate_number_of_clusters_(eigenvalues_, max_num_clusters); } embedded_points_ = eig.eigenvectors(num_clusters).transpose(); for (size_t i = 0; i < embedded_points_.cols(); i++) { ScalarT scale = 1.0/embedded_points_.col(i).norm(); if (std::isfinite(scale)) embedded_points_.col(i) *= scale; } break; } case GraphLaplacianType::NORMALIZED_RANDOM_WALK: { Eigen::Matrix<ScalarT,Eigen::Dynamic,Eigen::Dynamic> D = affinities.colwise().sum().asDiagonal(); Eigen::Matrix<ScalarT,Eigen::Dynamic,Eigen::Dynamic> L = D - affinities; Spectra::DenseSymMatProd<ScalarT> op(L); SpectraDiagonalInverseBop<ScalarT> Bop(D); Spectra::SymGEigsSolver<ScalarT, Spectra::SMALLEST_MAGN, Spectra::DenseSymMatProd<ScalarT>, SpectraDiagonalInverseBop<ScalarT>, Spectra::GEIGS_REGULAR_INVERSE> eig(&op, &Bop, num_eigenvalues, std::min(2*num_eigenvalues, (size_t)affinities.rows())); eig.init(); do { n_conv = eig.compute(max_iter, conv_tol, Spectra::SMALLEST_MAGN); max_iter *= 2; } while (n_conv != num_eigenvalues); eigenvalues_ = eig.eigenvalues(); for (size_t i = 0; i < eigenvalues_.rows(); i++) { if (eigenvalues_[i] < 0.0) eigenvalues_[i] = 0.0; } if (estimate_num_clusters) { num_clusters = estimate_number_of_clusters_(eigenvalues_, max_num_clusters); } embedded_points_ = eig.eigenvectors(num_clusters).transpose(); break; } } clusterer_.reset(new KMeans<ScalarT,EigenDim>(embedded_points_)); clusterer_->cluster(num_clusters, kmeans_max_iter, kmeans_conv_tol, kmeans_use_kd_tree); } void compute_sparse_(const Eigen::SparseMatrix<ScalarT> &affinities, size_t max_num_clusters, bool estimate_num_clusters, const GraphLaplacianType &laplacian_type, size_t kmeans_max_iter, ScalarT kmeans_conv_tol, bool kmeans_use_kd_tree) { size_t num_clusters = max_num_clusters; size_t num_eigenvalues = (estimate_num_clusters) ? std::min(max_num_clusters+1, (size_t)(affinities.rows()-1)) : max_num_clusters; ScalarT conv_tol = (std::is_same<ScalarT,float>::value) ? 1e-7 : 1e-10; size_t n_conv = 0; size_t max_iter = 1000; switch (laplacian_type) { case GraphLaplacianType::UNNORMALIZED: { Eigen::SparseMatrix<ScalarT> D(affinities.rows(),affinities.cols()); D.reserve(Eigen::VectorXi::Ones(affinities.rows())); for (size_t i = 0; i < affinities.cols(); i++) { D.insert(i,i) = affinities.col(i).sum(); } Eigen::SparseMatrix<ScalarT> L = D - affinities; Spectra::SparseSymMatProd<ScalarT> op(L); Spectra::SymEigsSolver<ScalarT, Spectra::SMALLEST_MAGN, Spectra::SparseSymMatProd<ScalarT>> eig(&op, num_eigenvalues, std::min(2*num_eigenvalues, (size_t)affinities.rows())); eig.init(); do { n_conv = eig.compute(max_iter, conv_tol, Spectra::SMALLEST_MAGN); max_iter *= 2; } while (n_conv != num_eigenvalues); eigenvalues_ = eig.eigenvalues(); for (size_t i = 0; i < eigenvalues_.rows(); i++) { if (eigenvalues_[i] < 0.0) eigenvalues_[i] = 0.0; } if (estimate_num_clusters) { num_clusters = estimate_number_of_clusters_(eigenvalues_, max_num_clusters); } embedded_points_ = eig.eigenvectors(num_clusters).transpose(); break; } case GraphLaplacianType::NORMALIZED_SYMMETRIC: { Eigen::SparseMatrix<ScalarT> Dtm12(affinities.rows(),affinities.cols()); Dtm12.reserve(Eigen::VectorXi::Ones(affinities.rows())); for (size_t i = 0; i < affinities.cols(); i++) { Dtm12.insert(i,i) = 1.0/std::sqrt(affinities.col(i).sum()); } Eigen::SparseMatrix<ScalarT> L(affinities.rows(),affinities.cols()); L.setIdentity(); L -= Dtm12*affinities*Dtm12; Spectra::SparseSymMatProd<ScalarT> op(L); Spectra::SymEigsSolver<ScalarT, Spectra::SMALLEST_MAGN, Spectra::SparseSymMatProd<ScalarT>> eig(&op, num_eigenvalues, std::min(2*num_eigenvalues, (size_t)affinities.rows())); eig.init(); do { n_conv = eig.compute(max_iter, conv_tol, Spectra::SMALLEST_MAGN); max_iter *= 2; } while (n_conv != num_eigenvalues); eigenvalues_ = eig.eigenvalues(); for (size_t i = 0; i < eigenvalues_.rows(); i++) { if (eigenvalues_[i] < 0.0) eigenvalues_[i] = 0.0; } if (estimate_num_clusters) { num_clusters = estimate_number_of_clusters_(eigenvalues_, max_num_clusters); } embedded_points_ = eig.eigenvectors(num_clusters).transpose(); for (size_t i = 0; i < embedded_points_.cols(); i++) { ScalarT scale = 1.0/embedded_points_.col(i).norm(); if (std::isfinite(scale)) embedded_points_.col(i) *= scale; } break; } case GraphLaplacianType::NORMALIZED_RANDOM_WALK: { Eigen::SparseMatrix<ScalarT> D(affinities.rows(),affinities.cols()); D.reserve(Eigen::VectorXi::Ones(affinities.rows())); for (size_t i = 0; i < affinities.cols(); i++) { D.insert(i,i) = affinities.col(i).sum(); } Eigen::SparseMatrix<ScalarT> L = D - affinities; Spectra::SparseSymMatProd<ScalarT> op(L); SpectraDiagonalInverseBop<ScalarT> Bop(D); Spectra::SymGEigsSolver<ScalarT, Spectra::SMALLEST_MAGN, Spectra::SparseSymMatProd<ScalarT>, SpectraDiagonalInverseBop<ScalarT>, Spectra::GEIGS_REGULAR_INVERSE> eig(&op, &Bop, num_eigenvalues, std::min(2*num_eigenvalues, (size_t)affinities.rows())); eig.init(); do { n_conv = eig.compute(max_iter, conv_tol, Spectra::SMALLEST_MAGN); max_iter *= 2; } while (n_conv != num_eigenvalues); eigenvalues_ = eig.eigenvalues(); for (size_t i = 0; i < eigenvalues_.rows(); i++) { if (eigenvalues_[i] < 0.0) eigenvalues_[i] = 0.0; } if (estimate_num_clusters) { num_clusters = estimate_number_of_clusters_(eigenvalues_, max_num_clusters); } embedded_points_ = eig.eigenvectors(num_clusters).transpose(); break; } } clusterer_.reset(new KMeans<ScalarT,EigenDim>(embedded_points_)); clusterer_->cluster(num_clusters, kmeans_max_iter, kmeans_conv_tol, kmeans_use_kd_tree); } size_t estimate_number_of_clusters_(const Eigen::Ref<const Eigen::Matrix<ScalarT,EigenDim,1>> &eigenvalues, size_t max_num_clusters) { ScalarT min_val = std::numeric_limits<ScalarT>::infinity(); ScalarT max_val = -std::numeric_limits<ScalarT>::infinity(); ScalarT max_diff = eigenvalues[0]; size_t max_ind = 0; for (size_t i = 0; i < eigenvalues.rows() - 1; i++) { ScalarT diff = eigenvalues[i+1] - eigenvalues[i]; if (diff > max_diff) { max_diff = diff; max_ind = i; } if (eigenvalues[i] < min_val) min_val = eigenvalues[i]; if (eigenvalues[i] > max_val) max_val = eigenvalues[i]; } if (eigenvalues[eigenvalues.rows()-1] < min_val) min_val = eigenvalues[eigenvalues.rows()-1]; if (eigenvalues[eigenvalues.rows()-1] > max_val) max_val = eigenvalues[eigenvalues.rows()-1]; if (max_val - min_val < std::numeric_limits<ScalarT>::epsilon()) return max_num_clusters; return max_ind + 1; } }; }
[ "kzampog@gmail.com" ]
kzampog@gmail.com
df349242a64db9f7bba6c5ce1512ca113f28cb7c
7f7d8aa917816bafe26c4252ad28529572f0e32e
/converter/Converters/CppVulkan/CppVulkanConverter.h
b2888a92f8ee4e818f380455035d49a9f4bf5cbe
[ "BSD-2-Clause" ]
permissive
azhirnov/vkTraceConverter
1b4cdfa28d61f88eecc04b98135b91883b19893b
1f8846eccc38ac9012c4259728f4710ad4296a61
refs/heads/master
2021-07-01T01:19:31.353109
2018-10-07T11:38:47
2018-10-07T11:38:47
148,522,177
6
0
null
null
null
null
UTF-8
C++
false
false
6,628
h
// Copyright (c) 2018, Zhirnov Andrey. For more information see 'LICENSE' /* Converts vktrace to c++ code with raw vulkan api calls. */ #pragma once #include "Analyzer/Default/ImageAnalyzer.h" #include "Analyzer/Default/BufferAnalyzer.h" #include "Analyzer/Default/MemoryObjAnalyzer.h" #include "Analyzer/Default/MemoryTransferAnalyzer.h" #include "Analyzer/Default/SwapchainAnalyzer.h" #include "Analyzer/Default/DeviceAnalyzer.h" #include "Analyzer/Default/QueueAnalyzer.h" #include "Analyzer/Default/AllResourcesBookmarks.h" #include "Converters/Converter.h" #include "Converters/Utils/ResRemapper.h" #include "Converters/Utils/NameSerializer.h" namespace VTC { // // C++ Vulkan Source Converter // class CppVulkanConverter { // types private: using DataID = uint; // same as DataID in engine struct DataAccessInfo { DataID dataId = ~0u; uint64_t offset = 0; uint64_t size = 0; DataAccessInfo () {} DataAccessInfo (uint64_t offset, uint64_t size) : offset{offset}, size{size} {} ND_ bool operator == (const DataAccessInfo &rhs) const { return offset == rhs.offset and size == rhs.size; } }; struct DataAccessInfoHash { ND_ size_t operator () (const DataAccessInfo &x) const { return size_t(HashOf(x.offset) + HashOf(x.size)); } }; using DatAccessInFile_t = HashMap< DataAccessInfo, HashSet<FrameID>, DataAccessInfoHash >; using DataAccess_t = HashMap< String, DatAccessInFile_t >; using InitializedResources_t = HashSet< ResourceID >; using Config_t = ConverterConfig::VulkanCppSource; // variables private: const Config_t _config; const fs::path _directory; const fs::path _dataDir; const String _inputFile; const String _projName; AppTrace const * _appTrace = null; ImageAnalyzer const* _imageAnalyzer = null; BufferAnalyzer const* _bufferAnalyzer = null; MemoryObjAnalyzer const* _memoryObjAnalyzer = null; MemoryTransferAnalyzer const* _memTransferAnalyzer = null; SwapchainAnalyzer const* _swapchainAnalyzer = null; DeviceAnalyzer const* _deviceAnalyzer = null; QueueAnalyzer const* _queueAnalyzer = null; AllResourcesBookmarks const* _resourcesBookmarks = null; mutable NameSerializer _nameSerializer; UniquePtr<ResRemapper> _resRemapper; mutable String _tempStr1; mutable String _tempStr2; mutable InitializedResources_t _initializedResources; // used in _Remap*** DataAccess_t _dataAccess; DataID _dataCounter = 0; uint64_t _dataSize = 0; // methods public: CppVulkanConverter (const ConverterConfig &cfg); bool Run (const AppTrace &trace); private: bool _ConvertFrame1 (FrameID index, const TraceRange &trace); bool _ConvertFrame2 (FrameID index, const TraceRange &trace); bool _ConvertFunction (const TraceRange::Iterator &iter, FrameID frameId, INOUT String &src); bool _ConvertVkFunction (const TraceRange::Iterator &iter, INOUT String &src) const; bool _GenCommonFile (FrameID first, FrameID last) const; bool _GenCMakeFile (FrameID first, FrameID last) const; bool _GenMain (FrameID first, FrameID last) const; bool _StoreFile (const fs::path &filename, StringView data) const; ND_ DataID _RequestData (const String &filename, uint64_t offset, uint64_t size, FrameID frameId); ND_ DataID _RequestData (const String &filename, const TraceRange::Iterator &iter, const void* hdr, const void *member, uint64_t size, FrameID frameId); bool _InitializeResources (INOUT String &str) const; bool _SetupDevice (TraceRange::Bookmark pos, INOUT String &str) const; bool _SetupQueues (const DeviceAnalyzer::LogicalDeviceInfo_t &deviceInfo, INOUT String &str) const; bool _SetupSwapchain (const SwapchainAnalyzer::SwapchainInfo_t &swapchain, INOUT String &str) const; bool _SetupResourceFiles (INOUT String &str) const; bool _SetupDrawFrames (FrameID first, FrameID last, INOUT String &str) const; // remap queue family bool _OnCreateCommandPool (const TraceRange::Iterator &, INOUT String &src) const; bool _OnCreateBuffer (const TraceRange::Iterator &, INOUT String &src) const; bool _OnCreateImage (const TraceRange::Iterator &, INOUT String &src) const; bool _OnCmdWaitEvents (const TraceRange::Iterator &, INOUT String &src) const; bool _OnCmdPipelineBarrier (const TraceRange::Iterator &, INOUT String &src); // remap memory bool _OnBindBufferMemory (const TraceRange::Iterator &, INOUT String &src) const; bool _OnBindImageMemory (const TraceRange::Iterator &, INOUT String &src) const; bool _OnBindBufferMemory2 (const TraceRange::Iterator &, INOUT String &src) const; bool _OnBindImageMemory2 (const TraceRange::Iterator &, INOUT String &src) const; bool _OnAllocateMemory (const TraceRange::Iterator &, INOUT String &src) const; bool _OnFreeMemory (const TraceRange::Iterator &, INOUT String &src) const; bool _OnMapMemory (const TraceRange::Iterator &, INOUT String &src) const; bool _OnUnmapMemory (const TraceRange::Iterator &, INOUT String &src) const; bool _OnFlushMappedMemoryRanges (const TraceRange::Iterator &, FrameID frameId, INOUT String &src); bool _OnDestroyImage (const TraceRange::Iterator &, INOUT String &src) const; bool _OnDestroyBuffer (const TraceRange::Iterator &, INOUT String &src) const; bool _OverrideMapMemory (const TraceRange::Iterator &, INOUT String &src) const; bool _OverrideUnmapMemory (const TraceRange::Iterator &, INOUT String &src) const; bool _OverrideFlushMappedMemoryRanges (const TraceRange::Iterator &, FrameID frameId, INOUT String &src); bool _RemapBufferMemory (const TraceRange::Iterator &, INOUT String &src) const; bool _RemapImageMemory (const TraceRange::Iterator &, INOUT String &src) const; bool _RemapBufferMemory2 (const TraceRange::Iterator &, INOUT String &src) const; bool _RemapImageMemory2 (const TraceRange::Iterator &, INOUT String &src) const; bool _RemapFlushMemoryRanges (const TraceRange::Iterator &, FrameID frameId, INOUT String &src); bool _FreeImageMemory (const TraceRange::Iterator &, INOUT String &src) const; bool _FreeBufferMemory (const TraceRange::Iterator &, INOUT String &src) const; // remap swapchain images bool _OnAcquireNextImage (const TraceRange::Iterator &, INOUT String &src) const; bool _OnQueuePresent (const TraceRange::Iterator &, INOUT String &src) const; // use loadable data bool _OnCreateShaderModule (const TraceRange::Iterator &, FrameID frameId, INOUT String &src); bool _OnCreatePipelineCache (const TraceRange::Iterator &, INOUT String &src); }; } // VTC
[ "zh1dron@gmail.com" ]
zh1dron@gmail.com
e5d2f3231ad90511a0fd32be409b67033e8f8cf9
69add2b44a24c48961d53c64014a7870dba12610
/AtCoder_Beginner_Contest_010_B/Source.cpp
cf6e9ae9848319d1017fe070b3313e0415e28aef
[]
no_license
strimuer213p/AtCoder_Beginner_Contest_010_B
48140315746372f5fca03edbb4bd1a690bbfb639
e5fd637f47eb5854b8719b2f910bd6ee4b89b9f8
refs/heads/master
2020-03-15T02:21:36.869595
2018-05-02T23:19:46
2018-05-02T23:19:46
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,896
cpp
/* 問題文 高橋君の秘書のなぎさちゃんは、高橋君が大好きです。つまり、高橋君もなぎさちゃんの事が大好きであるに違いありません。 そのことを確認するために、庭に咲いている花で、花占いをすることにしました。 「好き」、「嫌い」、「好き」、「嫌い」、「好き」、「嫌い」……。 おかしいです。高橋君はなぎさちゃんの事が好きであるはずなのに、花占いの結果は「嫌い」でした。 これは、花が悪いに違いありません。 なぎさちゃんは、使用人達に、花占いの結果が「嫌い」にならないように、花びらを毟るよう命じました。 なぎさちゃんの花占いは、2つのパターンがあります。 一つは、「好き」「嫌い」を交互に言いながら、花びらを 1 枚ずつ毟っていくパターンです。 もう一つは、「好き」「嫌い」「大好き」の 3 つを繰り返しながら、花びらを1枚ずつ毟っていくパターンです。 どちらのパターンにおいても、最後に言った言葉が、花占いの結果となります。 なぎさちゃんの使用人であるあなたは、なぎさちゃんがどちらのパターンで花占いをしたときも、「嫌い」にならないように、 花びらを事前に毟ってあげる必要があります。 庭に咲いている花の数と、その花びらの枚数が与えられるので、花びらを毟る必要のある枚数を出力してください。 */ #include<iostream> #include<vector> int main() { int n,ans=0; std::cin >> n; std::vector<int> v(n); for (int& x : v) { std::cin >> x; } for (int i = 0; i < v.size(); i++) { int m = v[i]; while (m % 3 == 2 || m% 2 == 0) { m--; ans++; } } std::cout << ans << std::endl; return 0; }
[ "stoneriver213@outlook.jp" ]
stoneriver213@outlook.jp
28da282664d59ff61fc6831a2860f61104244b4f
6aeadfb58eb9982c244ec938dcb3ff3d87824b15
/Capacitor.h
dcdfff47239a78026d4ce68cfa7c9570a99f5577
[]
no_license
kong0115/Class
f6ad428a19133898ac1b6b8cfb8e85d69099aa64
b2499020eb7b5c431d04b51067537777bbd82d05
refs/heads/master
2020-04-03T07:10:32.348987
2018-10-28T17:11:15
2018-10-28T17:11:15
155,095,151
0
0
null
null
null
null
UTF-8
C++
false
false
2,168
h
//class specification file that stores class declaration for Capacitor class #ifndef CAPACITOR_H_ //This directive tells the preprocessor to see if a constant named CAPACITOR_H_ has not been previously created with a #define directive. #define CAPACITOR_H_ //If the CAPACITOR_H_ constant has not been defined, the rest of the file is included. If the constant has been defined, everything between the #ifndef and #endif is skipped. #include "ElectricComponent.h" //Needed to use ElectricComponent class. " "indicates the file is located in the current project directory. //Create a Capacitor derived class that inherits information from the ElectricComponent base class class Capacitor : public ElectricComponent {//Public class access specification private://making the member variables private to protects critical data from being accidentally modified, they cannot be accessed by statements outside the class double cValue;//create a double variable to store the capacitor value const string cUnit = " Farad(s)";//create a string variable to store the capacitor unit. I don't want the unit to be changed, so I use a const string string cDescription; //create a string variable to store the printable description of the capacitor public://public access specifier is used for member functions which means that they can be called from statements outside the class. Capacitor(double cV); //create a constructor that takes one parameter for the capacitor value as double virtual ~Capacitor(); //create a virtual destructor that perform shutdown procedures when the object is destroyed. ////Inline member function virtual double getValue() const //redefine the getValue function in the base class { return cValue; //return the capacitor value as double } virtual string getUnit() const //redefine the getUnit function in the base class { return cUnit; //return the capacitor unit as string } virtual string getDescription() const //redefine the getDescription function in the base class { return cDescription; //return the capacitor description as string } }; #endif //Needed to end the #ifndef statement
[ "noreply@github.com" ]
kong0115.noreply@github.com
d96d3f073c68095316896add7874ac8110b3fde9
a32e8428fe087f3fbc6b89de9fa16e68449ba9b4
/src/json.hpp
233fa19745877ac7acd0a6fc19f8b4c389bf5547
[]
no_license
Taywee/cpp-dnd-character-generator
43aed3d7c8f2baa0d9c68897af37ca486a3a3fcd
1a03def80d603d106b2f1b9b69a89b188f7915b8
refs/heads/main
2023-06-28T16:41:39.413250
2021-07-29T15:34:44
2021-07-29T15:34:44
390,598,859
0
0
null
2021-07-29T04:22:58
2021-07-29T04:22:57
null
UTF-8
C++
false
false
959,898
hpp
/* __ _____ _____ _____ __| | __| | | | JSON for Modern C++ | | |__ | | | | | | version 3.9.1 |_____|_____|_____|_|___| https://github.com/nlohmann/json Licensed under the MIT License <http://opensource.org/licenses/MIT>. SPDX-License-Identifier: MIT Copyright (c) 2013-2019 Niels Lohmann <http://nlohmann.me>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef INCLUDE_NLOHMANN_JSON_HPP_ #define INCLUDE_NLOHMANN_JSON_HPP_ #define NLOHMANN_JSON_VERSION_MAJOR 3 #define NLOHMANN_JSON_VERSION_MINOR 9 #define NLOHMANN_JSON_VERSION_PATCH 1 #include <algorithm> // all_of, find, for_each #include <cstddef> // nullptr_t, ptrdiff_t, size_t #include <functional> // hash, less #include <initializer_list> // initializer_list #ifndef JSON_NO_IO #include <iosfwd> // istream, ostream #endif // JSON_NO_IO #include <iterator> // random_access_iterator_tag #include <memory> // unique_ptr #include <numeric> // accumulate #include <string> // string, stoi, to_string #include <utility> // declval, forward, move, pair, swap #include <vector> // vector // #include <nlohmann/adl_serializer.hpp> #include <type_traits> #include <utility> // #include <nlohmann/detail/conversions/from_json.hpp> #include <algorithm> // transform #include <array> // array #include <forward_list> // forward_list #include <iterator> // inserter, front_inserter, end #include <map> // map #include <string> // string #include <tuple> // tuple, make_tuple #include <type_traits> // is_arithmetic, is_same, is_enum, underlying_type, is_convertible #include <unordered_map> // unordered_map #include <utility> // pair, declval #include <valarray> // valarray // #include <nlohmann/detail/exceptions.hpp> #include <exception> // exception #include <stdexcept> // runtime_error #include <string> // to_string #include <vector> // vector // #include <nlohmann/detail/value_t.hpp> #include <array> // array #include <cstddef> // size_t #include <cstdint> // uint8_t #include <string> // string namespace nlohmann { namespace detail { /////////////////////////// // JSON type enumeration // /////////////////////////// /*! @brief the JSON type enumeration This enumeration collects the different JSON types. It is internally used to distinguish the stored values, and the functions @ref basic_json::is_null(), @ref basic_json::is_object(), @ref basic_json::is_array(), @ref basic_json::is_string(), @ref basic_json::is_boolean(), @ref basic_json::is_number() (with @ref basic_json::is_number_integer(), @ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()), @ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and @ref basic_json::is_structured() rely on it. @note There are three enumeration entries (number_integer, number_unsigned, and number_float), because the library distinguishes these three types for numbers: @ref basic_json::number_unsigned_t is used for unsigned integers, @ref basic_json::number_integer_t is used for signed integers, and @ref basic_json::number_float_t is used for floating-point numbers o to approximate integers which do not fit in the limits of their respective type. @sa see @ref basic_json::basic_json(const value_t value_type) -- create a JSON value with the default value for a given type @since version 1.0.0 */ enum class value_t : std::uint8_t { null, ///< null value object, ///< object (unordered set of name/value pairs) array, ///< array (ordered collection of values) string, ///< string value boolean, ///< boolean value number_integer, ///< number value (signed integer) number_unsigned, ///< number value (unsigned integer) number_float, ///< number value (floating-point) binary, ///< binary array (ordered collection of bytes) discarded ///< discarded by the parser callback function }; /*! @brief comparison operator for JSON types Returns an ordering that is similar to Python: - order: null < boolean < number < object < array < string < binary - furthermore, each type is not smaller than itself - discarded values are not comparable - binary is represented as a b"" string in python and directly comparable to a string; however, making a binary array directly comparable with a string would be surprising behavior in a JSON file. @since version 1.0.0 */ inline bool operator<(const value_t lhs, const value_t rhs) noexcept { static constexpr std::array<std::uint8_t, 9> order = {{ 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */, 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */, 6 /* binary */ } }; const auto l_index = static_cast<std::size_t>(lhs); const auto r_index = static_cast<std::size_t>(rhs); return l_index < order.size() && r_index < order.size() && order[l_index] < order[r_index]; } } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/string_escape.hpp> #include <string> // #include <nlohmann/detail/macro_scope.hpp> #include <utility> // pair // #include <nlohmann/thirdparty/hedley/hedley.hpp> /* Hedley - https://nemequ.github.io/hedley * Created by Evan Nemerson <evan@nemerson.com> * * To the extent possible under law, the author(s) have dedicated all * copyright and related and neighboring rights to this software to * the public domain worldwide. This software is distributed without * any warranty. * * For details, see <http://creativecommons.org/publicdomain/zero/1.0/>. * SPDX-License-Identifier: CC0-1.0 */ #if !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < 15) #if defined(JSON_HEDLEY_VERSION) #undef JSON_HEDLEY_VERSION #endif #define JSON_HEDLEY_VERSION 15 #if defined(JSON_HEDLEY_STRINGIFY_EX) #undef JSON_HEDLEY_STRINGIFY_EX #endif #define JSON_HEDLEY_STRINGIFY_EX(x) #x #if defined(JSON_HEDLEY_STRINGIFY) #undef JSON_HEDLEY_STRINGIFY #endif #define JSON_HEDLEY_STRINGIFY(x) JSON_HEDLEY_STRINGIFY_EX(x) #if defined(JSON_HEDLEY_CONCAT_EX) #undef JSON_HEDLEY_CONCAT_EX #endif #define JSON_HEDLEY_CONCAT_EX(a,b) a##b #if defined(JSON_HEDLEY_CONCAT) #undef JSON_HEDLEY_CONCAT #endif #define JSON_HEDLEY_CONCAT(a,b) JSON_HEDLEY_CONCAT_EX(a,b) #if defined(JSON_HEDLEY_CONCAT3_EX) #undef JSON_HEDLEY_CONCAT3_EX #endif #define JSON_HEDLEY_CONCAT3_EX(a,b,c) a##b##c #if defined(JSON_HEDLEY_CONCAT3) #undef JSON_HEDLEY_CONCAT3 #endif #define JSON_HEDLEY_CONCAT3(a,b,c) JSON_HEDLEY_CONCAT3_EX(a,b,c) #if defined(JSON_HEDLEY_VERSION_ENCODE) #undef JSON_HEDLEY_VERSION_ENCODE #endif #define JSON_HEDLEY_VERSION_ENCODE(major,minor,revision) (((major) * 1000000) + ((minor) * 1000) + (revision)) #if defined(JSON_HEDLEY_VERSION_DECODE_MAJOR) #undef JSON_HEDLEY_VERSION_DECODE_MAJOR #endif #define JSON_HEDLEY_VERSION_DECODE_MAJOR(version) ((version) / 1000000) #if defined(JSON_HEDLEY_VERSION_DECODE_MINOR) #undef JSON_HEDLEY_VERSION_DECODE_MINOR #endif #define JSON_HEDLEY_VERSION_DECODE_MINOR(version) (((version) % 1000000) / 1000) #if defined(JSON_HEDLEY_VERSION_DECODE_REVISION) #undef JSON_HEDLEY_VERSION_DECODE_REVISION #endif #define JSON_HEDLEY_VERSION_DECODE_REVISION(version) ((version) % 1000) #if defined(JSON_HEDLEY_GNUC_VERSION) #undef JSON_HEDLEY_GNUC_VERSION #endif #if defined(__GNUC__) && defined(__GNUC_PATCHLEVEL__) #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) #elif defined(__GNUC__) #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, 0) #endif #if defined(JSON_HEDLEY_GNUC_VERSION_CHECK) #undef JSON_HEDLEY_GNUC_VERSION_CHECK #endif #if defined(JSON_HEDLEY_GNUC_VERSION) #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GNUC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_MSVC_VERSION) #undef JSON_HEDLEY_MSVC_VERSION #endif #if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 140000000) && !defined(__ICL) #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 10000000, (_MSC_FULL_VER % 10000000) / 100000, (_MSC_FULL_VER % 100000) / 100) #elif defined(_MSC_FULL_VER) && !defined(__ICL) #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 1000000, (_MSC_FULL_VER % 1000000) / 10000, (_MSC_FULL_VER % 10000) / 10) #elif defined(_MSC_VER) && !defined(__ICL) #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_VER / 100, _MSC_VER % 100, 0) #endif #if defined(JSON_HEDLEY_MSVC_VERSION_CHECK) #undef JSON_HEDLEY_MSVC_VERSION_CHECK #endif #if !defined(JSON_HEDLEY_MSVC_VERSION) #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (0) #elif defined(_MSC_VER) && (_MSC_VER >= 1400) #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 10000000) + (minor * 100000) + (patch))) #elif defined(_MSC_VER) && (_MSC_VER >= 1200) #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 1000000) + (minor * 10000) + (patch))) #else #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_VER >= ((major * 100) + (minor))) #endif #if defined(JSON_HEDLEY_INTEL_VERSION) #undef JSON_HEDLEY_INTEL_VERSION #endif #if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && !defined(__ICL) #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, __INTEL_COMPILER_UPDATE) #elif defined(__INTEL_COMPILER) && !defined(__ICL) #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0) #endif #if defined(JSON_HEDLEY_INTEL_VERSION_CHECK) #undef JSON_HEDLEY_INTEL_VERSION_CHECK #endif #if defined(JSON_HEDLEY_INTEL_VERSION) #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_INTEL_CL_VERSION) #undef JSON_HEDLEY_INTEL_CL_VERSION #endif #if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && defined(__ICL) #define JSON_HEDLEY_INTEL_CL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER, __INTEL_COMPILER_UPDATE, 0) #endif #if defined(JSON_HEDLEY_INTEL_CL_VERSION_CHECK) #undef JSON_HEDLEY_INTEL_CL_VERSION_CHECK #endif #if defined(JSON_HEDLEY_INTEL_CL_VERSION) #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_CL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_PGI_VERSION) #undef JSON_HEDLEY_PGI_VERSION #endif #if defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) && defined(__PGIC_PATCHLEVEL__) #define JSON_HEDLEY_PGI_VERSION JSON_HEDLEY_VERSION_ENCODE(__PGIC__, __PGIC_MINOR__, __PGIC_PATCHLEVEL__) #endif #if defined(JSON_HEDLEY_PGI_VERSION_CHECK) #undef JSON_HEDLEY_PGI_VERSION_CHECK #endif #if defined(JSON_HEDLEY_PGI_VERSION) #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PGI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_SUNPRO_VERSION) #undef JSON_HEDLEY_SUNPRO_VERSION #endif #if defined(__SUNPRO_C) && (__SUNPRO_C > 0x1000) #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_C >> 16) & 0xf) * 10) + ((__SUNPRO_C >> 12) & 0xf), (((__SUNPRO_C >> 8) & 0xf) * 10) + ((__SUNPRO_C >> 4) & 0xf), (__SUNPRO_C & 0xf) * 10) #elif defined(__SUNPRO_C) #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_C >> 8) & 0xf, (__SUNPRO_C >> 4) & 0xf, (__SUNPRO_C) & 0xf) #elif defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x1000) #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_CC >> 16) & 0xf) * 10) + ((__SUNPRO_CC >> 12) & 0xf), (((__SUNPRO_CC >> 8) & 0xf) * 10) + ((__SUNPRO_CC >> 4) & 0xf), (__SUNPRO_CC & 0xf) * 10) #elif defined(__SUNPRO_CC) #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_CC >> 8) & 0xf, (__SUNPRO_CC >> 4) & 0xf, (__SUNPRO_CC) & 0xf) #endif #if defined(JSON_HEDLEY_SUNPRO_VERSION_CHECK) #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK #endif #if defined(JSON_HEDLEY_SUNPRO_VERSION) #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_SUNPRO_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) #undef JSON_HEDLEY_EMSCRIPTEN_VERSION #endif #if defined(__EMSCRIPTEN__) #define JSON_HEDLEY_EMSCRIPTEN_VERSION JSON_HEDLEY_VERSION_ENCODE(__EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__) #endif #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK) #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK #endif #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_EMSCRIPTEN_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_ARM_VERSION) #undef JSON_HEDLEY_ARM_VERSION #endif #if defined(__CC_ARM) && defined(__ARMCOMPILER_VERSION) #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCOMPILER_VERSION / 1000000, (__ARMCOMPILER_VERSION % 1000000) / 10000, (__ARMCOMPILER_VERSION % 10000) / 100) #elif defined(__CC_ARM) && defined(__ARMCC_VERSION) #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCC_VERSION / 1000000, (__ARMCC_VERSION % 1000000) / 10000, (__ARMCC_VERSION % 10000) / 100) #endif #if defined(JSON_HEDLEY_ARM_VERSION_CHECK) #undef JSON_HEDLEY_ARM_VERSION_CHECK #endif #if defined(JSON_HEDLEY_ARM_VERSION) #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_ARM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_IBM_VERSION) #undef JSON_HEDLEY_IBM_VERSION #endif #if defined(__ibmxl__) #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ibmxl_version__, __ibmxl_release__, __ibmxl_modification__) #elif defined(__xlC__) && defined(__xlC_ver__) #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, (__xlC_ver__ >> 8) & 0xff) #elif defined(__xlC__) #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, 0) #endif #if defined(JSON_HEDLEY_IBM_VERSION_CHECK) #undef JSON_HEDLEY_IBM_VERSION_CHECK #endif #if defined(JSON_HEDLEY_IBM_VERSION) #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IBM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_TI_VERSION) #undef JSON_HEDLEY_TI_VERSION #endif #if \ defined(__TI_COMPILER_VERSION__) && \ ( \ defined(__TMS470__) || defined(__TI_ARM__) || \ defined(__MSP430__) || \ defined(__TMS320C2000__) \ ) #if (__TI_COMPILER_VERSION__ >= 16000000) #define JSON_HEDLEY_TI_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) #endif #endif #if defined(JSON_HEDLEY_TI_VERSION_CHECK) #undef JSON_HEDLEY_TI_VERSION_CHECK #endif #if defined(JSON_HEDLEY_TI_VERSION) #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_TI_CL2000_VERSION) #undef JSON_HEDLEY_TI_CL2000_VERSION #endif #if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C2000__) #define JSON_HEDLEY_TI_CL2000_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) #endif #if defined(JSON_HEDLEY_TI_CL2000_VERSION_CHECK) #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK #endif #if defined(JSON_HEDLEY_TI_CL2000_VERSION) #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL2000_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_TI_CL430_VERSION) #undef JSON_HEDLEY_TI_CL430_VERSION #endif #if defined(__TI_COMPILER_VERSION__) && defined(__MSP430__) #define JSON_HEDLEY_TI_CL430_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) #endif #if defined(JSON_HEDLEY_TI_CL430_VERSION_CHECK) #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK #endif #if defined(JSON_HEDLEY_TI_CL430_VERSION) #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL430_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_TI_ARMCL_VERSION) #undef JSON_HEDLEY_TI_ARMCL_VERSION #endif #if defined(__TI_COMPILER_VERSION__) && (defined(__TMS470__) || defined(__TI_ARM__)) #define JSON_HEDLEY_TI_ARMCL_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) #endif #if defined(JSON_HEDLEY_TI_ARMCL_VERSION_CHECK) #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK #endif #if defined(JSON_HEDLEY_TI_ARMCL_VERSION) #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_ARMCL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_TI_CL6X_VERSION) #undef JSON_HEDLEY_TI_CL6X_VERSION #endif #if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C6X__) #define JSON_HEDLEY_TI_CL6X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) #endif #if defined(JSON_HEDLEY_TI_CL6X_VERSION_CHECK) #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK #endif #if defined(JSON_HEDLEY_TI_CL6X_VERSION) #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL6X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_TI_CL7X_VERSION) #undef JSON_HEDLEY_TI_CL7X_VERSION #endif #if defined(__TI_COMPILER_VERSION__) && defined(__C7000__) #define JSON_HEDLEY_TI_CL7X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) #endif #if defined(JSON_HEDLEY_TI_CL7X_VERSION_CHECK) #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK #endif #if defined(JSON_HEDLEY_TI_CL7X_VERSION) #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL7X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_TI_CLPRU_VERSION) #undef JSON_HEDLEY_TI_CLPRU_VERSION #endif #if defined(__TI_COMPILER_VERSION__) && defined(__PRU__) #define JSON_HEDLEY_TI_CLPRU_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) #endif #if defined(JSON_HEDLEY_TI_CLPRU_VERSION_CHECK) #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK #endif #if defined(JSON_HEDLEY_TI_CLPRU_VERSION) #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CLPRU_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_CRAY_VERSION) #undef JSON_HEDLEY_CRAY_VERSION #endif #if defined(_CRAYC) #if defined(_RELEASE_PATCHLEVEL) #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, _RELEASE_PATCHLEVEL) #else #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, 0) #endif #endif #if defined(JSON_HEDLEY_CRAY_VERSION_CHECK) #undef JSON_HEDLEY_CRAY_VERSION_CHECK #endif #if defined(JSON_HEDLEY_CRAY_VERSION) #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_CRAY_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_IAR_VERSION) #undef JSON_HEDLEY_IAR_VERSION #endif #if defined(__IAR_SYSTEMS_ICC__) #if __VER__ > 1000 #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE((__VER__ / 1000000), ((__VER__ / 1000) % 1000), (__VER__ % 1000)) #else #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE(__VER__ / 100, __VER__ % 100, 0) #endif #endif #if defined(JSON_HEDLEY_IAR_VERSION_CHECK) #undef JSON_HEDLEY_IAR_VERSION_CHECK #endif #if defined(JSON_HEDLEY_IAR_VERSION) #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IAR_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_TINYC_VERSION) #undef JSON_HEDLEY_TINYC_VERSION #endif #if defined(__TINYC__) #define JSON_HEDLEY_TINYC_VERSION JSON_HEDLEY_VERSION_ENCODE(__TINYC__ / 1000, (__TINYC__ / 100) % 10, __TINYC__ % 100) #endif #if defined(JSON_HEDLEY_TINYC_VERSION_CHECK) #undef JSON_HEDLEY_TINYC_VERSION_CHECK #endif #if defined(JSON_HEDLEY_TINYC_VERSION) #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TINYC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_DMC_VERSION) #undef JSON_HEDLEY_DMC_VERSION #endif #if defined(__DMC__) #define JSON_HEDLEY_DMC_VERSION JSON_HEDLEY_VERSION_ENCODE(__DMC__ >> 8, (__DMC__ >> 4) & 0xf, __DMC__ & 0xf) #endif #if defined(JSON_HEDLEY_DMC_VERSION_CHECK) #undef JSON_HEDLEY_DMC_VERSION_CHECK #endif #if defined(JSON_HEDLEY_DMC_VERSION) #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_DMC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_COMPCERT_VERSION) #undef JSON_HEDLEY_COMPCERT_VERSION #endif #if defined(__COMPCERT_VERSION__) #define JSON_HEDLEY_COMPCERT_VERSION JSON_HEDLEY_VERSION_ENCODE(__COMPCERT_VERSION__ / 10000, (__COMPCERT_VERSION__ / 100) % 100, __COMPCERT_VERSION__ % 100) #endif #if defined(JSON_HEDLEY_COMPCERT_VERSION_CHECK) #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK #endif #if defined(JSON_HEDLEY_COMPCERT_VERSION) #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_COMPCERT_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_PELLES_VERSION) #undef JSON_HEDLEY_PELLES_VERSION #endif #if defined(__POCC__) #define JSON_HEDLEY_PELLES_VERSION JSON_HEDLEY_VERSION_ENCODE(__POCC__ / 100, __POCC__ % 100, 0) #endif #if defined(JSON_HEDLEY_PELLES_VERSION_CHECK) #undef JSON_HEDLEY_PELLES_VERSION_CHECK #endif #if defined(JSON_HEDLEY_PELLES_VERSION) #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PELLES_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_MCST_LCC_VERSION) #undef JSON_HEDLEY_MCST_LCC_VERSION #endif #if defined(__LCC__) && defined(__LCC_MINOR__) #define JSON_HEDLEY_MCST_LCC_VERSION JSON_HEDLEY_VERSION_ENCODE(__LCC__ / 100, __LCC__ % 100, __LCC_MINOR__) #endif #if defined(JSON_HEDLEY_MCST_LCC_VERSION_CHECK) #undef JSON_HEDLEY_MCST_LCC_VERSION_CHECK #endif #if defined(JSON_HEDLEY_MCST_LCC_VERSION) #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_MCST_LCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_GCC_VERSION) #undef JSON_HEDLEY_GCC_VERSION #endif #if \ defined(JSON_HEDLEY_GNUC_VERSION) && \ !defined(__clang__) && \ !defined(JSON_HEDLEY_INTEL_VERSION) && \ !defined(JSON_HEDLEY_PGI_VERSION) && \ !defined(JSON_HEDLEY_ARM_VERSION) && \ !defined(JSON_HEDLEY_CRAY_VERSION) && \ !defined(JSON_HEDLEY_TI_VERSION) && \ !defined(JSON_HEDLEY_TI_ARMCL_VERSION) && \ !defined(JSON_HEDLEY_TI_CL430_VERSION) && \ !defined(JSON_HEDLEY_TI_CL2000_VERSION) && \ !defined(JSON_HEDLEY_TI_CL6X_VERSION) && \ !defined(JSON_HEDLEY_TI_CL7X_VERSION) && \ !defined(JSON_HEDLEY_TI_CLPRU_VERSION) && \ !defined(__COMPCERT__) && \ !defined(JSON_HEDLEY_MCST_LCC_VERSION) #define JSON_HEDLEY_GCC_VERSION JSON_HEDLEY_GNUC_VERSION #endif #if defined(JSON_HEDLEY_GCC_VERSION_CHECK) #undef JSON_HEDLEY_GCC_VERSION_CHECK #endif #if defined(JSON_HEDLEY_GCC_VERSION) #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_HAS_ATTRIBUTE) #undef JSON_HEDLEY_HAS_ATTRIBUTE #endif #if \ defined(__has_attribute) && \ ( \ (!defined(JSON_HEDLEY_IAR_VERSION) || JSON_HEDLEY_IAR_VERSION_CHECK(8,5,9)) \ ) # define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) __has_attribute(attribute) #else # define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) (0) #endif #if defined(JSON_HEDLEY_GNUC_HAS_ATTRIBUTE) #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE #endif #if defined(__has_attribute) #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) #else #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_GCC_HAS_ATTRIBUTE) #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE #endif #if defined(__has_attribute) #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) #else #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE) #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE #endif #if \ defined(__has_cpp_attribute) && \ defined(__cplusplus) && \ (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) __has_cpp_attribute(attribute) #else #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) (0) #endif #if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS) #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS #endif #if !defined(__cplusplus) || !defined(__has_cpp_attribute) #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) #elif \ !defined(JSON_HEDLEY_PGI_VERSION) && \ !defined(JSON_HEDLEY_IAR_VERSION) && \ (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) && \ (!defined(JSON_HEDLEY_MSVC_VERSION) || JSON_HEDLEY_MSVC_VERSION_CHECK(19,20,0)) #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(ns::attribute) #else #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) #endif #if defined(JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE) #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE #endif #if defined(__has_cpp_attribute) && defined(__cplusplus) #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) #else #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE) #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE #endif #if defined(__has_cpp_attribute) && defined(__cplusplus) #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) #else #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_HAS_BUILTIN) #undef JSON_HEDLEY_HAS_BUILTIN #endif #if defined(__has_builtin) #define JSON_HEDLEY_HAS_BUILTIN(builtin) __has_builtin(builtin) #else #define JSON_HEDLEY_HAS_BUILTIN(builtin) (0) #endif #if defined(JSON_HEDLEY_GNUC_HAS_BUILTIN) #undef JSON_HEDLEY_GNUC_HAS_BUILTIN #endif #if defined(__has_builtin) #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) #else #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_GCC_HAS_BUILTIN) #undef JSON_HEDLEY_GCC_HAS_BUILTIN #endif #if defined(__has_builtin) #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) #else #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_HAS_FEATURE) #undef JSON_HEDLEY_HAS_FEATURE #endif #if defined(__has_feature) #define JSON_HEDLEY_HAS_FEATURE(feature) __has_feature(feature) #else #define JSON_HEDLEY_HAS_FEATURE(feature) (0) #endif #if defined(JSON_HEDLEY_GNUC_HAS_FEATURE) #undef JSON_HEDLEY_GNUC_HAS_FEATURE #endif #if defined(__has_feature) #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) #else #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_GCC_HAS_FEATURE) #undef JSON_HEDLEY_GCC_HAS_FEATURE #endif #if defined(__has_feature) #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) #else #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_HAS_EXTENSION) #undef JSON_HEDLEY_HAS_EXTENSION #endif #if defined(__has_extension) #define JSON_HEDLEY_HAS_EXTENSION(extension) __has_extension(extension) #else #define JSON_HEDLEY_HAS_EXTENSION(extension) (0) #endif #if defined(JSON_HEDLEY_GNUC_HAS_EXTENSION) #undef JSON_HEDLEY_GNUC_HAS_EXTENSION #endif #if defined(__has_extension) #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) #else #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_GCC_HAS_EXTENSION) #undef JSON_HEDLEY_GCC_HAS_EXTENSION #endif #if defined(__has_extension) #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) #else #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE) #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE #endif #if defined(__has_declspec_attribute) #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) __has_declspec_attribute(attribute) #else #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) (0) #endif #if defined(JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE) #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE #endif #if defined(__has_declspec_attribute) #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) #else #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE) #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE #endif #if defined(__has_declspec_attribute) #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) #else #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_HAS_WARNING) #undef JSON_HEDLEY_HAS_WARNING #endif #if defined(__has_warning) #define JSON_HEDLEY_HAS_WARNING(warning) __has_warning(warning) #else #define JSON_HEDLEY_HAS_WARNING(warning) (0) #endif #if defined(JSON_HEDLEY_GNUC_HAS_WARNING) #undef JSON_HEDLEY_GNUC_HAS_WARNING #endif #if defined(__has_warning) #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) #else #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_GCC_HAS_WARNING) #undef JSON_HEDLEY_GCC_HAS_WARNING #endif #if defined(__has_warning) #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) #else #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) #endif #if \ (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ defined(__clang__) || \ JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,0,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) || \ JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,17) || \ JSON_HEDLEY_SUNPRO_VERSION_CHECK(8,0,0) || \ (JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) && defined(__C99_PRAGMA_OPERATOR)) #define JSON_HEDLEY_PRAGMA(value) _Pragma(#value) #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) #define JSON_HEDLEY_PRAGMA(value) __pragma(value) #else #define JSON_HEDLEY_PRAGMA(value) #endif #if defined(JSON_HEDLEY_DIAGNOSTIC_PUSH) #undef JSON_HEDLEY_DIAGNOSTIC_PUSH #endif #if defined(JSON_HEDLEY_DIAGNOSTIC_POP) #undef JSON_HEDLEY_DIAGNOSTIC_POP #endif #if defined(__clang__) #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("clang diagnostic push") #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("clang diagnostic pop") #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push") #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop") #elif \ JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \ JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) #define JSON_HEDLEY_DIAGNOSTIC_PUSH __pragma(warning(push)) #define JSON_HEDLEY_DIAGNOSTIC_POP __pragma(warning(pop)) #elif JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("push") #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("pop") #elif \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,4,0) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("diag_push") #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("diag_pop") #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") #else #define JSON_HEDLEY_DIAGNOSTIC_PUSH #define JSON_HEDLEY_DIAGNOSTIC_POP #endif /* JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ is for HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ #endif #if defined(__cplusplus) # if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat") # if JSON_HEDLEY_HAS_WARNING("-Wc++17-extensions") # if JSON_HEDLEY_HAS_WARNING("-Wc++1z-extensions") # define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ JSON_HEDLEY_DIAGNOSTIC_PUSH \ _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \ _Pragma("clang diagnostic ignored \"-Wc++1z-extensions\"") \ xpr \ JSON_HEDLEY_DIAGNOSTIC_POP # else # define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ JSON_HEDLEY_DIAGNOSTIC_PUSH \ _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \ xpr \ JSON_HEDLEY_DIAGNOSTIC_POP # endif # else # define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ JSON_HEDLEY_DIAGNOSTIC_PUSH \ _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ xpr \ JSON_HEDLEY_DIAGNOSTIC_POP # endif # endif #endif #if !defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(x) x #endif #if defined(JSON_HEDLEY_CONST_CAST) #undef JSON_HEDLEY_CONST_CAST #endif #if defined(__cplusplus) # define JSON_HEDLEY_CONST_CAST(T, expr) (const_cast<T>(expr)) #elif \ JSON_HEDLEY_HAS_WARNING("-Wcast-qual") || \ JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) # define JSON_HEDLEY_CONST_CAST(T, expr) (__extension__ ({ \ JSON_HEDLEY_DIAGNOSTIC_PUSH \ JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL \ ((T) (expr)); \ JSON_HEDLEY_DIAGNOSTIC_POP \ })) #else # define JSON_HEDLEY_CONST_CAST(T, expr) ((T) (expr)) #endif #if defined(JSON_HEDLEY_REINTERPRET_CAST) #undef JSON_HEDLEY_REINTERPRET_CAST #endif #if defined(__cplusplus) #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (reinterpret_cast<T>(expr)) #else #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) ((T) (expr)) #endif #if defined(JSON_HEDLEY_STATIC_CAST) #undef JSON_HEDLEY_STATIC_CAST #endif #if defined(__cplusplus) #define JSON_HEDLEY_STATIC_CAST(T, expr) (static_cast<T>(expr)) #else #define JSON_HEDLEY_STATIC_CAST(T, expr) ((T) (expr)) #endif #if defined(JSON_HEDLEY_CPP_CAST) #undef JSON_HEDLEY_CPP_CAST #endif #if defined(__cplusplus) # if JSON_HEDLEY_HAS_WARNING("-Wold-style-cast") # define JSON_HEDLEY_CPP_CAST(T, expr) \ JSON_HEDLEY_DIAGNOSTIC_PUSH \ _Pragma("clang diagnostic ignored \"-Wold-style-cast\"") \ ((T) (expr)) \ JSON_HEDLEY_DIAGNOSTIC_POP # elif JSON_HEDLEY_IAR_VERSION_CHECK(8,3,0) # define JSON_HEDLEY_CPP_CAST(T, expr) \ JSON_HEDLEY_DIAGNOSTIC_PUSH \ _Pragma("diag_suppress=Pe137") \ JSON_HEDLEY_DIAGNOSTIC_POP # else # define JSON_HEDLEY_CPP_CAST(T, expr) ((T) (expr)) # endif #else # define JSON_HEDLEY_CPP_CAST(T, expr) (expr) #endif #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED) #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED #endif #if JSON_HEDLEY_HAS_WARNING("-Wdeprecated-declarations") #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warning(disable:1478 1786)") #elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:1478 1786)) #elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1216,1444,1445") #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444") #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:4996)) #elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444") #elif \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1291,1718") #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && !defined(__cplusplus) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,E_DEPRECATED_ATT,E_DEPRECATED_ATT_MESS)") #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && defined(__cplusplus) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,symdeprecated,symdeprecated2)") #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress=Pe1444,Pe1215") #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warn(disable:2241)") #else #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED #endif #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS) #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS #endif #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("clang diagnostic ignored \"-Wunknown-pragmas\"") #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("warning(disable:161)") #elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:161)) #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 1675") #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("GCC diagnostic ignored \"-Wunknown-pragmas\"") #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:4068)) #elif \ JSON_HEDLEY_TI_VERSION_CHECK(16,9,0) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") #elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress=Pe161") #elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 161") #else #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS #endif #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES) #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES #endif #if JSON_HEDLEY_HAS_WARNING("-Wunknown-attributes") #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("clang diagnostic ignored \"-Wunknown-attributes\"") #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") #elif JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("warning(disable:1292)") #elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:1292)) #elif JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:5030)) #elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097,1098") #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097") #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("error_messages(off,attrskipunsup)") #elif \ JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1173") #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress=Pe1097") #elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097") #else #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES #endif #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL) #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL #endif #if JSON_HEDLEY_HAS_WARNING("-Wcast-qual") #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("clang diagnostic ignored \"-Wcast-qual\"") #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("warning(disable:2203 2331)") #elif JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("GCC diagnostic ignored \"-Wcast-qual\"") #else #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL #endif #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION) #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION #endif #if JSON_HEDLEY_HAS_WARNING("-Wunused-function") #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("clang diagnostic ignored \"-Wunused-function\"") #elif JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("GCC diagnostic ignored \"-Wunused-function\"") #elif JSON_HEDLEY_MSVC_VERSION_CHECK(1,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION __pragma(warning(disable:4505)) #elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("diag_suppress 3142") #else #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION #endif #if defined(JSON_HEDLEY_DEPRECATED) #undef JSON_HEDLEY_DEPRECATED #endif #if defined(JSON_HEDLEY_DEPRECATED_FOR) #undef JSON_HEDLEY_DEPRECATED_FOR #endif #if \ JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated("Since " # since)) #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated("Since " #since "; use " #replacement)) #elif \ (JSON_HEDLEY_HAS_EXTENSION(attribute_deprecated_with_message) && !defined(JSON_HEDLEY_IAR_VERSION)) || \ JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) || \ JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(18,1,0) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__("Since " #since))) #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__("Since " #since "; use " #replacement))) #elif defined(__cplusplus) && (__cplusplus >= 201402L) #define JSON_HEDLEY_DEPRECATED(since) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since)]]) #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since "; use " #replacement)]]) #elif \ JSON_HEDLEY_HAS_ATTRIBUTE(deprecated) || \ JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__)) #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__)) #elif \ JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ JSON_HEDLEY_PELLES_VERSION_CHECK(6,50,0) || \ JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated) #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated) #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) #define JSON_HEDLEY_DEPRECATED(since) _Pragma("deprecated") #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) _Pragma("deprecated") #else #define JSON_HEDLEY_DEPRECATED(since) #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) #endif #if defined(JSON_HEDLEY_UNAVAILABLE) #undef JSON_HEDLEY_UNAVAILABLE #endif #if \ JSON_HEDLEY_HAS_ATTRIBUTE(warning) || \ JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_UNAVAILABLE(available_since) __attribute__((__warning__("Not available until " #available_since))) #else #define JSON_HEDLEY_UNAVAILABLE(available_since) #endif #if defined(JSON_HEDLEY_WARN_UNUSED_RESULT) #undef JSON_HEDLEY_WARN_UNUSED_RESULT #endif #if defined(JSON_HEDLEY_WARN_UNUSED_RESULT_MSG) #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG #endif #if \ JSON_HEDLEY_HAS_ATTRIBUTE(warn_unused_result) || \ JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__)) #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) __attribute__((__warn_unused_result__)) #elif (JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) >= 201907L) #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard(msg)]]) #elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) #elif defined(_Check_return_) /* SAL */ #define JSON_HEDLEY_WARN_UNUSED_RESULT _Check_return_ #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) _Check_return_ #else #define JSON_HEDLEY_WARN_UNUSED_RESULT #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) #endif #if defined(JSON_HEDLEY_SENTINEL) #undef JSON_HEDLEY_SENTINEL #endif #if \ JSON_HEDLEY_HAS_ATTRIBUTE(sentinel) || \ JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_SENTINEL(position) __attribute__((__sentinel__(position))) #else #define JSON_HEDLEY_SENTINEL(position) #endif #if defined(JSON_HEDLEY_NO_RETURN) #undef JSON_HEDLEY_NO_RETURN #endif #if JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) #define JSON_HEDLEY_NO_RETURN __noreturn #elif \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) #elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L #define JSON_HEDLEY_NO_RETURN _Noreturn #elif defined(__cplusplus) && (__cplusplus >= 201103L) #define JSON_HEDLEY_NO_RETURN JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[noreturn]]) #elif \ JSON_HEDLEY_HAS_ATTRIBUTE(noreturn) || \ JSON_HEDLEY_GCC_VERSION_CHECK(3,2,0) || \ JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) #define JSON_HEDLEY_NO_RETURN _Pragma("does_not_return") #elif \ JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) #elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) #define JSON_HEDLEY_NO_RETURN _Pragma("FUNC_NEVER_RETURNS;") #elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) #define JSON_HEDLEY_NO_RETURN __attribute((noreturn)) #elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) #else #define JSON_HEDLEY_NO_RETURN #endif #if defined(JSON_HEDLEY_NO_ESCAPE) #undef JSON_HEDLEY_NO_ESCAPE #endif #if JSON_HEDLEY_HAS_ATTRIBUTE(noescape) #define JSON_HEDLEY_NO_ESCAPE __attribute__((__noescape__)) #else #define JSON_HEDLEY_NO_ESCAPE #endif #if defined(JSON_HEDLEY_UNREACHABLE) #undef JSON_HEDLEY_UNREACHABLE #endif #if defined(JSON_HEDLEY_UNREACHABLE_RETURN) #undef JSON_HEDLEY_UNREACHABLE_RETURN #endif #if defined(JSON_HEDLEY_ASSUME) #undef JSON_HEDLEY_ASSUME #endif #if \ JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) #define JSON_HEDLEY_ASSUME(expr) __assume(expr) #elif JSON_HEDLEY_HAS_BUILTIN(__builtin_assume) #define JSON_HEDLEY_ASSUME(expr) __builtin_assume(expr) #elif \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) #if defined(__cplusplus) #define JSON_HEDLEY_ASSUME(expr) std::_nassert(expr) #else #define JSON_HEDLEY_ASSUME(expr) _nassert(expr) #endif #endif #if \ (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && (!defined(JSON_HEDLEY_ARM_VERSION))) || \ JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ JSON_HEDLEY_PGI_VERSION_CHECK(18,10,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(13,1,5) || \ JSON_HEDLEY_CRAY_VERSION_CHECK(10,0,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_UNREACHABLE() __builtin_unreachable() #elif defined(JSON_HEDLEY_ASSUME) #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) #endif #if !defined(JSON_HEDLEY_ASSUME) #if defined(JSON_HEDLEY_UNREACHABLE) #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, ((expr) ? 1 : (JSON_HEDLEY_UNREACHABLE(), 1))) #else #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, expr) #endif #endif #if defined(JSON_HEDLEY_UNREACHABLE) #if \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (JSON_HEDLEY_STATIC_CAST(void, JSON_HEDLEY_ASSUME(0)), (value)) #else #define JSON_HEDLEY_UNREACHABLE_RETURN(value) JSON_HEDLEY_UNREACHABLE() #endif #else #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (value) #endif #if !defined(JSON_HEDLEY_UNREACHABLE) #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) #endif JSON_HEDLEY_DIAGNOSTIC_PUSH #if JSON_HEDLEY_HAS_WARNING("-Wpedantic") #pragma clang diagnostic ignored "-Wpedantic" #endif #if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat-pedantic") && defined(__cplusplus) #pragma clang diagnostic ignored "-Wc++98-compat-pedantic" #endif #if JSON_HEDLEY_GCC_HAS_WARNING("-Wvariadic-macros",4,0,0) #if defined(__clang__) #pragma clang diagnostic ignored "-Wvariadic-macros" #elif defined(JSON_HEDLEY_GCC_VERSION) #pragma GCC diagnostic ignored "-Wvariadic-macros" #endif #endif #if defined(JSON_HEDLEY_NON_NULL) #undef JSON_HEDLEY_NON_NULL #endif #if \ JSON_HEDLEY_HAS_ATTRIBUTE(nonnull) || \ JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) #define JSON_HEDLEY_NON_NULL(...) __attribute__((__nonnull__(__VA_ARGS__))) #else #define JSON_HEDLEY_NON_NULL(...) #endif JSON_HEDLEY_DIAGNOSTIC_POP #if defined(JSON_HEDLEY_PRINTF_FORMAT) #undef JSON_HEDLEY_PRINTF_FORMAT #endif #if defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && !defined(__USE_MINGW_ANSI_STDIO) #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(ms_printf, string_idx, first_to_check))) #elif defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && defined(__USE_MINGW_ANSI_STDIO) #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(gnu_printf, string_idx, first_to_check))) #elif \ JSON_HEDLEY_HAS_ATTRIBUTE(format) || \ JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(__printf__, string_idx, first_to_check))) #elif JSON_HEDLEY_PELLES_VERSION_CHECK(6,0,0) #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __declspec(vaformat(printf,string_idx,first_to_check)) #else #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) #endif #if defined(JSON_HEDLEY_CONSTEXPR) #undef JSON_HEDLEY_CONSTEXPR #endif #if defined(__cplusplus) #if __cplusplus >= 201103L #define JSON_HEDLEY_CONSTEXPR JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(constexpr) #endif #endif #if !defined(JSON_HEDLEY_CONSTEXPR) #define JSON_HEDLEY_CONSTEXPR #endif #if defined(JSON_HEDLEY_PREDICT) #undef JSON_HEDLEY_PREDICT #endif #if defined(JSON_HEDLEY_LIKELY) #undef JSON_HEDLEY_LIKELY #endif #if defined(JSON_HEDLEY_UNLIKELY) #undef JSON_HEDLEY_UNLIKELY #endif #if defined(JSON_HEDLEY_UNPREDICTABLE) #undef JSON_HEDLEY_UNPREDICTABLE #endif #if JSON_HEDLEY_HAS_BUILTIN(__builtin_unpredictable) #define JSON_HEDLEY_UNPREDICTABLE(expr) __builtin_unpredictable((expr)) #endif #if \ (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect_with_probability) && !defined(JSON_HEDLEY_PGI_VERSION)) || \ JSON_HEDLEY_GCC_VERSION_CHECK(9,0,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) # define JSON_HEDLEY_PREDICT(expr, value, probability) __builtin_expect_with_probability( (expr), (value), (probability)) # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) __builtin_expect_with_probability(!!(expr), 1 , (probability)) # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) __builtin_expect_with_probability(!!(expr), 0 , (probability)) # define JSON_HEDLEY_LIKELY(expr) __builtin_expect (!!(expr), 1 ) # define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect (!!(expr), 0 ) #elif \ (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \ JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,27) || \ JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) # define JSON_HEDLEY_PREDICT(expr, expected, probability) \ (((probability) >= 0.9) ? __builtin_expect((expr), (expected)) : (JSON_HEDLEY_STATIC_CAST(void, expected), (expr))) # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) \ (__extension__ ({ \ double hedley_probability_ = (probability); \ ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 1) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 0) : !!(expr))); \ })) # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) \ (__extension__ ({ \ double hedley_probability_ = (probability); \ ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 0) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 1) : !!(expr))); \ })) # define JSON_HEDLEY_LIKELY(expr) __builtin_expect(!!(expr), 1) # define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0) #else # define JSON_HEDLEY_PREDICT(expr, expected, probability) (JSON_HEDLEY_STATIC_CAST(void, expected), (expr)) # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) (!!(expr)) # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) (!!(expr)) # define JSON_HEDLEY_LIKELY(expr) (!!(expr)) # define JSON_HEDLEY_UNLIKELY(expr) (!!(expr)) #endif #if !defined(JSON_HEDLEY_UNPREDICTABLE) #define JSON_HEDLEY_UNPREDICTABLE(expr) JSON_HEDLEY_PREDICT(expr, 1, 0.5) #endif #if defined(JSON_HEDLEY_MALLOC) #undef JSON_HEDLEY_MALLOC #endif #if \ JSON_HEDLEY_HAS_ATTRIBUTE(malloc) || \ JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_MALLOC __attribute__((__malloc__)) #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) #define JSON_HEDLEY_MALLOC _Pragma("returns_new_memory") #elif \ JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) #define JSON_HEDLEY_MALLOC __declspec(restrict) #else #define JSON_HEDLEY_MALLOC #endif #if defined(JSON_HEDLEY_PURE) #undef JSON_HEDLEY_PURE #endif #if \ JSON_HEDLEY_HAS_ATTRIBUTE(pure) || \ JSON_HEDLEY_GCC_VERSION_CHECK(2,96,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) # define JSON_HEDLEY_PURE __attribute__((__pure__)) #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) # define JSON_HEDLEY_PURE _Pragma("does_not_write_global_data") #elif defined(__cplusplus) && \ ( \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) \ ) # define JSON_HEDLEY_PURE _Pragma("FUNC_IS_PURE;") #else # define JSON_HEDLEY_PURE #endif #if defined(JSON_HEDLEY_CONST) #undef JSON_HEDLEY_CONST #endif #if \ JSON_HEDLEY_HAS_ATTRIBUTE(const) || \ JSON_HEDLEY_GCC_VERSION_CHECK(2,5,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_CONST __attribute__((__const__)) #elif \ JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) #define JSON_HEDLEY_CONST _Pragma("no_side_effect") #else #define JSON_HEDLEY_CONST JSON_HEDLEY_PURE #endif #if defined(JSON_HEDLEY_RESTRICT) #undef JSON_HEDLEY_RESTRICT #endif #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && !defined(__cplusplus) #define JSON_HEDLEY_RESTRICT restrict #elif \ JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,4) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)) || \ JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ defined(__clang__) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_RESTRICT __restrict #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,3,0) && !defined(__cplusplus) #define JSON_HEDLEY_RESTRICT _Restrict #else #define JSON_HEDLEY_RESTRICT #endif #if defined(JSON_HEDLEY_INLINE) #undef JSON_HEDLEY_INLINE #endif #if \ (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ (defined(__cplusplus) && (__cplusplus >= 199711L)) #define JSON_HEDLEY_INLINE inline #elif \ defined(JSON_HEDLEY_GCC_VERSION) || \ JSON_HEDLEY_ARM_VERSION_CHECK(6,2,0) #define JSON_HEDLEY_INLINE __inline__ #elif \ JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \ JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,1,0) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_INLINE __inline #else #define JSON_HEDLEY_INLINE #endif #if defined(JSON_HEDLEY_ALWAYS_INLINE) #undef JSON_HEDLEY_ALWAYS_INLINE #endif #if \ JSON_HEDLEY_HAS_ATTRIBUTE(always_inline) || \ JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) # define JSON_HEDLEY_ALWAYS_INLINE __attribute__((__always_inline__)) JSON_HEDLEY_INLINE #elif \ JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \ JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) # define JSON_HEDLEY_ALWAYS_INLINE __forceinline #elif defined(__cplusplus) && \ ( \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) \ ) # define JSON_HEDLEY_ALWAYS_INLINE _Pragma("FUNC_ALWAYS_INLINE;") #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) # define JSON_HEDLEY_ALWAYS_INLINE _Pragma("inline=forced") #else # define JSON_HEDLEY_ALWAYS_INLINE JSON_HEDLEY_INLINE #endif #if defined(JSON_HEDLEY_NEVER_INLINE) #undef JSON_HEDLEY_NEVER_INLINE #endif #if \ JSON_HEDLEY_HAS_ATTRIBUTE(noinline) || \ JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) #define JSON_HEDLEY_NEVER_INLINE __attribute__((__noinline__)) #elif \ JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) #elif JSON_HEDLEY_PGI_VERSION_CHECK(10,2,0) #define JSON_HEDLEY_NEVER_INLINE _Pragma("noinline") #elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) #define JSON_HEDLEY_NEVER_INLINE _Pragma("FUNC_CANNOT_INLINE;") #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) #define JSON_HEDLEY_NEVER_INLINE _Pragma("inline=never") #elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) #define JSON_HEDLEY_NEVER_INLINE __attribute((noinline)) #elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) #else #define JSON_HEDLEY_NEVER_INLINE #endif #if defined(JSON_HEDLEY_PRIVATE) #undef JSON_HEDLEY_PRIVATE #endif #if defined(JSON_HEDLEY_PUBLIC) #undef JSON_HEDLEY_PUBLIC #endif #if defined(JSON_HEDLEY_IMPORT) #undef JSON_HEDLEY_IMPORT #endif #if defined(_WIN32) || defined(__CYGWIN__) # define JSON_HEDLEY_PRIVATE # define JSON_HEDLEY_PUBLIC __declspec(dllexport) # define JSON_HEDLEY_IMPORT __declspec(dllimport) #else # if \ JSON_HEDLEY_HAS_ATTRIBUTE(visibility) || \ JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ ( \ defined(__TI_EABI__) && \ ( \ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) \ ) \ ) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) # define JSON_HEDLEY_PRIVATE __attribute__((__visibility__("hidden"))) # define JSON_HEDLEY_PUBLIC __attribute__((__visibility__("default"))) # else # define JSON_HEDLEY_PRIVATE # define JSON_HEDLEY_PUBLIC # endif # define JSON_HEDLEY_IMPORT extern #endif #if defined(JSON_HEDLEY_NO_THROW) #undef JSON_HEDLEY_NO_THROW #endif #if \ JSON_HEDLEY_HAS_ATTRIBUTE(nothrow) || \ JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_NO_THROW __attribute__((__nothrow__)) #elif \ JSON_HEDLEY_MSVC_VERSION_CHECK(13,1,0) || \ JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) #define JSON_HEDLEY_NO_THROW __declspec(nothrow) #else #define JSON_HEDLEY_NO_THROW #endif #if defined(JSON_HEDLEY_FALL_THROUGH) #undef JSON_HEDLEY_FALL_THROUGH #endif #if \ JSON_HEDLEY_HAS_ATTRIBUTE(fallthrough) || \ JSON_HEDLEY_GCC_VERSION_CHECK(7,0,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_FALL_THROUGH __attribute__((__fallthrough__)) #elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(clang,fallthrough) #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[clang::fallthrough]]) #elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(fallthrough) #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[fallthrough]]) #elif defined(__fallthrough) /* SAL */ #define JSON_HEDLEY_FALL_THROUGH __fallthrough #else #define JSON_HEDLEY_FALL_THROUGH #endif #if defined(JSON_HEDLEY_RETURNS_NON_NULL) #undef JSON_HEDLEY_RETURNS_NON_NULL #endif #if \ JSON_HEDLEY_HAS_ATTRIBUTE(returns_nonnull) || \ JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_RETURNS_NON_NULL __attribute__((__returns_nonnull__)) #elif defined(_Ret_notnull_) /* SAL */ #define JSON_HEDLEY_RETURNS_NON_NULL _Ret_notnull_ #else #define JSON_HEDLEY_RETURNS_NON_NULL #endif #if defined(JSON_HEDLEY_ARRAY_PARAM) #undef JSON_HEDLEY_ARRAY_PARAM #endif #if \ defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ !defined(__STDC_NO_VLA__) && \ !defined(__cplusplus) && \ !defined(JSON_HEDLEY_PGI_VERSION) && \ !defined(JSON_HEDLEY_TINYC_VERSION) #define JSON_HEDLEY_ARRAY_PARAM(name) (name) #else #define JSON_HEDLEY_ARRAY_PARAM(name) #endif #if defined(JSON_HEDLEY_IS_CONSTANT) #undef JSON_HEDLEY_IS_CONSTANT #endif #if defined(JSON_HEDLEY_REQUIRE_CONSTEXPR) #undef JSON_HEDLEY_REQUIRE_CONSTEXPR #endif /* JSON_HEDLEY_IS_CONSTEXPR_ is for HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ #if defined(JSON_HEDLEY_IS_CONSTEXPR_) #undef JSON_HEDLEY_IS_CONSTEXPR_ #endif #if \ JSON_HEDLEY_HAS_BUILTIN(__builtin_constant_p) || \ JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,19) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) && !defined(__cplusplus)) || \ JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_IS_CONSTANT(expr) __builtin_constant_p(expr) #endif #if !defined(__cplusplus) # if \ JSON_HEDLEY_HAS_BUILTIN(__builtin_types_compatible_p) || \ JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \ JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,24) #if defined(__INTPTR_TYPE__) #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0)), int*) #else #include <stdint.h> #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((intptr_t) ((expr) * 0)) : (int*) 0)), int*) #endif # elif \ ( \ defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && \ !defined(JSON_HEDLEY_SUNPRO_VERSION) && \ !defined(JSON_HEDLEY_PGI_VERSION) && \ !defined(JSON_HEDLEY_IAR_VERSION)) || \ (JSON_HEDLEY_HAS_EXTENSION(c_generic_selections) && !defined(JSON_HEDLEY_IAR_VERSION)) || \ JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(5,3,0) #if defined(__INTPTR_TYPE__) #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0), int*: 1, void*: 0) #else #include <stdint.h> #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((intptr_t) * 0) : (int*) 0), int*: 1, void*: 0) #endif # elif \ defined(JSON_HEDLEY_GCC_VERSION) || \ defined(JSON_HEDLEY_INTEL_VERSION) || \ defined(JSON_HEDLEY_TINYC_VERSION) || \ defined(JSON_HEDLEY_TI_ARMCL_VERSION) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(18,12,0) || \ defined(JSON_HEDLEY_TI_CL2000_VERSION) || \ defined(JSON_HEDLEY_TI_CL6X_VERSION) || \ defined(JSON_HEDLEY_TI_CL7X_VERSION) || \ defined(JSON_HEDLEY_TI_CLPRU_VERSION) || \ defined(__clang__) # define JSON_HEDLEY_IS_CONSTEXPR_(expr) ( \ sizeof(void) != \ sizeof(*( \ 1 ? \ ((void*) ((expr) * 0L) ) : \ ((struct { char v[sizeof(void) * 2]; } *) 1) \ ) \ ) \ ) # endif #endif #if defined(JSON_HEDLEY_IS_CONSTEXPR_) #if !defined(JSON_HEDLEY_IS_CONSTANT) #define JSON_HEDLEY_IS_CONSTANT(expr) JSON_HEDLEY_IS_CONSTEXPR_(expr) #endif #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (JSON_HEDLEY_IS_CONSTEXPR_(expr) ? (expr) : (-1)) #else #if !defined(JSON_HEDLEY_IS_CONSTANT) #define JSON_HEDLEY_IS_CONSTANT(expr) (0) #endif #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (expr) #endif #if defined(JSON_HEDLEY_BEGIN_C_DECLS) #undef JSON_HEDLEY_BEGIN_C_DECLS #endif #if defined(JSON_HEDLEY_END_C_DECLS) #undef JSON_HEDLEY_END_C_DECLS #endif #if defined(JSON_HEDLEY_C_DECL) #undef JSON_HEDLEY_C_DECL #endif #if defined(__cplusplus) #define JSON_HEDLEY_BEGIN_C_DECLS extern "C" { #define JSON_HEDLEY_END_C_DECLS } #define JSON_HEDLEY_C_DECL extern "C" #else #define JSON_HEDLEY_BEGIN_C_DECLS #define JSON_HEDLEY_END_C_DECLS #define JSON_HEDLEY_C_DECL #endif #if defined(JSON_HEDLEY_STATIC_ASSERT) #undef JSON_HEDLEY_STATIC_ASSERT #endif #if \ !defined(__cplusplus) && ( \ (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) || \ (JSON_HEDLEY_HAS_FEATURE(c_static_assert) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \ JSON_HEDLEY_GCC_VERSION_CHECK(6,0,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ defined(_Static_assert) \ ) # define JSON_HEDLEY_STATIC_ASSERT(expr, message) _Static_assert(expr, message) #elif \ (defined(__cplusplus) && (__cplusplus >= 201103L)) || \ JSON_HEDLEY_MSVC_VERSION_CHECK(16,0,0) || \ JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) # define JSON_HEDLEY_STATIC_ASSERT(expr, message) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(static_assert(expr, message)) #else # define JSON_HEDLEY_STATIC_ASSERT(expr, message) #endif #if defined(JSON_HEDLEY_NULL) #undef JSON_HEDLEY_NULL #endif #if defined(__cplusplus) #if __cplusplus >= 201103L #define JSON_HEDLEY_NULL JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(nullptr) #elif defined(NULL) #define JSON_HEDLEY_NULL NULL #else #define JSON_HEDLEY_NULL JSON_HEDLEY_STATIC_CAST(void*, 0) #endif #elif defined(NULL) #define JSON_HEDLEY_NULL NULL #else #define JSON_HEDLEY_NULL ((void*) 0) #endif #if defined(JSON_HEDLEY_MESSAGE) #undef JSON_HEDLEY_MESSAGE #endif #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") # define JSON_HEDLEY_MESSAGE(msg) \ JSON_HEDLEY_DIAGNOSTIC_PUSH \ JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ JSON_HEDLEY_PRAGMA(message msg) \ JSON_HEDLEY_DIAGNOSTIC_POP #elif \ JSON_HEDLEY_GCC_VERSION_CHECK(4,4,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message msg) #elif JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(_CRI message msg) #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,0,0) # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) #else # define JSON_HEDLEY_MESSAGE(msg) #endif #if defined(JSON_HEDLEY_WARNING) #undef JSON_HEDLEY_WARNING #endif #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") # define JSON_HEDLEY_WARNING(msg) \ JSON_HEDLEY_DIAGNOSTIC_PUSH \ JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ JSON_HEDLEY_PRAGMA(clang warning msg) \ JSON_HEDLEY_DIAGNOSTIC_POP #elif \ JSON_HEDLEY_GCC_VERSION_CHECK(4,8,0) || \ JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(GCC warning msg) #elif \ JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \ JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(message(msg)) #else # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_MESSAGE(msg) #endif #if defined(JSON_HEDLEY_REQUIRE) #undef JSON_HEDLEY_REQUIRE #endif #if defined(JSON_HEDLEY_REQUIRE_MSG) #undef JSON_HEDLEY_REQUIRE_MSG #endif #if JSON_HEDLEY_HAS_ATTRIBUTE(diagnose_if) # if JSON_HEDLEY_HAS_WARNING("-Wgcc-compat") # define JSON_HEDLEY_REQUIRE(expr) \ JSON_HEDLEY_DIAGNOSTIC_PUSH \ _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ __attribute__((diagnose_if(!(expr), #expr, "error"))) \ JSON_HEDLEY_DIAGNOSTIC_POP # define JSON_HEDLEY_REQUIRE_MSG(expr,msg) \ JSON_HEDLEY_DIAGNOSTIC_PUSH \ _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ __attribute__((diagnose_if(!(expr), msg, "error"))) \ JSON_HEDLEY_DIAGNOSTIC_POP # else # define JSON_HEDLEY_REQUIRE(expr) __attribute__((diagnose_if(!(expr), #expr, "error"))) # define JSON_HEDLEY_REQUIRE_MSG(expr,msg) __attribute__((diagnose_if(!(expr), msg, "error"))) # endif #else # define JSON_HEDLEY_REQUIRE(expr) # define JSON_HEDLEY_REQUIRE_MSG(expr,msg) #endif #if defined(JSON_HEDLEY_FLAGS) #undef JSON_HEDLEY_FLAGS #endif #if JSON_HEDLEY_HAS_ATTRIBUTE(flag_enum) && (!defined(__cplusplus) || JSON_HEDLEY_HAS_WARNING("-Wbitfield-enum-conversion")) #define JSON_HEDLEY_FLAGS __attribute__((__flag_enum__)) #else #define JSON_HEDLEY_FLAGS #endif #if defined(JSON_HEDLEY_FLAGS_CAST) #undef JSON_HEDLEY_FLAGS_CAST #endif #if JSON_HEDLEY_INTEL_VERSION_CHECK(19,0,0) # define JSON_HEDLEY_FLAGS_CAST(T, expr) (__extension__ ({ \ JSON_HEDLEY_DIAGNOSTIC_PUSH \ _Pragma("warning(disable:188)") \ ((T) (expr)); \ JSON_HEDLEY_DIAGNOSTIC_POP \ })) #else # define JSON_HEDLEY_FLAGS_CAST(T, expr) JSON_HEDLEY_STATIC_CAST(T, expr) #endif #if defined(JSON_HEDLEY_EMPTY_BASES) #undef JSON_HEDLEY_EMPTY_BASES #endif #if \ (JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,23918) && !JSON_HEDLEY_MSVC_VERSION_CHECK(20,0,0)) || \ JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) #define JSON_HEDLEY_EMPTY_BASES __declspec(empty_bases) #else #define JSON_HEDLEY_EMPTY_BASES #endif /* Remaining macros are deprecated. */ #if defined(JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK) #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK #endif #if defined(__clang__) #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) (0) #else #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_CLANG_HAS_ATTRIBUTE) #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE #endif #define JSON_HEDLEY_CLANG_HAS_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) #if defined(JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE) #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE #endif #define JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) #if defined(JSON_HEDLEY_CLANG_HAS_BUILTIN) #undef JSON_HEDLEY_CLANG_HAS_BUILTIN #endif #define JSON_HEDLEY_CLANG_HAS_BUILTIN(builtin) JSON_HEDLEY_HAS_BUILTIN(builtin) #if defined(JSON_HEDLEY_CLANG_HAS_FEATURE) #undef JSON_HEDLEY_CLANG_HAS_FEATURE #endif #define JSON_HEDLEY_CLANG_HAS_FEATURE(feature) JSON_HEDLEY_HAS_FEATURE(feature) #if defined(JSON_HEDLEY_CLANG_HAS_EXTENSION) #undef JSON_HEDLEY_CLANG_HAS_EXTENSION #endif #define JSON_HEDLEY_CLANG_HAS_EXTENSION(extension) JSON_HEDLEY_HAS_EXTENSION(extension) #if defined(JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE) #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE #endif #define JSON_HEDLEY_CLANG_HAS_DECLSPEC_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) #if defined(JSON_HEDLEY_CLANG_HAS_WARNING) #undef JSON_HEDLEY_CLANG_HAS_WARNING #endif #define JSON_HEDLEY_CLANG_HAS_WARNING(warning) JSON_HEDLEY_HAS_WARNING(warning) #endif /* !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < X) */ // This file contains all internal macro definitions // You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them // exclude unsupported compilers #if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK) #if defined(__clang__) #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400 #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers" #endif #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER)) #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800 #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" #endif #endif #endif // C++ language standard detection // if the user manually specified the used c++ version this is skipped #if !defined(JSON_HAS_CPP_20) && !defined(JSON_HAS_CPP_17) && !defined(JSON_HAS_CPP_14) && !defined(JSON_HAS_CPP_11) #if (defined(__cplusplus) && __cplusplus >= 202002L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 202002L) #define JSON_HAS_CPP_20 #define JSON_HAS_CPP_17 #define JSON_HAS_CPP_14 #elif (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464 #define JSON_HAS_CPP_17 #define JSON_HAS_CPP_14 #elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1) #define JSON_HAS_CPP_14 #endif // the cpp 11 flag is always specified because it is the minimal required version #define JSON_HAS_CPP_11 #endif // disable documentation warnings on clang #if defined(__clang__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdocumentation" #endif // allow to disable exceptions #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION) #define JSON_THROW(exception) throw exception #define JSON_TRY try #define JSON_CATCH(exception) catch(exception) #define JSON_INTERNAL_CATCH(exception) catch(exception) #else #include <cstdlib> #define JSON_THROW(exception) std::abort() #define JSON_TRY if(true) #define JSON_CATCH(exception) if(false) #define JSON_INTERNAL_CATCH(exception) if(false) #endif // override exception macros #if defined(JSON_THROW_USER) #undef JSON_THROW #define JSON_THROW JSON_THROW_USER #endif #if defined(JSON_TRY_USER) #undef JSON_TRY #define JSON_TRY JSON_TRY_USER #endif #if defined(JSON_CATCH_USER) #undef JSON_CATCH #define JSON_CATCH JSON_CATCH_USER #undef JSON_INTERNAL_CATCH #define JSON_INTERNAL_CATCH JSON_CATCH_USER #endif #if defined(JSON_INTERNAL_CATCH_USER) #undef JSON_INTERNAL_CATCH #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER #endif // allow to override assert #if !defined(JSON_ASSERT) #include <cassert> // assert #define JSON_ASSERT(x) assert(x) #endif // allow to access some private functions (needed by the test suite) #if defined(JSON_TESTS_PRIVATE) #define JSON_PRIVATE_UNLESS_TESTED public #else #define JSON_PRIVATE_UNLESS_TESTED private #endif /*! @brief macro to briefly define a mapping between an enum and JSON @def NLOHMANN_JSON_SERIALIZE_ENUM @since version 3.4.0 */ #define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \ template<typename BasicJsonType> \ inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \ { \ static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \ static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \ auto it = std::find_if(std::begin(m), std::end(m), \ [e](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \ { \ return ej_pair.first == e; \ }); \ j = ((it != std::end(m)) ? it : std::begin(m))->second; \ } \ template<typename BasicJsonType> \ inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \ { \ static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \ static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \ auto it = std::find_if(std::begin(m), std::end(m), \ [&j](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \ { \ return ej_pair.second == j; \ }); \ e = ((it != std::end(m)) ? it : std::begin(m))->first; \ } // Ugly macros to avoid uglier copy-paste when specializing basic_json. They // may be removed in the future once the class is split. #define NLOHMANN_BASIC_JSON_TPL_DECLARATION \ template<template<typename, typename, typename...> class ObjectType, \ template<typename, typename...> class ArrayType, \ class StringType, class BooleanType, class NumberIntegerType, \ class NumberUnsignedType, class NumberFloatType, \ template<typename> class AllocatorType, \ template<typename, typename = void> class JSONSerializer, \ class BinaryType> #define NLOHMANN_BASIC_JSON_TPL \ basic_json<ObjectType, ArrayType, StringType, BooleanType, \ NumberIntegerType, NumberUnsignedType, NumberFloatType, \ AllocatorType, JSONSerializer, BinaryType> // Macros to simplify conversion from/to types #define NLOHMANN_JSON_EXPAND( x ) x #define NLOHMANN_JSON_GET_MACRO(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63, _64, NAME,...) NAME #define NLOHMANN_JSON_PASTE(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_GET_MACRO(__VA_ARGS__, \ NLOHMANN_JSON_PASTE64, \ NLOHMANN_JSON_PASTE63, \ NLOHMANN_JSON_PASTE62, \ NLOHMANN_JSON_PASTE61, \ NLOHMANN_JSON_PASTE60, \ NLOHMANN_JSON_PASTE59, \ NLOHMANN_JSON_PASTE58, \ NLOHMANN_JSON_PASTE57, \ NLOHMANN_JSON_PASTE56, \ NLOHMANN_JSON_PASTE55, \ NLOHMANN_JSON_PASTE54, \ NLOHMANN_JSON_PASTE53, \ NLOHMANN_JSON_PASTE52, \ NLOHMANN_JSON_PASTE51, \ NLOHMANN_JSON_PASTE50, \ NLOHMANN_JSON_PASTE49, \ NLOHMANN_JSON_PASTE48, \ NLOHMANN_JSON_PASTE47, \ NLOHMANN_JSON_PASTE46, \ NLOHMANN_JSON_PASTE45, \ NLOHMANN_JSON_PASTE44, \ NLOHMANN_JSON_PASTE43, \ NLOHMANN_JSON_PASTE42, \ NLOHMANN_JSON_PASTE41, \ NLOHMANN_JSON_PASTE40, \ NLOHMANN_JSON_PASTE39, \ NLOHMANN_JSON_PASTE38, \ NLOHMANN_JSON_PASTE37, \ NLOHMANN_JSON_PASTE36, \ NLOHMANN_JSON_PASTE35, \ NLOHMANN_JSON_PASTE34, \ NLOHMANN_JSON_PASTE33, \ NLOHMANN_JSON_PASTE32, \ NLOHMANN_JSON_PASTE31, \ NLOHMANN_JSON_PASTE30, \ NLOHMANN_JSON_PASTE29, \ NLOHMANN_JSON_PASTE28, \ NLOHMANN_JSON_PASTE27, \ NLOHMANN_JSON_PASTE26, \ NLOHMANN_JSON_PASTE25, \ NLOHMANN_JSON_PASTE24, \ NLOHMANN_JSON_PASTE23, \ NLOHMANN_JSON_PASTE22, \ NLOHMANN_JSON_PASTE21, \ NLOHMANN_JSON_PASTE20, \ NLOHMANN_JSON_PASTE19, \ NLOHMANN_JSON_PASTE18, \ NLOHMANN_JSON_PASTE17, \ NLOHMANN_JSON_PASTE16, \ NLOHMANN_JSON_PASTE15, \ NLOHMANN_JSON_PASTE14, \ NLOHMANN_JSON_PASTE13, \ NLOHMANN_JSON_PASTE12, \ NLOHMANN_JSON_PASTE11, \ NLOHMANN_JSON_PASTE10, \ NLOHMANN_JSON_PASTE9, \ NLOHMANN_JSON_PASTE8, \ NLOHMANN_JSON_PASTE7, \ NLOHMANN_JSON_PASTE6, \ NLOHMANN_JSON_PASTE5, \ NLOHMANN_JSON_PASTE4, \ NLOHMANN_JSON_PASTE3, \ NLOHMANN_JSON_PASTE2, \ NLOHMANN_JSON_PASTE1)(__VA_ARGS__)) #define NLOHMANN_JSON_PASTE2(func, v1) func(v1) #define NLOHMANN_JSON_PASTE3(func, v1, v2) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE2(func, v2) #define NLOHMANN_JSON_PASTE4(func, v1, v2, v3) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE3(func, v2, v3) #define NLOHMANN_JSON_PASTE5(func, v1, v2, v3, v4) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE4(func, v2, v3, v4) #define NLOHMANN_JSON_PASTE6(func, v1, v2, v3, v4, v5) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE5(func, v2, v3, v4, v5) #define NLOHMANN_JSON_PASTE7(func, v1, v2, v3, v4, v5, v6) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE6(func, v2, v3, v4, v5, v6) #define NLOHMANN_JSON_PASTE8(func, v1, v2, v3, v4, v5, v6, v7) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE7(func, v2, v3, v4, v5, v6, v7) #define NLOHMANN_JSON_PASTE9(func, v1, v2, v3, v4, v5, v6, v7, v8) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE8(func, v2, v3, v4, v5, v6, v7, v8) #define NLOHMANN_JSON_PASTE10(func, v1, v2, v3, v4, v5, v6, v7, v8, v9) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE9(func, v2, v3, v4, v5, v6, v7, v8, v9) #define NLOHMANN_JSON_PASTE11(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE10(func, v2, v3, v4, v5, v6, v7, v8, v9, v10) #define NLOHMANN_JSON_PASTE12(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE11(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) #define NLOHMANN_JSON_PASTE13(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE12(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) #define NLOHMANN_JSON_PASTE14(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE13(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) #define NLOHMANN_JSON_PASTE15(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE14(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) #define NLOHMANN_JSON_PASTE16(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE15(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) #define NLOHMANN_JSON_PASTE17(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE16(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) #define NLOHMANN_JSON_PASTE18(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE17(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) #define NLOHMANN_JSON_PASTE19(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE18(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) #define NLOHMANN_JSON_PASTE20(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE19(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) #define NLOHMANN_JSON_PASTE21(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE20(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) #define NLOHMANN_JSON_PASTE22(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE21(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) #define NLOHMANN_JSON_PASTE23(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE22(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) #define NLOHMANN_JSON_PASTE24(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE23(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) #define NLOHMANN_JSON_PASTE25(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE24(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) #define NLOHMANN_JSON_PASTE26(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE25(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) #define NLOHMANN_JSON_PASTE27(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE26(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) #define NLOHMANN_JSON_PASTE28(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE27(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) #define NLOHMANN_JSON_PASTE29(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE28(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) #define NLOHMANN_JSON_PASTE30(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE29(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) #define NLOHMANN_JSON_PASTE31(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE30(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) #define NLOHMANN_JSON_PASTE32(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE31(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) #define NLOHMANN_JSON_PASTE33(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE32(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) #define NLOHMANN_JSON_PASTE34(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE33(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) #define NLOHMANN_JSON_PASTE35(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE34(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) #define NLOHMANN_JSON_PASTE36(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE35(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) #define NLOHMANN_JSON_PASTE37(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE36(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) #define NLOHMANN_JSON_PASTE38(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE37(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) #define NLOHMANN_JSON_PASTE39(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE38(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) #define NLOHMANN_JSON_PASTE40(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE39(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) #define NLOHMANN_JSON_PASTE41(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE40(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) #define NLOHMANN_JSON_PASTE42(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE41(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) #define NLOHMANN_JSON_PASTE43(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE42(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) #define NLOHMANN_JSON_PASTE44(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE43(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) #define NLOHMANN_JSON_PASTE45(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE44(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) #define NLOHMANN_JSON_PASTE46(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE45(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) #define NLOHMANN_JSON_PASTE47(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE46(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) #define NLOHMANN_JSON_PASTE48(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE47(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) #define NLOHMANN_JSON_PASTE49(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE48(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) #define NLOHMANN_JSON_PASTE50(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE49(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) #define NLOHMANN_JSON_PASTE51(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE50(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) #define NLOHMANN_JSON_PASTE52(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE51(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) #define NLOHMANN_JSON_PASTE53(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE52(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) #define NLOHMANN_JSON_PASTE54(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE53(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) #define NLOHMANN_JSON_PASTE55(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE54(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) #define NLOHMANN_JSON_PASTE56(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE55(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) #define NLOHMANN_JSON_PASTE57(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE56(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) #define NLOHMANN_JSON_PASTE58(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE57(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) #define NLOHMANN_JSON_PASTE59(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE58(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) #define NLOHMANN_JSON_PASTE60(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE59(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) #define NLOHMANN_JSON_PASTE61(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE60(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) #define NLOHMANN_JSON_PASTE62(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE61(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) #define NLOHMANN_JSON_PASTE63(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE62(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) #define NLOHMANN_JSON_PASTE64(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE63(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) #define NLOHMANN_JSON_TO(v1) nlohmann_json_j[#v1] = nlohmann_json_t.v1; #define NLOHMANN_JSON_FROM(v1) nlohmann_json_j.at(#v1).get_to(nlohmann_json_t.v1); /*! @brief macro @def NLOHMANN_DEFINE_TYPE_INTRUSIVE @since version 3.9.0 */ #define NLOHMANN_DEFINE_TYPE_INTRUSIVE(Type, ...) \ friend void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ friend void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } /*! @brief macro @def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE @since version 3.9.0 */ #define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Type, ...) \ inline void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ inline void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } #ifndef JSON_USE_IMPLICIT_CONVERSIONS #define JSON_USE_IMPLICIT_CONVERSIONS 1 #endif #if JSON_USE_IMPLICIT_CONVERSIONS #define JSON_EXPLICIT #else #define JSON_EXPLICIT explicit #endif namespace nlohmann { namespace detail { /*! @brief replace all occurrences of a substring by another string @param[in,out] s the string to manipulate; changed so that all occurrences of @a f are replaced with @a t @param[in] f the substring to replace with @a t @param[in] t the string to replace @a f @pre The search string @a f must not be empty. **This precondition is enforced with an assertion.** @since version 2.0.0 */ inline void replace_substring(std::string& s, const std::string& f, const std::string& t) { JSON_ASSERT(!f.empty()); for (auto pos = s.find(f); // find first occurrence of f pos != std::string::npos; // make sure f was found s.replace(pos, f.size(), t), // replace with t, and pos = s.find(f, pos + t.size())) // find next occurrence of f {} } /*! * @brief string escaping as described in RFC 6901 (Sect. 4) * @param[in] s string to escape * @return escaped string * * Note the order of escaping "~" to "~0" and "/" to "~1" is important. */ inline std::string escape(std::string s) { replace_substring(s, "~", "~0"); replace_substring(s, "/", "~1"); return s; } /*! * @brief string unescaping as described in RFC 6901 (Sect. 4) * @param[in] s string to unescape * @return unescaped string * * Note the order of escaping "~1" to "/" and "~0" to "~" is important. */ static void unescape(std::string& s) { replace_substring(s, "~1", "/"); replace_substring(s, "~0", "~"); } } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/input/position_t.hpp> #include <cstddef> // size_t namespace nlohmann { namespace detail { /// struct to capture the start position of the current token struct position_t { /// the total number of characters read std::size_t chars_read_total = 0; /// the number of characters read in the current line std::size_t chars_read_current_line = 0; /// the number of lines read std::size_t lines_read = 0; /// conversion to size_t to preserve SAX interface constexpr operator size_t() const { return chars_read_total; } }; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/macro_scope.hpp> namespace nlohmann { namespace detail { //////////////// // exceptions // //////////////// /*! @brief general exception of the @ref basic_json class This class is an extension of `std::exception` objects with a member @a id for exception ids. It is used as the base class for all exceptions thrown by the @ref basic_json class. This class can hence be used as "wildcard" to catch exceptions. Subclasses: - @ref parse_error for exceptions indicating a parse error - @ref invalid_iterator for exceptions indicating errors with iterators - @ref type_error for exceptions indicating executing a member function with a wrong type - @ref out_of_range for exceptions indicating access out of the defined range - @ref other_error for exceptions indicating other library errors @internal @note To have nothrow-copy-constructible exceptions, we internally use `std::runtime_error` which can cope with arbitrary-length error messages. Intermediate strings are built with static functions and then passed to the actual constructor. @endinternal @liveexample{The following code shows how arbitrary library exceptions can be caught.,exception} @since version 3.0.0 */ class exception : public std::exception { public: /// returns the explanatory string const char* what() const noexcept override { return m.what(); } /// the id of the exception const int id; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes) protected: JSON_HEDLEY_NON_NULL(3) exception(int id_, const char* what_arg) : id(id_), m(what_arg) {} static std::string name(const std::string& ename, int id_) { return "[json.exception." + ename + "." + std::to_string(id_) + "] "; } template<typename BasicJsonType> static std::string diagnostics(const BasicJsonType& leaf_element) { #if JSON_DIAGNOSTICS std::vector<std::string> tokens; for (const auto* current = &leaf_element; current->m_parent != nullptr; current = current->m_parent) { switch (current->m_parent->type()) { case value_t::array: { for (std::size_t i = 0; i < current->m_parent->m_value.array->size(); ++i) { if (&current->m_parent->m_value.array->operator[](i) == current) { tokens.emplace_back(std::to_string(i)); break; } } break; } case value_t::object: { for (const auto& element : *current->m_parent->m_value.object) { if (&element.second == current) { tokens.emplace_back(element.first.c_str()); break; } } break; } default: // LCOV_EXCL_LINE break; // LCOV_EXCL_LINE } } if (tokens.empty()) { return ""; } return "(" + std::accumulate(tokens.rbegin(), tokens.rend(), std::string{}, [](const std::string & a, const std::string & b) { return a + "/" + detail::escape(b); }) + ") "; #else static_cast<void>(leaf_element); return ""; #endif } private: /// an exception object as storage for error messages std::runtime_error m; }; /*! @brief exception indicating a parse error This exception is thrown by the library when a parse error occurs. Parse errors can occur during the deserialization of JSON text, CBOR, MessagePack, as well as when using JSON Patch. Member @a byte holds the byte index of the last read character in the input file. Exceptions have ids 1xx. name / id | example message | description ------------------------------ | --------------- | ------------------------- json.exception.parse_error.101 | parse error at 2: unexpected end of input; expected string literal | This error indicates a syntax error while deserializing a JSON text. The error message describes that an unexpected token (character) was encountered, and the member @a byte indicates the error position. json.exception.parse_error.102 | parse error at 14: missing or wrong low surrogate | JSON uses the `\uxxxx` format to describe Unicode characters. Code points above above 0xFFFF are split into two `\uxxxx` entries ("surrogate pairs"). This error indicates that the surrogate pair is incomplete or contains an invalid code point. json.exception.parse_error.103 | parse error: code points above 0x10FFFF are invalid | Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid. json.exception.parse_error.104 | parse error: JSON patch must be an array of objects | [RFC 6902](https://tools.ietf.org/html/rfc6902) requires a JSON Patch document to be a JSON document that represents an array of objects. json.exception.parse_error.105 | parse error: operation must have string member 'op' | An operation of a JSON Patch document must contain exactly one "op" member, whose value indicates the operation to perform. Its value must be one of "add", "remove", "replace", "move", "copy", or "test"; other values are errors. json.exception.parse_error.106 | parse error: array index '01' must not begin with '0' | An array index in a JSON Pointer ([RFC 6901](https://tools.ietf.org/html/rfc6901)) may be `0` or any number without a leading `0`. json.exception.parse_error.107 | parse error: JSON pointer must be empty or begin with '/' - was: 'foo' | A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a `/` character. json.exception.parse_error.108 | parse error: escape character '~' must be followed with '0' or '1' | In a JSON Pointer, only `~0` and `~1` are valid escape sequences. json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number. json.exception.parse_error.110 | parse error at 1: cannot read 2 bytes from vector | When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read. json.exception.parse_error.112 | parse error at 1: error reading CBOR; last byte: 0xF8 | Not all types of CBOR or MessagePack are supported. This exception occurs if an unsupported byte was read. json.exception.parse_error.113 | parse error at 2: expected a CBOR string; last byte: 0x98 | While parsing a map key, a value that is not a string has been read. json.exception.parse_error.114 | parse error: Unsupported BSON record type 0x0F | The parsing of the corresponding BSON record type is not implemented (yet). json.exception.parse_error.115 | parse error at byte 5: syntax error while parsing UBJSON high-precision number: invalid number text: 1A | A UBJSON high-precision number could not be parsed. @note For an input with n bytes, 1 is the index of the first character and n+1 is the index of the terminating null byte or the end of file. This also holds true when reading a byte vector (CBOR or MessagePack). @liveexample{The following code shows how a `parse_error` exception can be caught.,parse_error} @sa - @ref exception for the base class of the library exceptions @sa - @ref invalid_iterator for exceptions indicating errors with iterators @sa - @ref type_error for exceptions indicating executing a member function with a wrong type @sa - @ref out_of_range for exceptions indicating access out of the defined range @sa - @ref other_error for exceptions indicating other library errors @since version 3.0.0 */ class parse_error : public exception { public: /*! @brief create a parse error exception @param[in] id_ the id of the exception @param[in] pos the position where the error occurred (or with chars_read_total=0 if the position cannot be determined) @param[in] what_arg the explanatory string @return parse_error object */ template<typename BasicJsonType> static parse_error create(int id_, const position_t& pos, const std::string& what_arg, const BasicJsonType& context) { std::string w = exception::name("parse_error", id_) + "parse error" + position_string(pos) + ": " + exception::diagnostics(context) + what_arg; return parse_error(id_, pos.chars_read_total, w.c_str()); } template<typename BasicJsonType> static parse_error create(int id_, std::size_t byte_, const std::string& what_arg, const BasicJsonType& context) { std::string w = exception::name("parse_error", id_) + "parse error" + (byte_ != 0 ? (" at byte " + std::to_string(byte_)) : "") + ": " + exception::diagnostics(context) + what_arg; return parse_error(id_, byte_, w.c_str()); } /*! @brief byte index of the parse error The byte index of the last read character in the input file. @note For an input with n bytes, 1 is the index of the first character and n+1 is the index of the terminating null byte or the end of file. This also holds true when reading a byte vector (CBOR or MessagePack). */ const std::size_t byte; private: parse_error(int id_, std::size_t byte_, const char* what_arg) : exception(id_, what_arg), byte(byte_) {} static std::string position_string(const position_t& pos) { return " at line " + std::to_string(pos.lines_read + 1) + ", column " + std::to_string(pos.chars_read_current_line); } }; /*! @brief exception indicating errors with iterators This exception is thrown if iterators passed to a library function do not match the expected semantics. Exceptions have ids 2xx. name / id | example message | description ----------------------------------- | --------------- | ------------------------- json.exception.invalid_iterator.201 | iterators are not compatible | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid. json.exception.invalid_iterator.202 | iterator does not fit current value | In an erase or insert function, the passed iterator @a pos does not belong to the JSON value for which the function was called. It hence does not define a valid position for the deletion/insertion. json.exception.invalid_iterator.203 | iterators do not fit current value | Either iterator passed to function @ref erase(IteratorType first, IteratorType last) does not belong to the JSON value from which values shall be erased. It hence does not define a valid range to delete values from. json.exception.invalid_iterator.204 | iterators out of range | When an iterator range for a primitive type (number, boolean, or string) is passed to a constructor or an erase function, this range has to be exactly (@ref begin(), @ref end()), because this is the only way the single stored value is expressed. All other ranges are invalid. json.exception.invalid_iterator.205 | iterator out of range | When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the @ref begin() iterator, because it is the only way to address the stored value. All other iterators are invalid. json.exception.invalid_iterator.206 | cannot construct with iterators from null | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) belong to a JSON null value and hence to not define a valid range. json.exception.invalid_iterator.207 | cannot use key() for non-object iterators | The key() member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key. json.exception.invalid_iterator.208 | cannot use operator[] for object iterators | The operator[] to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. json.exception.invalid_iterator.209 | cannot use offsets with object iterators | The offset operators (+, -, +=, -=) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. json.exception.invalid_iterator.210 | iterators do not fit | The iterator range passed to the insert function are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid. json.exception.invalid_iterator.211 | passed iterators may not belong to container | The iterator range passed to the insert function must not be a subrange of the container to insert to. json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container. json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered. json.exception.invalid_iterator.214 | cannot get value | Cannot get value for iterator: Either the iterator belongs to a null value or it is an iterator to a primitive type (number, boolean, or string), but the iterator is different to @ref begin(). @liveexample{The following code shows how an `invalid_iterator` exception can be caught.,invalid_iterator} @sa - @ref exception for the base class of the library exceptions @sa - @ref parse_error for exceptions indicating a parse error @sa - @ref type_error for exceptions indicating executing a member function with a wrong type @sa - @ref out_of_range for exceptions indicating access out of the defined range @sa - @ref other_error for exceptions indicating other library errors @since version 3.0.0 */ class invalid_iterator : public exception { public: template<typename BasicJsonType> static invalid_iterator create(int id_, const std::string& what_arg, const BasicJsonType& context) { std::string w = exception::name("invalid_iterator", id_) + exception::diagnostics(context) + what_arg; return invalid_iterator(id_, w.c_str()); } private: JSON_HEDLEY_NON_NULL(3) invalid_iterator(int id_, const char* what_arg) : exception(id_, what_arg) {} }; /*! @brief exception indicating executing a member function with a wrong type This exception is thrown in case of a type error; that is, a library function is executed on a JSON value whose type does not match the expected semantics. Exceptions have ids 3xx. name / id | example message | description ----------------------------- | --------------- | ------------------------- json.exception.type_error.301 | cannot create object from initializer list | To create an object from an initializer list, the initializer list must consist only of a list of pairs whose first element is a string. When this constraint is violated, an array is created instead. json.exception.type_error.302 | type must be object, but is array | During implicit or explicit value conversion, the JSON type must be compatible to the target type. For instance, a JSON string can only be converted into string types, but not into numbers or boolean types. json.exception.type_error.303 | incompatible ReferenceType for get_ref, actual type is object | To retrieve a reference to a value stored in a @ref basic_json object with @ref get_ref, the type of the reference must match the value type. For instance, for a JSON array, the @a ReferenceType must be @ref array_t &. json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types. json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types. json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types. json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types. json.exception.type_error.308 | cannot use push_back() with string | The @ref push_back() and @ref operator+= member functions can only be executed for certain JSON types. json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types. json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types. json.exception.type_error.311 | cannot use emplace_back() with string | The @ref emplace_back() member function can only be executed for certain JSON types. json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types. json.exception.type_error.313 | invalid value to unflatten | The @ref unflatten function converts an object whose keys are JSON Pointers back into an arbitrary nested JSON value. The JSON Pointers must not overlap, because then the resulting value would not be well defined. json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers. json.exception.type_error.315 | values in object must be primitive | The @ref unflatten function only works for an object whose keys are JSON Pointers and whose values are primitive. json.exception.type_error.316 | invalid UTF-8 byte at index 10: 0x7E | The @ref dump function only works with UTF-8 encoded strings; that is, if you assign a `std::string` to a JSON value, make sure it is UTF-8 encoded. | json.exception.type_error.317 | JSON value cannot be serialized to requested format | The dynamic type of the object cannot be represented in the requested serialization format (e.g. a raw `true` or `null` JSON object cannot be serialized to BSON) | @liveexample{The following code shows how a `type_error` exception can be caught.,type_error} @sa - @ref exception for the base class of the library exceptions @sa - @ref parse_error for exceptions indicating a parse error @sa - @ref invalid_iterator for exceptions indicating errors with iterators @sa - @ref out_of_range for exceptions indicating access out of the defined range @sa - @ref other_error for exceptions indicating other library errors @since version 3.0.0 */ class type_error : public exception { public: template<typename BasicJsonType> static type_error create(int id_, const std::string& what_arg, const BasicJsonType& context) { std::string w = exception::name("type_error", id_) + exception::diagnostics(context) + what_arg; return type_error(id_, w.c_str()); } private: JSON_HEDLEY_NON_NULL(3) type_error(int id_, const char* what_arg) : exception(id_, what_arg) {} }; /*! @brief exception indicating access out of the defined range This exception is thrown in case a library function is called on an input parameter that exceeds the expected range, for instance in case of array indices or nonexisting object keys. Exceptions have ids 4xx. name / id | example message | description ------------------------------- | --------------- | ------------------------- json.exception.out_of_range.401 | array index 3 is out of range | The provided array index @a i is larger than @a size-1. json.exception.out_of_range.402 | array index '-' (3) is out of range | The special array index `-` in a JSON Pointer never describes a valid element of the array, but the index past the end. That is, it can only be used to add elements at this position, but not to read it. json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object. json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved. json.exception.out_of_range.405 | JSON pointer has no parent | The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value. json.exception.out_of_range.406 | number overflow parsing '10E1000' | A parsed number could not be stored as without changing it to NaN or INF. json.exception.out_of_range.407 | number overflow serializing '9223372036854775808' | UBJSON and BSON only support integer numbers up to 9223372036854775807. (until version 3.8.0) | json.exception.out_of_range.408 | excessive array size: 8658170730974374167 | The size (following `#`) of an UBJSON array or object exceeds the maximal capacity. | json.exception.out_of_range.409 | BSON key cannot contain code point U+0000 (at byte 2) | Key identifiers to be serialized to BSON cannot contain code point U+0000, since the key is stored as zero-terminated c-string | @liveexample{The following code shows how an `out_of_range` exception can be caught.,out_of_range} @sa - @ref exception for the base class of the library exceptions @sa - @ref parse_error for exceptions indicating a parse error @sa - @ref invalid_iterator for exceptions indicating errors with iterators @sa - @ref type_error for exceptions indicating executing a member function with a wrong type @sa - @ref other_error for exceptions indicating other library errors @since version 3.0.0 */ class out_of_range : public exception { public: template<typename BasicJsonType> static out_of_range create(int id_, const std::string& what_arg, const BasicJsonType& context) { std::string w = exception::name("out_of_range", id_) + exception::diagnostics(context) + what_arg; return out_of_range(id_, w.c_str()); } private: JSON_HEDLEY_NON_NULL(3) out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {} }; /*! @brief exception indicating other library errors This exception is thrown in case of errors that cannot be classified with the other exception types. Exceptions have ids 5xx. name / id | example message | description ------------------------------ | --------------- | ------------------------- json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed. @sa - @ref exception for the base class of the library exceptions @sa - @ref parse_error for exceptions indicating a parse error @sa - @ref invalid_iterator for exceptions indicating errors with iterators @sa - @ref type_error for exceptions indicating executing a member function with a wrong type @sa - @ref out_of_range for exceptions indicating access out of the defined range @liveexample{The following code shows how an `other_error` exception can be caught.,other_error} @since version 3.0.0 */ class other_error : public exception { public: template<typename BasicJsonType> static other_error create(int id_, const std::string& what_arg, const BasicJsonType& context) { std::string w = exception::name("other_error", id_) + exception::diagnostics(context) + what_arg; return other_error(id_, w.c_str()); } private: JSON_HEDLEY_NON_NULL(3) other_error(int id_, const char* what_arg) : exception(id_, what_arg) {} }; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/macro_scope.hpp> // #include <nlohmann/detail/meta/cpp_future.hpp> #include <cstddef> // size_t #include <type_traits> // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type #include <utility> // index_sequence, make_index_sequence, index_sequence_for // #include <nlohmann/detail/macro_scope.hpp> namespace nlohmann { namespace detail { template<typename T> using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type; #ifdef JSON_HAS_CPP_14 // the following utilities are natively available in C++14 using std::enable_if_t; using std::index_sequence; using std::make_index_sequence; using std::index_sequence_for; #else // alias templates to reduce boilerplate template<bool B, typename T = void> using enable_if_t = typename std::enable_if<B, T>::type; // The following code is taken from https://github.com/abseil/abseil-cpp/blob/10cb35e459f5ecca5b2ff107635da0bfa41011b4/absl/utility/utility.h // which is part of Google Abseil (https://github.com/abseil/abseil-cpp), licensed under the Apache License 2.0. //// START OF CODE FROM GOOGLE ABSEIL // integer_sequence // // Class template representing a compile-time integer sequence. An instantiation // of `integer_sequence<T, Ints...>` has a sequence of integers encoded in its // type through its template arguments (which is a common need when // working with C++11 variadic templates). `absl::integer_sequence` is designed // to be a drop-in replacement for C++14's `std::integer_sequence`. // // Example: // // template< class T, T... Ints > // void user_function(integer_sequence<T, Ints...>); // // int main() // { // // user_function's `T` will be deduced to `int` and `Ints...` // // will be deduced to `0, 1, 2, 3, 4`. // user_function(make_integer_sequence<int, 5>()); // } template <typename T, T... Ints> struct integer_sequence { using value_type = T; static constexpr std::size_t size() noexcept { return sizeof...(Ints); } }; // index_sequence // // A helper template for an `integer_sequence` of `size_t`, // `absl::index_sequence` is designed to be a drop-in replacement for C++14's // `std::index_sequence`. template <size_t... Ints> using index_sequence = integer_sequence<size_t, Ints...>; namespace utility_internal { template <typename Seq, size_t SeqSize, size_t Rem> struct Extend; // Note that SeqSize == sizeof...(Ints). It's passed explicitly for efficiency. template <typename T, T... Ints, size_t SeqSize> struct Extend<integer_sequence<T, Ints...>, SeqSize, 0> { using type = integer_sequence < T, Ints..., (Ints + SeqSize)... >; }; template <typename T, T... Ints, size_t SeqSize> struct Extend<integer_sequence<T, Ints...>, SeqSize, 1> { using type = integer_sequence < T, Ints..., (Ints + SeqSize)..., 2 * SeqSize >; }; // Recursion helper for 'make_integer_sequence<T, N>'. // 'Gen<T, N>::type' is an alias for 'integer_sequence<T, 0, 1, ... N-1>'. template <typename T, size_t N> struct Gen { using type = typename Extend < typename Gen < T, N / 2 >::type, N / 2, N % 2 >::type; }; template <typename T> struct Gen<T, 0> { using type = integer_sequence<T>; }; } // namespace utility_internal // Compile-time sequences of integers // make_integer_sequence // // This template alias is equivalent to // `integer_sequence<int, 0, 1, ..., N-1>`, and is designed to be a drop-in // replacement for C++14's `std::make_integer_sequence`. template <typename T, T N> using make_integer_sequence = typename utility_internal::Gen<T, N>::type; // make_index_sequence // // This template alias is equivalent to `index_sequence<0, 1, ..., N-1>`, // and is designed to be a drop-in replacement for C++14's // `std::make_index_sequence`. template <size_t N> using make_index_sequence = make_integer_sequence<size_t, N>; // index_sequence_for // // Converts a typename pack into an index sequence of the same length, and // is designed to be a drop-in replacement for C++14's // `std::index_sequence_for()` template <typename... Ts> using index_sequence_for = make_index_sequence<sizeof...(Ts)>; //// END OF CODE FROM GOOGLE ABSEIL #endif // dispatch utility (taken from ranges-v3) template<unsigned N> struct priority_tag : priority_tag < N - 1 > {}; template<> struct priority_tag<0> {}; // taken from ranges-v3 template<typename T> struct static_const { static constexpr T value{}; }; template<typename T> constexpr T static_const<T>::value; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/meta/identity_tag.hpp> namespace nlohmann { namespace detail { // dispatching helper struct template <class T> struct identity_tag {}; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/meta/type_traits.hpp> #include <limits> // numeric_limits #include <type_traits> // false_type, is_constructible, is_integral, is_same, true_type #include <utility> // declval #include <tuple> // tuple // #include <nlohmann/detail/iterators/iterator_traits.hpp> #include <iterator> // random_access_iterator_tag // #include <nlohmann/detail/meta/void_t.hpp> namespace nlohmann { namespace detail { template<typename ...Ts> struct make_void { using type = void; }; template<typename ...Ts> using void_t = typename make_void<Ts...>::type; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/meta/cpp_future.hpp> namespace nlohmann { namespace detail { template<typename It, typename = void> struct iterator_types {}; template<typename It> struct iterator_types < It, void_t<typename It::difference_type, typename It::value_type, typename It::pointer, typename It::reference, typename It::iterator_category >> { using difference_type = typename It::difference_type; using value_type = typename It::value_type; using pointer = typename It::pointer; using reference = typename It::reference; using iterator_category = typename It::iterator_category; }; // This is required as some compilers implement std::iterator_traits in a way that // doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341. template<typename T, typename = void> struct iterator_traits { }; template<typename T> struct iterator_traits < T, enable_if_t < !std::is_pointer<T>::value >> : iterator_types<T> { }; template<typename T> struct iterator_traits<T*, enable_if_t<std::is_object<T>::value>> { using iterator_category = std::random_access_iterator_tag; using value_type = T; using difference_type = ptrdiff_t; using pointer = T*; using reference = T&; }; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/macro_scope.hpp> // #include <nlohmann/detail/meta/cpp_future.hpp> // #include <nlohmann/detail/meta/detected.hpp> #include <type_traits> // #include <nlohmann/detail/meta/void_t.hpp> // https://en.cppreference.com/w/cpp/experimental/is_detected namespace nlohmann { namespace detail { struct nonesuch { nonesuch() = delete; ~nonesuch() = delete; nonesuch(nonesuch const&) = delete; nonesuch(nonesuch const&&) = delete; void operator=(nonesuch const&) = delete; void operator=(nonesuch&&) = delete; }; template<class Default, class AlwaysVoid, template<class...> class Op, class... Args> struct detector { using value_t = std::false_type; using type = Default; }; template<class Default, template<class...> class Op, class... Args> struct detector<Default, void_t<Op<Args...>>, Op, Args...> { using value_t = std::true_type; using type = Op<Args...>; }; template<template<class...> class Op, class... Args> using is_detected = typename detector<nonesuch, void, Op, Args...>::value_t; template<template<class...> class Op, class... Args> using detected_t = typename detector<nonesuch, void, Op, Args...>::type; template<class Default, template<class...> class Op, class... Args> using detected_or = detector<Default, void, Op, Args...>; template<class Default, template<class...> class Op, class... Args> using detected_or_t = typename detected_or<Default, Op, Args...>::type; template<class Expected, template<class...> class Op, class... Args> using is_detected_exact = std::is_same<Expected, detected_t<Op, Args...>>; template<class To, template<class...> class Op, class... Args> using is_detected_convertible = std::is_convertible<detected_t<Op, Args...>, To>; } // namespace detail } // namespace nlohmann // #include <nlohmann/json_fwd.hpp> #ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_ #define INCLUDE_NLOHMANN_JSON_FWD_HPP_ #include <cstdint> // int64_t, uint64_t #include <map> // map #include <memory> // allocator #include <string> // string #include <vector> // vector /*! @brief namespace for Niels Lohmann @see https://github.com/nlohmann @since version 1.0.0 */ namespace nlohmann { /*! @brief default JSONSerializer template argument This serializer ignores the template arguments and uses ADL ([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl)) for serialization. */ template<typename T = void, typename SFINAE = void> struct adl_serializer; template<template<typename U, typename V, typename... Args> class ObjectType = std::map, template<typename U, typename... Args> class ArrayType = std::vector, class StringType = std::string, class BooleanType = bool, class NumberIntegerType = std::int64_t, class NumberUnsignedType = std::uint64_t, class NumberFloatType = double, template<typename U> class AllocatorType = std::allocator, template<typename T, typename SFINAE = void> class JSONSerializer = adl_serializer, class BinaryType = std::vector<std::uint8_t>> class basic_json; /*! @brief JSON Pointer A JSON pointer defines a string syntax for identifying a specific value within a JSON document. It can be used with functions `at` and `operator[]`. Furthermore, JSON pointers are the base for JSON patches. @sa [RFC 6901](https://tools.ietf.org/html/rfc6901) @since version 2.0.0 */ template<typename BasicJsonType> class json_pointer; /*! @brief default JSON class This type is the default specialization of the @ref basic_json class which uses the standard template types. @since version 1.0.0 */ using json = basic_json<>; template<class Key, class T, class IgnoredLess, class Allocator> struct ordered_map; /*! @brief ordered JSON class This type preserves the insertion order of object keys. @since version 3.9.0 */ using ordered_json = basic_json<nlohmann::ordered_map>; } // namespace nlohmann #endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_ namespace nlohmann { /*! @brief detail namespace with internal helper functions This namespace collects functions that should not be exposed, implementations of some @ref basic_json methods, and meta-programming helpers. @since version 2.1.0 */ namespace detail { ///////////// // helpers // ///////////// // Note to maintainers: // // Every trait in this file expects a non CV-qualified type. // The only exceptions are in the 'aliases for detected' section // (i.e. those of the form: decltype(T::member_function(std::declval<T>()))) // // In this case, T has to be properly CV-qualified to constraint the function arguments // (e.g. to_json(BasicJsonType&, const T&)) template<typename> struct is_basic_json : std::false_type {}; NLOHMANN_BASIC_JSON_TPL_DECLARATION struct is_basic_json<NLOHMANN_BASIC_JSON_TPL> : std::true_type {}; ////////////////////// // json_ref helpers // ////////////////////// template<typename> class json_ref; template<typename> struct is_json_ref : std::false_type {}; template<typename T> struct is_json_ref<json_ref<T>> : std::true_type {}; ////////////////////////// // aliases for detected // ////////////////////////// template<typename T> using mapped_type_t = typename T::mapped_type; template<typename T> using key_type_t = typename T::key_type; template<typename T> using value_type_t = typename T::value_type; template<typename T> using difference_type_t = typename T::difference_type; template<typename T> using pointer_t = typename T::pointer; template<typename T> using reference_t = typename T::reference; template<typename T> using iterator_category_t = typename T::iterator_category; template<typename T> using iterator_t = typename T::iterator; template<typename T, typename... Args> using to_json_function = decltype(T::to_json(std::declval<Args>()...)); template<typename T, typename... Args> using from_json_function = decltype(T::from_json(std::declval<Args>()...)); template<typename T, typename U> using get_template_function = decltype(std::declval<T>().template get<U>()); // trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists template<typename BasicJsonType, typename T, typename = void> struct has_from_json : std::false_type {}; // trait checking if j.get<T> is valid // use this trait instead of std::is_constructible or std::is_convertible, // both rely on, or make use of implicit conversions, and thus fail when T // has several constructors/operator= (see https://github.com/nlohmann/json/issues/958) template <typename BasicJsonType, typename T> struct is_getable { static constexpr bool value = is_detected<get_template_function, const BasicJsonType&, T>::value; }; template<typename BasicJsonType, typename T> struct has_from_json < BasicJsonType, T, enable_if_t < !is_basic_json<T>::value >> { using serializer = typename BasicJsonType::template json_serializer<T, void>; static constexpr bool value = is_detected_exact<void, from_json_function, serializer, const BasicJsonType&, T&>::value; }; // This trait checks if JSONSerializer<T>::from_json(json const&) exists // this overload is used for non-default-constructible user-defined-types template<typename BasicJsonType, typename T, typename = void> struct has_non_default_from_json : std::false_type {}; template<typename BasicJsonType, typename T> struct has_non_default_from_json < BasicJsonType, T, enable_if_t < !is_basic_json<T>::value >> { using serializer = typename BasicJsonType::template json_serializer<T, void>; static constexpr bool value = is_detected_exact<T, from_json_function, serializer, const BasicJsonType&>::value; }; // This trait checks if BasicJsonType::json_serializer<T>::to_json exists // Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion. template<typename BasicJsonType, typename T, typename = void> struct has_to_json : std::false_type {}; template<typename BasicJsonType, typename T> struct has_to_json < BasicJsonType, T, enable_if_t < !is_basic_json<T>::value >> { using serializer = typename BasicJsonType::template json_serializer<T, void>; static constexpr bool value = is_detected_exact<void, to_json_function, serializer, BasicJsonType&, T>::value; }; /////////////////// // is_ functions // /////////////////// // https://en.cppreference.com/w/cpp/types/conjunction template<class...> struct conjunction : std::true_type { }; template<class B1> struct conjunction<B1> : B1 { }; template<class B1, class... Bn> struct conjunction<B1, Bn...> : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {}; // Reimplementation of is_constructible and is_default_constructible, due to them being broken for // std::pair and std::tuple until LWG 2367 fix (see https://cplusplus.github.io/LWG/lwg-defects.html#2367). // This causes compile errors in e.g. clang 3.5 or gcc 4.9. template <typename T> struct is_default_constructible : std::is_default_constructible<T> {}; template <typename T1, typename T2> struct is_default_constructible<std::pair<T1, T2>> : conjunction<is_default_constructible<T1>, is_default_constructible<T2>> {}; template <typename T1, typename T2> struct is_default_constructible<const std::pair<T1, T2>> : conjunction<is_default_constructible<T1>, is_default_constructible<T2>> {}; template <typename... Ts> struct is_default_constructible<std::tuple<Ts...>> : conjunction<is_default_constructible<Ts>...> {}; template <typename... Ts> struct is_default_constructible<const std::tuple<Ts...>> : conjunction<is_default_constructible<Ts>...> {}; template <typename T, typename... Args> struct is_constructible : std::is_constructible<T, Args...> {}; template <typename T1, typename T2> struct is_constructible<std::pair<T1, T2>> : is_default_constructible<std::pair<T1, T2>> {}; template <typename T1, typename T2> struct is_constructible<const std::pair<T1, T2>> : is_default_constructible<const std::pair<T1, T2>> {}; template <typename... Ts> struct is_constructible<std::tuple<Ts...>> : is_default_constructible<std::tuple<Ts...>> {}; template <typename... Ts> struct is_constructible<const std::tuple<Ts...>> : is_default_constructible<const std::tuple<Ts...>> {}; template<typename T, typename = void> struct is_iterator_traits : std::false_type {}; template<typename T> struct is_iterator_traits<iterator_traits<T>> { private: using traits = iterator_traits<T>; public: static constexpr auto value = is_detected<value_type_t, traits>::value && is_detected<difference_type_t, traits>::value && is_detected<pointer_t, traits>::value && is_detected<iterator_category_t, traits>::value && is_detected<reference_t, traits>::value; }; // The following implementation of is_complete_type is taken from // https://blogs.msdn.microsoft.com/vcblog/2015/12/02/partial-support-for-expression-sfinae-in-vs-2015-update-1/ // and is written by Xiang Fan who agreed to using it in this library. template<typename T, typename = void> struct is_complete_type : std::false_type {}; template<typename T> struct is_complete_type<T, decltype(void(sizeof(T)))> : std::true_type {}; template<typename BasicJsonType, typename CompatibleObjectType, typename = void> struct is_compatible_object_type_impl : std::false_type {}; template<typename BasicJsonType, typename CompatibleObjectType> struct is_compatible_object_type_impl < BasicJsonType, CompatibleObjectType, enable_if_t < is_detected<mapped_type_t, CompatibleObjectType>::value&& is_detected<key_type_t, CompatibleObjectType>::value >> { using object_t = typename BasicJsonType::object_t; // macOS's is_constructible does not play well with nonesuch... static constexpr bool value = is_constructible<typename object_t::key_type, typename CompatibleObjectType::key_type>::value && is_constructible<typename object_t::mapped_type, typename CompatibleObjectType::mapped_type>::value; }; template<typename BasicJsonType, typename CompatibleObjectType> struct is_compatible_object_type : is_compatible_object_type_impl<BasicJsonType, CompatibleObjectType> {}; template<typename BasicJsonType, typename ConstructibleObjectType, typename = void> struct is_constructible_object_type_impl : std::false_type {}; template<typename BasicJsonType, typename ConstructibleObjectType> struct is_constructible_object_type_impl < BasicJsonType, ConstructibleObjectType, enable_if_t < is_detected<mapped_type_t, ConstructibleObjectType>::value&& is_detected<key_type_t, ConstructibleObjectType>::value >> { using object_t = typename BasicJsonType::object_t; static constexpr bool value = (is_default_constructible<ConstructibleObjectType>::value && (std::is_move_assignable<ConstructibleObjectType>::value || std::is_copy_assignable<ConstructibleObjectType>::value) && (is_constructible<typename ConstructibleObjectType::key_type, typename object_t::key_type>::value && std::is_same < typename object_t::mapped_type, typename ConstructibleObjectType::mapped_type >::value)) || (has_from_json<BasicJsonType, typename ConstructibleObjectType::mapped_type>::value || has_non_default_from_json < BasicJsonType, typename ConstructibleObjectType::mapped_type >::value); }; template<typename BasicJsonType, typename ConstructibleObjectType> struct is_constructible_object_type : is_constructible_object_type_impl<BasicJsonType, ConstructibleObjectType> {}; template<typename BasicJsonType, typename CompatibleStringType, typename = void> struct is_compatible_string_type_impl : std::false_type {}; template<typename BasicJsonType, typename CompatibleStringType> struct is_compatible_string_type_impl < BasicJsonType, CompatibleStringType, enable_if_t<is_detected_exact<typename BasicJsonType::string_t::value_type, value_type_t, CompatibleStringType>::value >> { static constexpr auto value = is_constructible<typename BasicJsonType::string_t, CompatibleStringType>::value; }; template<typename BasicJsonType, typename ConstructibleStringType> struct is_compatible_string_type : is_compatible_string_type_impl<BasicJsonType, ConstructibleStringType> {}; template<typename BasicJsonType, typename ConstructibleStringType, typename = void> struct is_constructible_string_type_impl : std::false_type {}; template<typename BasicJsonType, typename ConstructibleStringType> struct is_constructible_string_type_impl < BasicJsonType, ConstructibleStringType, enable_if_t<is_detected_exact<typename BasicJsonType::string_t::value_type, value_type_t, ConstructibleStringType>::value >> { static constexpr auto value = is_constructible<ConstructibleStringType, typename BasicJsonType::string_t>::value; }; template<typename BasicJsonType, typename ConstructibleStringType> struct is_constructible_string_type : is_constructible_string_type_impl<BasicJsonType, ConstructibleStringType> {}; template<typename BasicJsonType, typename CompatibleArrayType, typename = void> struct is_compatible_array_type_impl : std::false_type {}; template<typename BasicJsonType, typename CompatibleArrayType> struct is_compatible_array_type_impl < BasicJsonType, CompatibleArrayType, enable_if_t < is_detected<value_type_t, CompatibleArrayType>::value&& is_detected<iterator_t, CompatibleArrayType>::value&& // This is needed because json_reverse_iterator has a ::iterator type... // Therefore it is detected as a CompatibleArrayType. // The real fix would be to have an Iterable concept. !is_iterator_traits < iterator_traits<CompatibleArrayType >>::value >> { static constexpr bool value = is_constructible<BasicJsonType, typename CompatibleArrayType::value_type>::value; }; template<typename BasicJsonType, typename CompatibleArrayType> struct is_compatible_array_type : is_compatible_array_type_impl<BasicJsonType, CompatibleArrayType> {}; template<typename BasicJsonType, typename ConstructibleArrayType, typename = void> struct is_constructible_array_type_impl : std::false_type {}; template<typename BasicJsonType, typename ConstructibleArrayType> struct is_constructible_array_type_impl < BasicJsonType, ConstructibleArrayType, enable_if_t<std::is_same<ConstructibleArrayType, typename BasicJsonType::value_type>::value >> : std::true_type {}; template<typename BasicJsonType, typename ConstructibleArrayType> struct is_constructible_array_type_impl < BasicJsonType, ConstructibleArrayType, enable_if_t < !std::is_same<ConstructibleArrayType, typename BasicJsonType::value_type>::value&& is_default_constructible<ConstructibleArrayType>::value&& (std::is_move_assignable<ConstructibleArrayType>::value || std::is_copy_assignable<ConstructibleArrayType>::value)&& is_detected<value_type_t, ConstructibleArrayType>::value&& is_detected<iterator_t, ConstructibleArrayType>::value&& is_complete_type < detected_t<value_type_t, ConstructibleArrayType >>::value >> { static constexpr bool value = // This is needed because json_reverse_iterator has a ::iterator type, // furthermore, std::back_insert_iterator (and other iterators) have a // base class `iterator`... Therefore it is detected as a // ConstructibleArrayType. The real fix would be to have an Iterable // concept. !is_iterator_traits<iterator_traits<ConstructibleArrayType>>::value && (std::is_same<typename ConstructibleArrayType::value_type, typename BasicJsonType::array_t::value_type>::value || has_from_json<BasicJsonType, typename ConstructibleArrayType::value_type>::value || has_non_default_from_json < BasicJsonType, typename ConstructibleArrayType::value_type >::value); }; template<typename BasicJsonType, typename ConstructibleArrayType> struct is_constructible_array_type : is_constructible_array_type_impl<BasicJsonType, ConstructibleArrayType> {}; template<typename RealIntegerType, typename CompatibleNumberIntegerType, typename = void> struct is_compatible_integer_type_impl : std::false_type {}; template<typename RealIntegerType, typename CompatibleNumberIntegerType> struct is_compatible_integer_type_impl < RealIntegerType, CompatibleNumberIntegerType, enable_if_t < std::is_integral<RealIntegerType>::value&& std::is_integral<CompatibleNumberIntegerType>::value&& !std::is_same<bool, CompatibleNumberIntegerType>::value >> { // is there an assert somewhere on overflows? using RealLimits = std::numeric_limits<RealIntegerType>; using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>; static constexpr auto value = is_constructible<RealIntegerType, CompatibleNumberIntegerType>::value && CompatibleLimits::is_integer && RealLimits::is_signed == CompatibleLimits::is_signed; }; template<typename RealIntegerType, typename CompatibleNumberIntegerType> struct is_compatible_integer_type : is_compatible_integer_type_impl<RealIntegerType, CompatibleNumberIntegerType> {}; template<typename BasicJsonType, typename CompatibleType, typename = void> struct is_compatible_type_impl: std::false_type {}; template<typename BasicJsonType, typename CompatibleType> struct is_compatible_type_impl < BasicJsonType, CompatibleType, enable_if_t<is_complete_type<CompatibleType>::value >> { static constexpr bool value = has_to_json<BasicJsonType, CompatibleType>::value; }; template<typename BasicJsonType, typename CompatibleType> struct is_compatible_type : is_compatible_type_impl<BasicJsonType, CompatibleType> {}; template<typename T1, typename T2> struct is_constructible_tuple : std::false_type {}; template<typename T1, typename... Args> struct is_constructible_tuple<T1, std::tuple<Args...>> : conjunction<is_constructible<T1, Args>...> {}; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/value_t.hpp> namespace nlohmann { namespace detail { template<typename BasicJsonType> void from_json(const BasicJsonType& j, typename std::nullptr_t& n) { if (JSON_HEDLEY_UNLIKELY(!j.is_null())) { JSON_THROW(type_error::create(302, "type must be null, but is " + std::string(j.type_name()), j)); } n = nullptr; } // overloads for basic_json template parameters template < typename BasicJsonType, typename ArithmeticType, enable_if_t < std::is_arithmetic<ArithmeticType>::value&& !std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value, int > = 0 > void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val) { switch (static_cast<value_t>(j)) { case value_t::number_unsigned: { val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>()); break; } case value_t::number_integer: { val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>()); break; } case value_t::number_float: { val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>()); break; } default: JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()), j)); } } template<typename BasicJsonType> void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b) { if (JSON_HEDLEY_UNLIKELY(!j.is_boolean())) { JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name()), j)); } b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>(); } template<typename BasicJsonType> void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s) { if (JSON_HEDLEY_UNLIKELY(!j.is_string())) { JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()), j)); } s = *j.template get_ptr<const typename BasicJsonType::string_t*>(); } template < typename BasicJsonType, typename ConstructibleStringType, enable_if_t < is_constructible_string_type<BasicJsonType, ConstructibleStringType>::value&& !std::is_same<typename BasicJsonType::string_t, ConstructibleStringType>::value, int > = 0 > void from_json(const BasicJsonType& j, ConstructibleStringType& s) { if (JSON_HEDLEY_UNLIKELY(!j.is_string())) { JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()), j)); } s = *j.template get_ptr<const typename BasicJsonType::string_t*>(); } template<typename BasicJsonType> void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val) { get_arithmetic_value(j, val); } template<typename BasicJsonType> void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val) { get_arithmetic_value(j, val); } template<typename BasicJsonType> void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val) { get_arithmetic_value(j, val); } template<typename BasicJsonType, typename EnumType, enable_if_t<std::is_enum<EnumType>::value, int> = 0> void from_json(const BasicJsonType& j, EnumType& e) { typename std::underlying_type<EnumType>::type val; get_arithmetic_value(j, val); e = static_cast<EnumType>(val); } // forward_list doesn't have an insert method template<typename BasicJsonType, typename T, typename Allocator, enable_if_t<is_getable<BasicJsonType, T>::value, int> = 0> void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l) { if (JSON_HEDLEY_UNLIKELY(!j.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); } l.clear(); std::transform(j.rbegin(), j.rend(), std::front_inserter(l), [](const BasicJsonType & i) { return i.template get<T>(); }); } // valarray doesn't have an insert method template<typename BasicJsonType, typename T, enable_if_t<is_getable<BasicJsonType, T>::value, int> = 0> void from_json(const BasicJsonType& j, std::valarray<T>& l) { if (JSON_HEDLEY_UNLIKELY(!j.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); } l.resize(j.size()); std::transform(j.begin(), j.end(), std::begin(l), [](const BasicJsonType & elem) { return elem.template get<T>(); }); } template<typename BasicJsonType, typename T, std::size_t N> auto from_json(const BasicJsonType& j, T (&arr)[N]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) -> decltype(j.template get<T>(), void()) { for (std::size_t i = 0; i < N; ++i) { arr[i] = j.at(i).template get<T>(); } } template<typename BasicJsonType> void from_json_array_impl(const BasicJsonType& j, typename BasicJsonType::array_t& arr, priority_tag<3> /*unused*/) { arr = *j.template get_ptr<const typename BasicJsonType::array_t*>(); } template<typename BasicJsonType, typename T, std::size_t N> auto from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr, priority_tag<2> /*unused*/) -> decltype(j.template get<T>(), void()) { for (std::size_t i = 0; i < N; ++i) { arr[i] = j.at(i).template get<T>(); } } template<typename BasicJsonType, typename ConstructibleArrayType, enable_if_t< std::is_assignable<ConstructibleArrayType&, ConstructibleArrayType>::value, int> = 0> auto from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<1> /*unused*/) -> decltype( arr.reserve(std::declval<typename ConstructibleArrayType::size_type>()), j.template get<typename ConstructibleArrayType::value_type>(), void()) { using std::end; ConstructibleArrayType ret; ret.reserve(j.size()); std::transform(j.begin(), j.end(), std::inserter(ret, end(ret)), [](const BasicJsonType & i) { // get<BasicJsonType>() returns *this, this won't call a from_json // method when value_type is BasicJsonType return i.template get<typename ConstructibleArrayType::value_type>(); }); arr = std::move(ret); } template<typename BasicJsonType, typename ConstructibleArrayType, enable_if_t< std::is_assignable<ConstructibleArrayType&, ConstructibleArrayType>::value, int> = 0> void from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<0> /*unused*/) { using std::end; ConstructibleArrayType ret; std::transform( j.begin(), j.end(), std::inserter(ret, end(ret)), [](const BasicJsonType & i) { // get<BasicJsonType>() returns *this, this won't call a from_json // method when value_type is BasicJsonType return i.template get<typename ConstructibleArrayType::value_type>(); }); arr = std::move(ret); } template < typename BasicJsonType, typename ConstructibleArrayType, enable_if_t < is_constructible_array_type<BasicJsonType, ConstructibleArrayType>::value&& !is_constructible_object_type<BasicJsonType, ConstructibleArrayType>::value&& !is_constructible_string_type<BasicJsonType, ConstructibleArrayType>::value&& !std::is_same<ConstructibleArrayType, typename BasicJsonType::binary_t>::value&& !is_basic_json<ConstructibleArrayType>::value, int > = 0 > auto from_json(const BasicJsonType& j, ConstructibleArrayType& arr) -> decltype(from_json_array_impl(j, arr, priority_tag<3> {}), j.template get<typename ConstructibleArrayType::value_type>(), void()) { if (JSON_HEDLEY_UNLIKELY(!j.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); } from_json_array_impl(j, arr, priority_tag<3> {}); } template < typename BasicJsonType, typename T, std::size_t... Idx > std::array<T, sizeof...(Idx)> from_json_inplace_array_impl(BasicJsonType&& j, identity_tag<std::array<T, sizeof...(Idx)>> /*unused*/, index_sequence<Idx...> /*unused*/) { return { { std::forward<BasicJsonType>(j).at(Idx).template get<T>()... } }; } template < typename BasicJsonType, typename T, std::size_t N > auto from_json(BasicJsonType&& j, identity_tag<std::array<T, N>> tag) -> decltype(from_json_inplace_array_impl(std::forward<BasicJsonType>(j), tag, make_index_sequence<N> {})) { if (JSON_HEDLEY_UNLIKELY(!j.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); } return from_json_inplace_array_impl(std::forward<BasicJsonType>(j), tag, make_index_sequence<N> {}); } template<typename BasicJsonType> void from_json(const BasicJsonType& j, typename BasicJsonType::binary_t& bin) { if (JSON_HEDLEY_UNLIKELY(!j.is_binary())) { JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(j.type_name()), j)); } bin = *j.template get_ptr<const typename BasicJsonType::binary_t*>(); } template<typename BasicJsonType, typename ConstructibleObjectType, enable_if_t<is_constructible_object_type<BasicJsonType, ConstructibleObjectType>::value, int> = 0> void from_json(const BasicJsonType& j, ConstructibleObjectType& obj) { if (JSON_HEDLEY_UNLIKELY(!j.is_object())) { JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name()), j)); } ConstructibleObjectType ret; const auto* inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>(); using value_type = typename ConstructibleObjectType::value_type; std::transform( inner_object->begin(), inner_object->end(), std::inserter(ret, ret.begin()), [](typename BasicJsonType::object_t::value_type const & p) { return value_type(p.first, p.second.template get<typename ConstructibleObjectType::mapped_type>()); }); obj = std::move(ret); } // overload for arithmetic types, not chosen for basic_json template arguments // (BooleanType, etc..); note: Is it really necessary to provide explicit // overloads for boolean_t etc. in case of a custom BooleanType which is not // an arithmetic type? template < typename BasicJsonType, typename ArithmeticType, enable_if_t < std::is_arithmetic<ArithmeticType>::value&& !std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value&& !std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value&& !std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value&& !std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value, int > = 0 > void from_json(const BasicJsonType& j, ArithmeticType& val) { switch (static_cast<value_t>(j)) { case value_t::number_unsigned: { val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>()); break; } case value_t::number_integer: { val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>()); break; } case value_t::number_float: { val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>()); break; } case value_t::boolean: { val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>()); break; } default: JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()), j)); } } template<typename BasicJsonType, typename... Args, std::size_t... Idx> std::tuple<Args...> from_json_tuple_impl_base(BasicJsonType&& j, index_sequence<Idx...> /*unused*/) { return std::make_tuple(std::forward<BasicJsonType>(j).at(Idx).template get<Args>()...); } template < typename BasicJsonType, class A1, class A2 > std::pair<A1, A2> from_json_tuple_impl(BasicJsonType&& j, identity_tag<std::pair<A1, A2>> /*unused*/, priority_tag<0> /*unused*/) { return {std::forward<BasicJsonType>(j).at(0).template get<A1>(), std::forward<BasicJsonType>(j).at(1).template get<A2>()}; } template<typename BasicJsonType, typename A1, typename A2> void from_json_tuple_impl(BasicJsonType&& j, std::pair<A1, A2>& p, priority_tag<1> /*unused*/) { p = from_json_tuple_impl(std::forward<BasicJsonType>(j), identity_tag<std::pair<A1, A2>> {}, priority_tag<0> {}); } template<typename BasicJsonType, typename... Args> std::tuple<Args...> from_json_tuple_impl(BasicJsonType&& j, identity_tag<std::tuple<Args...>> /*unused*/, priority_tag<2> /*unused*/) { return from_json_tuple_impl_base<BasicJsonType, Args...>(std::forward<BasicJsonType>(j), index_sequence_for<Args...> {}); } template<typename BasicJsonType, typename... Args> void from_json_tuple_impl(BasicJsonType&& j, std::tuple<Args...>& t, priority_tag<3> /*unused*/) { t = from_json_tuple_impl_base<BasicJsonType, Args...>(std::forward<BasicJsonType>(j), index_sequence_for<Args...> {}); } template<typename BasicJsonType, typename TupleRelated> auto from_json(BasicJsonType&& j, TupleRelated&& t) -> decltype(from_json_tuple_impl(std::forward<BasicJsonType>(j), std::forward<TupleRelated>(t), priority_tag<3> {})) { if (JSON_HEDLEY_UNLIKELY(!j.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); } return from_json_tuple_impl(std::forward<BasicJsonType>(j), std::forward<TupleRelated>(t), priority_tag<3> {}); } template < typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator, typename = enable_if_t < !std::is_constructible < typename BasicJsonType::string_t, Key >::value >> void from_json(const BasicJsonType& j, std::map<Key, Value, Compare, Allocator>& m) { if (JSON_HEDLEY_UNLIKELY(!j.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); } m.clear(); for (const auto& p : j) { if (JSON_HEDLEY_UNLIKELY(!p.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name()), j)); } m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>()); } } template < typename BasicJsonType, typename Key, typename Value, typename Hash, typename KeyEqual, typename Allocator, typename = enable_if_t < !std::is_constructible < typename BasicJsonType::string_t, Key >::value >> void from_json(const BasicJsonType& j, std::unordered_map<Key, Value, Hash, KeyEqual, Allocator>& m) { if (JSON_HEDLEY_UNLIKELY(!j.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); } m.clear(); for (const auto& p : j) { if (JSON_HEDLEY_UNLIKELY(!p.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name()), j)); } m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>()); } } struct from_json_fn { template<typename BasicJsonType, typename T> auto operator()(const BasicJsonType& j, T&& val) const noexcept(noexcept(from_json(j, std::forward<T>(val)))) -> decltype(from_json(j, std::forward<T>(val))) { return from_json(j, std::forward<T>(val)); } }; } // namespace detail /// namespace to hold default `from_json` function /// to see why this is required: /// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html namespace // NOLINT(cert-dcl59-cpp,fuchsia-header-anon-namespaces,google-build-namespaces) { constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value; // NOLINT(misc-definitions-in-headers) } // namespace } // namespace nlohmann // #include <nlohmann/detail/conversions/to_json.hpp> #include <algorithm> // copy #include <iterator> // begin, end #include <string> // string #include <tuple> // tuple, get #include <type_traits> // is_same, is_constructible, is_floating_point, is_enum, underlying_type #include <utility> // move, forward, declval, pair #include <valarray> // valarray #include <vector> // vector // #include <nlohmann/detail/iterators/iteration_proxy.hpp> #include <cstddef> // size_t #include <iterator> // input_iterator_tag #include <string> // string, to_string #include <tuple> // tuple_size, get, tuple_element #include <utility> // move // #include <nlohmann/detail/meta/type_traits.hpp> // #include <nlohmann/detail/value_t.hpp> namespace nlohmann { namespace detail { template<typename string_type> void int_to_string( string_type& target, std::size_t value ) { // For ADL using std::to_string; target = to_string(value); } template<typename IteratorType> class iteration_proxy_value { public: using difference_type = std::ptrdiff_t; using value_type = iteration_proxy_value; using pointer = value_type * ; using reference = value_type & ; using iterator_category = std::input_iterator_tag; using string_type = typename std::remove_cv< typename std::remove_reference<decltype( std::declval<IteratorType>().key() ) >::type >::type; private: /// the iterator IteratorType anchor; /// an index for arrays (used to create key names) std::size_t array_index = 0; /// last stringified array index mutable std::size_t array_index_last = 0; /// a string representation of the array index mutable string_type array_index_str = "0"; /// an empty string (to return a reference for primitive values) const string_type empty_str{}; public: explicit iteration_proxy_value(IteratorType it) noexcept : anchor(std::move(it)) {} /// dereference operator (needed for range-based for) iteration_proxy_value& operator*() { return *this; } /// increment operator (needed for range-based for) iteration_proxy_value& operator++() { ++anchor; ++array_index; return *this; } /// equality operator (needed for InputIterator) bool operator==(const iteration_proxy_value& o) const { return anchor == o.anchor; } /// inequality operator (needed for range-based for) bool operator!=(const iteration_proxy_value& o) const { return anchor != o.anchor; } /// return key of the iterator const string_type& key() const { JSON_ASSERT(anchor.m_object != nullptr); switch (anchor.m_object->type()) { // use integer array index as key case value_t::array: { if (array_index != array_index_last) { int_to_string( array_index_str, array_index ); array_index_last = array_index; } return array_index_str; } // use key from the object case value_t::object: return anchor.key(); // use an empty key for all primitive types default: return empty_str; } } /// return value of the iterator typename IteratorType::reference value() const { return anchor.value(); } }; /// proxy class for the items() function template<typename IteratorType> class iteration_proxy { private: /// the container to iterate typename IteratorType::reference container; public: /// construct iteration proxy from a container explicit iteration_proxy(typename IteratorType::reference cont) noexcept : container(cont) {} /// return iterator begin (needed for range-based for) iteration_proxy_value<IteratorType> begin() noexcept { return iteration_proxy_value<IteratorType>(container.begin()); } /// return iterator end (needed for range-based for) iteration_proxy_value<IteratorType> end() noexcept { return iteration_proxy_value<IteratorType>(container.end()); } }; // Structured Bindings Support // For further reference see https://blog.tartanllama.xyz/structured-bindings/ // And see https://github.com/nlohmann/json/pull/1391 template<std::size_t N, typename IteratorType, enable_if_t<N == 0, int> = 0> auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.key()) { return i.key(); } // Structured Bindings Support // For further reference see https://blog.tartanllama.xyz/structured-bindings/ // And see https://github.com/nlohmann/json/pull/1391 template<std::size_t N, typename IteratorType, enable_if_t<N == 1, int> = 0> auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.value()) { return i.value(); } } // namespace detail } // namespace nlohmann // The Addition to the STD Namespace is required to add // Structured Bindings Support to the iteration_proxy_value class // For further reference see https://blog.tartanllama.xyz/structured-bindings/ // And see https://github.com/nlohmann/json/pull/1391 namespace std { #if defined(__clang__) // Fix: https://github.com/nlohmann/json/issues/1401 #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wmismatched-tags" #endif template<typename IteratorType> class tuple_size<::nlohmann::detail::iteration_proxy_value<IteratorType>> : public std::integral_constant<std::size_t, 2> {}; template<std::size_t N, typename IteratorType> class tuple_element<N, ::nlohmann::detail::iteration_proxy_value<IteratorType >> { public: using type = decltype( get<N>(std::declval < ::nlohmann::detail::iteration_proxy_value<IteratorType >> ())); }; #if defined(__clang__) #pragma clang diagnostic pop #endif } // namespace std // #include <nlohmann/detail/meta/cpp_future.hpp> // #include <nlohmann/detail/meta/type_traits.hpp> // #include <nlohmann/detail/value_t.hpp> namespace nlohmann { namespace detail { ////////////////// // constructors // ////////////////// /* * Note all external_constructor<>::construct functions need to call * j.m_value.destroy(j.m_type) to avoid a memory leak in case j contains an * allocated value (e.g., a string). See bug issue * https://github.com/nlohmann/json/issues/2865 for more information. */ template<value_t> struct external_constructor; template<> struct external_constructor<value_t::boolean> { template<typename BasicJsonType> static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept { j.m_value.destroy(j.m_type); j.m_type = value_t::boolean; j.m_value = b; j.assert_invariant(); } }; template<> struct external_constructor<value_t::string> { template<typename BasicJsonType> static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s) { j.m_value.destroy(j.m_type); j.m_type = value_t::string; j.m_value = s; j.assert_invariant(); } template<typename BasicJsonType> static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s) { j.m_value.destroy(j.m_type); j.m_type = value_t::string; j.m_value = std::move(s); j.assert_invariant(); } template < typename BasicJsonType, typename CompatibleStringType, enable_if_t < !std::is_same<CompatibleStringType, typename BasicJsonType::string_t>::value, int > = 0 > static void construct(BasicJsonType& j, const CompatibleStringType& str) { j.m_value.destroy(j.m_type); j.m_type = value_t::string; j.m_value.string = j.template create<typename BasicJsonType::string_t>(str); j.assert_invariant(); } }; template<> struct external_constructor<value_t::binary> { template<typename BasicJsonType> static void construct(BasicJsonType& j, const typename BasicJsonType::binary_t& b) { j.m_value.destroy(j.m_type); j.m_type = value_t::binary; j.m_value = typename BasicJsonType::binary_t(b); j.assert_invariant(); } template<typename BasicJsonType> static void construct(BasicJsonType& j, typename BasicJsonType::binary_t&& b) { j.m_value.destroy(j.m_type); j.m_type = value_t::binary; j.m_value = typename BasicJsonType::binary_t(std::move(b));; j.assert_invariant(); } }; template<> struct external_constructor<value_t::number_float> { template<typename BasicJsonType> static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept { j.m_value.destroy(j.m_type); j.m_type = value_t::number_float; j.m_value = val; j.assert_invariant(); } }; template<> struct external_constructor<value_t::number_unsigned> { template<typename BasicJsonType> static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept { j.m_value.destroy(j.m_type); j.m_type = value_t::number_unsigned; j.m_value = val; j.assert_invariant(); } }; template<> struct external_constructor<value_t::number_integer> { template<typename BasicJsonType> static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept { j.m_value.destroy(j.m_type); j.m_type = value_t::number_integer; j.m_value = val; j.assert_invariant(); } }; template<> struct external_constructor<value_t::array> { template<typename BasicJsonType> static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr) { j.m_value.destroy(j.m_type); j.m_type = value_t::array; j.m_value = arr; j.set_parents(); j.assert_invariant(); } template<typename BasicJsonType> static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr) { j.m_value.destroy(j.m_type); j.m_type = value_t::array; j.m_value = std::move(arr); j.set_parents(); j.assert_invariant(); } template < typename BasicJsonType, typename CompatibleArrayType, enable_if_t < !std::is_same<CompatibleArrayType, typename BasicJsonType::array_t>::value, int > = 0 > static void construct(BasicJsonType& j, const CompatibleArrayType& arr) { using std::begin; using std::end; j.m_value.destroy(j.m_type); j.m_type = value_t::array; j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr)); j.set_parents(); j.assert_invariant(); } template<typename BasicJsonType> static void construct(BasicJsonType& j, const std::vector<bool>& arr) { j.m_value.destroy(j.m_type); j.m_type = value_t::array; j.m_value = value_t::array; j.m_value.array->reserve(arr.size()); for (const bool x : arr) { j.m_value.array->push_back(x); j.set_parent(j.m_value.array->back()); } j.assert_invariant(); } template<typename BasicJsonType, typename T, enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0> static void construct(BasicJsonType& j, const std::valarray<T>& arr) { j.m_value.destroy(j.m_type); j.m_type = value_t::array; j.m_value = value_t::array; j.m_value.array->resize(arr.size()); if (arr.size() > 0) { std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin()); } j.set_parents(); j.assert_invariant(); } }; template<> struct external_constructor<value_t::object> { template<typename BasicJsonType> static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj) { j.m_value.destroy(j.m_type); j.m_type = value_t::object; j.m_value = obj; j.set_parents(); j.assert_invariant(); } template<typename BasicJsonType> static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj) { j.m_value.destroy(j.m_type); j.m_type = value_t::object; j.m_value = std::move(obj); j.set_parents(); j.assert_invariant(); } template < typename BasicJsonType, typename CompatibleObjectType, enable_if_t < !std::is_same<CompatibleObjectType, typename BasicJsonType::object_t>::value, int > = 0 > static void construct(BasicJsonType& j, const CompatibleObjectType& obj) { using std::begin; using std::end; j.m_value.destroy(j.m_type); j.m_type = value_t::object; j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj)); j.set_parents(); j.assert_invariant(); } }; ///////////// // to_json // ///////////// template<typename BasicJsonType, typename T, enable_if_t<std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0> void to_json(BasicJsonType& j, T b) noexcept { external_constructor<value_t::boolean>::construct(j, b); } template<typename BasicJsonType, typename CompatibleString, enable_if_t<std::is_constructible<typename BasicJsonType::string_t, CompatibleString>::value, int> = 0> void to_json(BasicJsonType& j, const CompatibleString& s) { external_constructor<value_t::string>::construct(j, s); } template<typename BasicJsonType> void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s) { external_constructor<value_t::string>::construct(j, std::move(s)); } template<typename BasicJsonType, typename FloatType, enable_if_t<std::is_floating_point<FloatType>::value, int> = 0> void to_json(BasicJsonType& j, FloatType val) noexcept { external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val)); } template<typename BasicJsonType, typename CompatibleNumberUnsignedType, enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t, CompatibleNumberUnsignedType>::value, int> = 0> void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept { external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val)); } template<typename BasicJsonType, typename CompatibleNumberIntegerType, enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t, CompatibleNumberIntegerType>::value, int> = 0> void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept { external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val)); } template<typename BasicJsonType, typename EnumType, enable_if_t<std::is_enum<EnumType>::value, int> = 0> void to_json(BasicJsonType& j, EnumType e) noexcept { using underlying_type = typename std::underlying_type<EnumType>::type; external_constructor<value_t::number_integer>::construct(j, static_cast<underlying_type>(e)); } template<typename BasicJsonType> void to_json(BasicJsonType& j, const std::vector<bool>& e) { external_constructor<value_t::array>::construct(j, e); } template < typename BasicJsonType, typename CompatibleArrayType, enable_if_t < is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value&& !is_compatible_object_type<BasicJsonType, CompatibleArrayType>::value&& !is_compatible_string_type<BasicJsonType, CompatibleArrayType>::value&& !std::is_same<typename BasicJsonType::binary_t, CompatibleArrayType>::value&& !is_basic_json<CompatibleArrayType>::value, int > = 0 > void to_json(BasicJsonType& j, const CompatibleArrayType& arr) { external_constructor<value_t::array>::construct(j, arr); } template<typename BasicJsonType> void to_json(BasicJsonType& j, const typename BasicJsonType::binary_t& bin) { external_constructor<value_t::binary>::construct(j, bin); } template<typename BasicJsonType, typename T, enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0> void to_json(BasicJsonType& j, const std::valarray<T>& arr) { external_constructor<value_t::array>::construct(j, std::move(arr)); } template<typename BasicJsonType> void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr) { external_constructor<value_t::array>::construct(j, std::move(arr)); } template < typename BasicJsonType, typename CompatibleObjectType, enable_if_t < is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value&& !is_basic_json<CompatibleObjectType>::value, int > = 0 > void to_json(BasicJsonType& j, const CompatibleObjectType& obj) { external_constructor<value_t::object>::construct(j, obj); } template<typename BasicJsonType> void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj) { external_constructor<value_t::object>::construct(j, std::move(obj)); } template < typename BasicJsonType, typename T, std::size_t N, enable_if_t < !std::is_constructible<typename BasicJsonType::string_t, const T(&)[N]>::value, // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) int > = 0 > void to_json(BasicJsonType& j, const T(&arr)[N]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) { external_constructor<value_t::array>::construct(j, arr); } template < typename BasicJsonType, typename T1, typename T2, enable_if_t < std::is_constructible<BasicJsonType, T1>::value&& std::is_constructible<BasicJsonType, T2>::value, int > = 0 > void to_json(BasicJsonType& j, const std::pair<T1, T2>& p) { j = { p.first, p.second }; } // for https://github.com/nlohmann/json/pull/1134 template<typename BasicJsonType, typename T, enable_if_t<std::is_same<T, iteration_proxy_value<typename BasicJsonType::iterator>>::value, int> = 0> void to_json(BasicJsonType& j, const T& b) { j = { {b.key(), b.value()} }; } template<typename BasicJsonType, typename Tuple, std::size_t... Idx> void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence<Idx...> /*unused*/) { j = { std::get<Idx>(t)... }; } template<typename BasicJsonType, typename T, enable_if_t<is_constructible_tuple<BasicJsonType, T>::value, int > = 0> void to_json(BasicJsonType& j, const T& t) { to_json_tuple_impl(j, t, make_index_sequence<std::tuple_size<T>::value> {}); } struct to_json_fn { template<typename BasicJsonType, typename T> auto operator()(BasicJsonType& j, T&& val) const noexcept(noexcept(to_json(j, std::forward<T>(val)))) -> decltype(to_json(j, std::forward<T>(val)), void()) { return to_json(j, std::forward<T>(val)); } }; } // namespace detail /// namespace to hold default `to_json` function /// to see why this is required: /// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html namespace // NOLINT(cert-dcl59-cpp,fuchsia-header-anon-namespaces,google-build-namespaces) { constexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value; // NOLINT(misc-definitions-in-headers) } // namespace } // namespace nlohmann // #include <nlohmann/detail/meta/identity_tag.hpp> // #include <nlohmann/detail/meta/type_traits.hpp> namespace nlohmann { template<typename ValueType, typename> struct adl_serializer { /*! @brief convert a JSON value to any value type This function is usually called by the `get()` function of the @ref basic_json class (either explicit or via conversion operators). @note This function is chosen for default-constructible value types. @param[in] j JSON value to read from @param[in,out] val value to write to */ template<typename BasicJsonType, typename TargetType = ValueType> static auto from_json(BasicJsonType && j, TargetType& val) noexcept( noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val))) -> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), val), void()) { ::nlohmann::from_json(std::forward<BasicJsonType>(j), val); } /*! @brief convert a JSON value to any value type This function is usually called by the `get()` function of the @ref basic_json class (either explicit or via conversion operators). @note This function is chosen for value types which are not default-constructible. @param[in] j JSON value to read from @return copy of the JSON value, converted to @a ValueType */ template<typename BasicJsonType, typename TargetType = ValueType> static auto from_json(BasicJsonType && j) noexcept( noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType> {}))) -> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType> {})) { return ::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType> {}); } /*! @brief convert any value type to a JSON value This function is usually called by the constructors of the @ref basic_json class. @param[in,out] j JSON value to write to @param[in] val value to read from */ template<typename BasicJsonType, typename TargetType = ValueType> static auto to_json(BasicJsonType& j, TargetType && val) noexcept( noexcept(::nlohmann::to_json(j, std::forward<TargetType>(val)))) -> decltype(::nlohmann::to_json(j, std::forward<TargetType>(val)), void()) { ::nlohmann::to_json(j, std::forward<TargetType>(val)); } }; } // namespace nlohmann // #include <nlohmann/byte_container_with_subtype.hpp> #include <cstdint> // uint8_t #include <tuple> // tie #include <utility> // move namespace nlohmann { /*! @brief an internal type for a backed binary type This type extends the template parameter @a BinaryType provided to `basic_json` with a subtype used by BSON and MessagePack. This type exists so that the user does not have to specify a type themselves with a specific naming scheme in order to override the binary type. @tparam BinaryType container to store bytes (`std::vector<std::uint8_t>` by default) @since version 3.8.0 */ template<typename BinaryType> class byte_container_with_subtype : public BinaryType { public: /// the type of the underlying container using container_type = BinaryType; byte_container_with_subtype() noexcept(noexcept(container_type())) : container_type() {} byte_container_with_subtype(const container_type& b) noexcept(noexcept(container_type(b))) : container_type(b) {} byte_container_with_subtype(container_type&& b) noexcept(noexcept(container_type(std::move(b)))) : container_type(std::move(b)) {} byte_container_with_subtype(const container_type& b, std::uint8_t subtype_) noexcept(noexcept(container_type(b))) : container_type(b) , m_subtype(subtype_) , m_has_subtype(true) {} byte_container_with_subtype(container_type&& b, std::uint8_t subtype_) noexcept(noexcept(container_type(std::move(b)))) : container_type(std::move(b)) , m_subtype(subtype_) , m_has_subtype(true) {} bool operator==(const byte_container_with_subtype& rhs) const { return std::tie(static_cast<const BinaryType&>(*this), m_subtype, m_has_subtype) == std::tie(static_cast<const BinaryType&>(rhs), rhs.m_subtype, rhs.m_has_subtype); } bool operator!=(const byte_container_with_subtype& rhs) const { return !(rhs == *this); } /*! @brief sets the binary subtype Sets the binary subtype of the value, also flags a binary JSON value as having a subtype, which has implications for serialization. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @sa see @ref subtype() -- return the binary subtype @sa see @ref clear_subtype() -- clears the binary subtype @sa see @ref has_subtype() -- returns whether or not the binary value has a subtype @since version 3.8.0 */ void set_subtype(std::uint8_t subtype_) noexcept { m_subtype = subtype_; m_has_subtype = true; } /*! @brief return the binary subtype Returns the numerical subtype of the value if it has a subtype. If it does not have a subtype, this function will return size_t(-1) as a sentinel value. @return the numerical subtype of the binary value @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @sa see @ref set_subtype() -- sets the binary subtype @sa see @ref clear_subtype() -- clears the binary subtype @sa see @ref has_subtype() -- returns whether or not the binary value has a subtype @since version 3.8.0 */ constexpr std::uint8_t subtype() const noexcept { return m_subtype; } /*! @brief return whether the value has a subtype @return whether the value has a subtype @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @sa see @ref subtype() -- return the binary subtype @sa see @ref set_subtype() -- sets the binary subtype @sa see @ref clear_subtype() -- clears the binary subtype @since version 3.8.0 */ constexpr bool has_subtype() const noexcept { return m_has_subtype; } /*! @brief clears the binary subtype Clears the binary subtype and flags the value as not having a subtype, which has implications for serialization; for instance MessagePack will prefer the bin family over the ext family. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @sa see @ref subtype() -- return the binary subtype @sa see @ref set_subtype() -- sets the binary subtype @sa see @ref has_subtype() -- returns whether or not the binary value has a subtype @since version 3.8.0 */ void clear_subtype() noexcept { m_subtype = 0; m_has_subtype = false; } private: std::uint8_t m_subtype = 0; bool m_has_subtype = false; }; } // namespace nlohmann // #include <nlohmann/detail/conversions/from_json.hpp> // #include <nlohmann/detail/conversions/to_json.hpp> // #include <nlohmann/detail/exceptions.hpp> // #include <nlohmann/detail/hash.hpp> #include <cstdint> // uint8_t #include <cstddef> // size_t #include <functional> // hash // #include <nlohmann/detail/macro_scope.hpp> namespace nlohmann { namespace detail { // boost::hash_combine inline std::size_t combine(std::size_t seed, std::size_t h) noexcept { seed ^= h + 0x9e3779b9 + (seed << 6U) + (seed >> 2U); return seed; } /*! @brief hash a JSON value The hash function tries to rely on std::hash where possible. Furthermore, the type of the JSON value is taken into account to have different hash values for null, 0, 0U, and false, etc. @tparam BasicJsonType basic_json specialization @param j JSON value to hash @return hash value of j */ template<typename BasicJsonType> std::size_t hash(const BasicJsonType& j) { using string_t = typename BasicJsonType::string_t; using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; const auto type = static_cast<std::size_t>(j.type()); switch (j.type()) { case BasicJsonType::value_t::null: case BasicJsonType::value_t::discarded: { return combine(type, 0); } case BasicJsonType::value_t::object: { auto seed = combine(type, j.size()); for (const auto& element : j.items()) { const auto h = std::hash<string_t> {}(element.key()); seed = combine(seed, h); seed = combine(seed, hash(element.value())); } return seed; } case BasicJsonType::value_t::array: { auto seed = combine(type, j.size()); for (const auto& element : j) { seed = combine(seed, hash(element)); } return seed; } case BasicJsonType::value_t::string: { const auto h = std::hash<string_t> {}(j.template get_ref<const string_t&>()); return combine(type, h); } case BasicJsonType::value_t::boolean: { const auto h = std::hash<bool> {}(j.template get<bool>()); return combine(type, h); } case BasicJsonType::value_t::number_integer: { const auto h = std::hash<number_integer_t> {}(j.template get<number_integer_t>()); return combine(type, h); } case BasicJsonType::value_t::number_unsigned: { const auto h = std::hash<number_unsigned_t> {}(j.template get<number_unsigned_t>()); return combine(type, h); } case BasicJsonType::value_t::number_float: { const auto h = std::hash<number_float_t> {}(j.template get<number_float_t>()); return combine(type, h); } case BasicJsonType::value_t::binary: { auto seed = combine(type, j.get_binary().size()); const auto h = std::hash<bool> {}(j.get_binary().has_subtype()); seed = combine(seed, h); seed = combine(seed, j.get_binary().subtype()); for (const auto byte : j.get_binary()) { seed = combine(seed, std::hash<std::uint8_t> {}(byte)); } return seed; } default: // LCOV_EXCL_LINE JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE return 0; // LCOV_EXCL_LINE } } } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/input/binary_reader.hpp> #include <algorithm> // generate_n #include <array> // array #include <cmath> // ldexp #include <cstddef> // size_t #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t #include <cstdio> // snprintf #include <cstring> // memcpy #include <iterator> // back_inserter #include <limits> // numeric_limits #include <string> // char_traits, string #include <utility> // make_pair, move #include <vector> // vector // #include <nlohmann/detail/exceptions.hpp> // #include <nlohmann/detail/input/input_adapters.hpp> #include <array> // array #include <cstddef> // size_t #include <cstring> // strlen #include <iterator> // begin, end, iterator_traits, random_access_iterator_tag, distance, next #include <memory> // shared_ptr, make_shared, addressof #include <numeric> // accumulate #include <string> // string, char_traits #include <type_traits> // enable_if, is_base_of, is_pointer, is_integral, remove_pointer #include <utility> // pair, declval #ifndef JSON_NO_IO #include <cstdio> //FILE * #include <istream> // istream #endif // JSON_NO_IO // #include <nlohmann/detail/iterators/iterator_traits.hpp> // #include <nlohmann/detail/macro_scope.hpp> namespace nlohmann { namespace detail { /// the supported input formats enum class input_format_t { json, cbor, msgpack, ubjson, bson }; //////////////////// // input adapters // //////////////////// #ifndef JSON_NO_IO /*! Input adapter for stdio file access. This adapter read only 1 byte and do not use any buffer. This adapter is a very low level adapter. */ class file_input_adapter { public: using char_type = char; JSON_HEDLEY_NON_NULL(2) explicit file_input_adapter(std::FILE* f) noexcept : m_file(f) {} // make class move-only file_input_adapter(const file_input_adapter&) = delete; file_input_adapter(file_input_adapter&&) noexcept = default; file_input_adapter& operator=(const file_input_adapter&) = delete; file_input_adapter& operator=(file_input_adapter&&) = delete; ~file_input_adapter() = default; std::char_traits<char>::int_type get_character() noexcept { return std::fgetc(m_file); } private: /// the file pointer to read from std::FILE* m_file; }; /*! Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at beginning of input. Does not support changing the underlying std::streambuf in mid-input. Maintains underlying std::istream and std::streambuf to support subsequent use of standard std::istream operations to process any input characters following those used in parsing the JSON input. Clears the std::istream flags; any input errors (e.g., EOF) will be detected by the first subsequent call for input from the std::istream. */ class input_stream_adapter { public: using char_type = char; ~input_stream_adapter() { // clear stream flags; we use underlying streambuf I/O, do not // maintain ifstream flags, except eof if (is != nullptr) { is->clear(is->rdstate() & std::ios::eofbit); } } explicit input_stream_adapter(std::istream& i) : is(&i), sb(i.rdbuf()) {} // delete because of pointer members input_stream_adapter(const input_stream_adapter&) = delete; input_stream_adapter& operator=(input_stream_adapter&) = delete; input_stream_adapter& operator=(input_stream_adapter&&) = delete; input_stream_adapter(input_stream_adapter&& rhs) noexcept : is(rhs.is), sb(rhs.sb) { rhs.is = nullptr; rhs.sb = nullptr; } // std::istream/std::streambuf use std::char_traits<char>::to_int_type, to // ensure that std::char_traits<char>::eof() and the character 0xFF do not // end up as the same value, eg. 0xFFFFFFFF. std::char_traits<char>::int_type get_character() { auto res = sb->sbumpc(); // set eof manually, as we don't use the istream interface. if (JSON_HEDLEY_UNLIKELY(res == std::char_traits<char>::eof())) { is->clear(is->rdstate() | std::ios::eofbit); } return res; } private: /// the associated input stream std::istream* is = nullptr; std::streambuf* sb = nullptr; }; #endif // JSON_NO_IO // General-purpose iterator-based adapter. It might not be as fast as // theoretically possible for some containers, but it is extremely versatile. template<typename IteratorType> class iterator_input_adapter { public: using char_type = typename std::iterator_traits<IteratorType>::value_type; iterator_input_adapter(IteratorType first, IteratorType last) : current(std::move(first)), end(std::move(last)) {} typename std::char_traits<char_type>::int_type get_character() { if (JSON_HEDLEY_LIKELY(current != end)) { auto result = std::char_traits<char_type>::to_int_type(*current); std::advance(current, 1); return result; } return std::char_traits<char_type>::eof(); } private: IteratorType current; IteratorType end; template<typename BaseInputAdapter, size_t T> friend struct wide_string_input_helper; bool empty() const { return current == end; } }; template<typename BaseInputAdapter, size_t T> struct wide_string_input_helper; template<typename BaseInputAdapter> struct wide_string_input_helper<BaseInputAdapter, 4> { // UTF-32 static void fill_buffer(BaseInputAdapter& input, std::array<std::char_traits<char>::int_type, 4>& utf8_bytes, size_t& utf8_bytes_index, size_t& utf8_bytes_filled) { utf8_bytes_index = 0; if (JSON_HEDLEY_UNLIKELY(input.empty())) { utf8_bytes[0] = std::char_traits<char>::eof(); utf8_bytes_filled = 1; } else { // get the current character const auto wc = input.get_character(); // UTF-32 to UTF-8 encoding if (wc < 0x80) { utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc); utf8_bytes_filled = 1; } else if (wc <= 0x7FF) { utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xC0u | ((static_cast<unsigned int>(wc) >> 6u) & 0x1Fu)); utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu)); utf8_bytes_filled = 2; } else if (wc <= 0xFFFF) { utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xE0u | ((static_cast<unsigned int>(wc) >> 12u) & 0x0Fu)); utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((static_cast<unsigned int>(wc) >> 6u) & 0x3Fu)); utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu)); utf8_bytes_filled = 3; } else if (wc <= 0x10FFFF) { utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xF0u | ((static_cast<unsigned int>(wc) >> 18u) & 0x07u)); utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((static_cast<unsigned int>(wc) >> 12u) & 0x3Fu)); utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | ((static_cast<unsigned int>(wc) >> 6u) & 0x3Fu)); utf8_bytes[3] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu)); utf8_bytes_filled = 4; } else { // unknown character utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc); utf8_bytes_filled = 1; } } } }; template<typename BaseInputAdapter> struct wide_string_input_helper<BaseInputAdapter, 2> { // UTF-16 static void fill_buffer(BaseInputAdapter& input, std::array<std::char_traits<char>::int_type, 4>& utf8_bytes, size_t& utf8_bytes_index, size_t& utf8_bytes_filled) { utf8_bytes_index = 0; if (JSON_HEDLEY_UNLIKELY(input.empty())) { utf8_bytes[0] = std::char_traits<char>::eof(); utf8_bytes_filled = 1; } else { // get the current character const auto wc = input.get_character(); // UTF-16 to UTF-8 encoding if (wc < 0x80) { utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc); utf8_bytes_filled = 1; } else if (wc <= 0x7FF) { utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xC0u | ((static_cast<unsigned int>(wc) >> 6u))); utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu)); utf8_bytes_filled = 2; } else if (0xD800 > wc || wc >= 0xE000) { utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xE0u | ((static_cast<unsigned int>(wc) >> 12u))); utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((static_cast<unsigned int>(wc) >> 6u) & 0x3Fu)); utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu)); utf8_bytes_filled = 3; } else { if (JSON_HEDLEY_UNLIKELY(!input.empty())) { const auto wc2 = static_cast<unsigned int>(input.get_character()); const auto charcode = 0x10000u + (((static_cast<unsigned int>(wc) & 0x3FFu) << 10u) | (wc2 & 0x3FFu)); utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xF0u | (charcode >> 18u)); utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 12u) & 0x3Fu)); utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 6u) & 0x3Fu)); utf8_bytes[3] = static_cast<std::char_traits<char>::int_type>(0x80u | (charcode & 0x3Fu)); utf8_bytes_filled = 4; } else { utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc); utf8_bytes_filled = 1; } } } } }; // Wraps another input apdater to convert wide character types into individual bytes. template<typename BaseInputAdapter, typename WideCharType> class wide_string_input_adapter { public: using char_type = char; wide_string_input_adapter(BaseInputAdapter base) : base_adapter(base) {} typename std::char_traits<char>::int_type get_character() noexcept { // check if buffer needs to be filled if (utf8_bytes_index == utf8_bytes_filled) { fill_buffer<sizeof(WideCharType)>(); JSON_ASSERT(utf8_bytes_filled > 0); JSON_ASSERT(utf8_bytes_index == 0); } // use buffer JSON_ASSERT(utf8_bytes_filled > 0); JSON_ASSERT(utf8_bytes_index < utf8_bytes_filled); return utf8_bytes[utf8_bytes_index++]; } private: BaseInputAdapter base_adapter; template<size_t T> void fill_buffer() { wide_string_input_helper<BaseInputAdapter, T>::fill_buffer(base_adapter, utf8_bytes, utf8_bytes_index, utf8_bytes_filled); } /// a buffer for UTF-8 bytes std::array<std::char_traits<char>::int_type, 4> utf8_bytes = {{0, 0, 0, 0}}; /// index to the utf8_codes array for the next valid byte std::size_t utf8_bytes_index = 0; /// number of valid bytes in the utf8_codes array std::size_t utf8_bytes_filled = 0; }; template<typename IteratorType, typename Enable = void> struct iterator_input_adapter_factory { using iterator_type = IteratorType; using char_type = typename std::iterator_traits<iterator_type>::value_type; using adapter_type = iterator_input_adapter<iterator_type>; static adapter_type create(IteratorType first, IteratorType last) { return adapter_type(std::move(first), std::move(last)); } }; template<typename T> struct is_iterator_of_multibyte { using value_type = typename std::iterator_traits<T>::value_type; enum { value = sizeof(value_type) > 1 }; }; template<typename IteratorType> struct iterator_input_adapter_factory<IteratorType, enable_if_t<is_iterator_of_multibyte<IteratorType>::value>> { using iterator_type = IteratorType; using char_type = typename std::iterator_traits<iterator_type>::value_type; using base_adapter_type = iterator_input_adapter<iterator_type>; using adapter_type = wide_string_input_adapter<base_adapter_type, char_type>; static adapter_type create(IteratorType first, IteratorType last) { return adapter_type(base_adapter_type(std::move(first), std::move(last))); } }; // General purpose iterator-based input template<typename IteratorType> typename iterator_input_adapter_factory<IteratorType>::adapter_type input_adapter(IteratorType first, IteratorType last) { using factory_type = iterator_input_adapter_factory<IteratorType>; return factory_type::create(first, last); } // Convenience shorthand from container to iterator // Enables ADL on begin(container) and end(container) // Encloses the using declarations in namespace for not to leak them to outside scope namespace container_input_adapter_factory_impl { using std::begin; using std::end; template<typename ContainerType, typename Enable = void> struct container_input_adapter_factory {}; template<typename ContainerType> struct container_input_adapter_factory< ContainerType, void_t<decltype(begin(std::declval<ContainerType>()), end(std::declval<ContainerType>()))>> { using adapter_type = decltype(input_adapter(begin(std::declval<ContainerType>()), end(std::declval<ContainerType>()))); static adapter_type create(const ContainerType& container) { return input_adapter(begin(container), end(container)); } }; } // namespace container_input_adapter_factory_impl template<typename ContainerType> typename container_input_adapter_factory_impl::container_input_adapter_factory<ContainerType>::adapter_type input_adapter(const ContainerType& container) { return container_input_adapter_factory_impl::container_input_adapter_factory<ContainerType>::create(container); } #ifndef JSON_NO_IO // Special cases with fast paths inline file_input_adapter input_adapter(std::FILE* file) { return file_input_adapter(file); } inline input_stream_adapter input_adapter(std::istream& stream) { return input_stream_adapter(stream); } inline input_stream_adapter input_adapter(std::istream&& stream) { return input_stream_adapter(stream); } #endif // JSON_NO_IO using contiguous_bytes_input_adapter = decltype(input_adapter(std::declval<const char*>(), std::declval<const char*>())); // Null-delimited strings, and the like. template < typename CharT, typename std::enable_if < std::is_pointer<CharT>::value&& !std::is_array<CharT>::value&& std::is_integral<typename std::remove_pointer<CharT>::type>::value&& sizeof(typename std::remove_pointer<CharT>::type) == 1, int >::type = 0 > contiguous_bytes_input_adapter input_adapter(CharT b) { auto length = std::strlen(reinterpret_cast<const char*>(b)); const auto* ptr = reinterpret_cast<const char*>(b); return input_adapter(ptr, ptr + length); } template<typename T, std::size_t N> auto input_adapter(T (&array)[N]) -> decltype(input_adapter(array, array + N)) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) { return input_adapter(array, array + N); } // This class only handles inputs of input_buffer_adapter type. // It's required so that expressions like {ptr, len} can be implicitely casted // to the correct adapter. class span_input_adapter { public: template < typename CharT, typename std::enable_if < std::is_pointer<CharT>::value&& std::is_integral<typename std::remove_pointer<CharT>::type>::value&& sizeof(typename std::remove_pointer<CharT>::type) == 1, int >::type = 0 > span_input_adapter(CharT b, std::size_t l) : ia(reinterpret_cast<const char*>(b), reinterpret_cast<const char*>(b) + l) {} template<class IteratorType, typename std::enable_if< std::is_same<typename iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value, int>::type = 0> span_input_adapter(IteratorType first, IteratorType last) : ia(input_adapter(first, last)) {} contiguous_bytes_input_adapter&& get() { return std::move(ia); // NOLINT(hicpp-move-const-arg,performance-move-const-arg) } private: contiguous_bytes_input_adapter ia; }; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/input/json_sax.hpp> #include <cstddef> #include <string> // string #include <utility> // move #include <vector> // vector // #include <nlohmann/detail/exceptions.hpp> // #include <nlohmann/detail/macro_scope.hpp> namespace nlohmann { /*! @brief SAX interface This class describes the SAX interface used by @ref nlohmann::json::sax_parse. Each function is called in different situations while the input is parsed. The boolean return value informs the parser whether to continue processing the input. */ template<typename BasicJsonType> struct json_sax { using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using binary_t = typename BasicJsonType::binary_t; /*! @brief a null value was read @return whether parsing should proceed */ virtual bool null() = 0; /*! @brief a boolean value was read @param[in] val boolean value @return whether parsing should proceed */ virtual bool boolean(bool val) = 0; /*! @brief an integer number was read @param[in] val integer value @return whether parsing should proceed */ virtual bool number_integer(number_integer_t val) = 0; /*! @brief an unsigned integer number was read @param[in] val unsigned integer value @return whether parsing should proceed */ virtual bool number_unsigned(number_unsigned_t val) = 0; /*! @brief an floating-point number was read @param[in] val floating-point value @param[in] s raw token value @return whether parsing should proceed */ virtual bool number_float(number_float_t val, const string_t& s) = 0; /*! @brief a string was read @param[in] val string value @return whether parsing should proceed @note It is safe to move the passed string. */ virtual bool string(string_t& val) = 0; /*! @brief a binary string was read @param[in] val binary value @return whether parsing should proceed @note It is safe to move the passed binary. */ virtual bool binary(binary_t& val) = 0; /*! @brief the beginning of an object was read @param[in] elements number of object elements or -1 if unknown @return whether parsing should proceed @note binary formats may report the number of elements */ virtual bool start_object(std::size_t elements) = 0; /*! @brief an object key was read @param[in] val object key @return whether parsing should proceed @note It is safe to move the passed string. */ virtual bool key(string_t& val) = 0; /*! @brief the end of an object was read @return whether parsing should proceed */ virtual bool end_object() = 0; /*! @brief the beginning of an array was read @param[in] elements number of array elements or -1 if unknown @return whether parsing should proceed @note binary formats may report the number of elements */ virtual bool start_array(std::size_t elements) = 0; /*! @brief the end of an array was read @return whether parsing should proceed */ virtual bool end_array() = 0; /*! @brief a parse error occurred @param[in] position the position in the input where the error occurs @param[in] last_token the last read token @param[in] ex an exception object describing the error @return whether parsing should proceed (must return false) */ virtual bool parse_error(std::size_t position, const std::string& last_token, const detail::exception& ex) = 0; json_sax() = default; json_sax(const json_sax&) = default; json_sax(json_sax&&) noexcept = default; json_sax& operator=(const json_sax&) = default; json_sax& operator=(json_sax&&) noexcept = default; virtual ~json_sax() = default; }; namespace detail { /*! @brief SAX implementation to create a JSON value from SAX events This class implements the @ref json_sax interface and processes the SAX events to create a JSON value which makes it basically a DOM parser. The structure or hierarchy of the JSON value is managed by the stack `ref_stack` which contains a pointer to the respective array or object for each recursion depth. After successful parsing, the value that is passed by reference to the constructor contains the parsed value. @tparam BasicJsonType the JSON type */ template<typename BasicJsonType> class json_sax_dom_parser { public: using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using binary_t = typename BasicJsonType::binary_t; /*! @param[in,out] r reference to a JSON value that is manipulated while parsing @param[in] allow_exceptions_ whether parse errors yield exceptions */ explicit json_sax_dom_parser(BasicJsonType& r, const bool allow_exceptions_ = true) : root(r), allow_exceptions(allow_exceptions_) {} // make class move-only json_sax_dom_parser(const json_sax_dom_parser&) = delete; json_sax_dom_parser(json_sax_dom_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) json_sax_dom_parser& operator=(const json_sax_dom_parser&) = delete; json_sax_dom_parser& operator=(json_sax_dom_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) ~json_sax_dom_parser() = default; bool null() { handle_value(nullptr); return true; } bool boolean(bool val) { handle_value(val); return true; } bool number_integer(number_integer_t val) { handle_value(val); return true; } bool number_unsigned(number_unsigned_t val) { handle_value(val); return true; } bool number_float(number_float_t val, const string_t& /*unused*/) { handle_value(val); return true; } bool string(string_t& val) { handle_value(val); return true; } bool binary(binary_t& val) { handle_value(std::move(val)); return true; } bool start_object(std::size_t len) { ref_stack.push_back(handle_value(BasicJsonType::value_t::object)); if (JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) && len > ref_stack.back()->max_size())) { JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len), *ref_stack.back())); } return true; } bool key(string_t& val) { // add null at given key and store the reference for later object_element = &(ref_stack.back()->m_value.object->operator[](val)); return true; } bool end_object() { ref_stack.back()->set_parents(); ref_stack.pop_back(); return true; } bool start_array(std::size_t len) { ref_stack.push_back(handle_value(BasicJsonType::value_t::array)); if (JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) && len > ref_stack.back()->max_size())) { JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len), *ref_stack.back())); } return true; } bool end_array() { ref_stack.back()->set_parents(); ref_stack.pop_back(); return true; } template<class Exception> bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const Exception& ex) { errored = true; static_cast<void>(ex); if (allow_exceptions) { JSON_THROW(ex); } return false; } constexpr bool is_errored() const { return errored; } private: /*! @invariant If the ref stack is empty, then the passed value will be the new root. @invariant If the ref stack contains a value, then it is an array or an object to which we can add elements */ template<typename Value> JSON_HEDLEY_RETURNS_NON_NULL BasicJsonType* handle_value(Value&& v) { if (ref_stack.empty()) { root = BasicJsonType(std::forward<Value>(v)); return &root; } JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object()); if (ref_stack.back()->is_array()) { ref_stack.back()->m_value.array->emplace_back(std::forward<Value>(v)); return &(ref_stack.back()->m_value.array->back()); } JSON_ASSERT(ref_stack.back()->is_object()); JSON_ASSERT(object_element); *object_element = BasicJsonType(std::forward<Value>(v)); return object_element; } /// the parsed JSON value BasicJsonType& root; /// stack to model hierarchy of values std::vector<BasicJsonType*> ref_stack {}; /// helper to hold the reference for the next object element BasicJsonType* object_element = nullptr; /// whether a syntax error occurred bool errored = false; /// whether to throw exceptions in case of errors const bool allow_exceptions = true; }; template<typename BasicJsonType> class json_sax_dom_callback_parser { public: using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using binary_t = typename BasicJsonType::binary_t; using parser_callback_t = typename BasicJsonType::parser_callback_t; using parse_event_t = typename BasicJsonType::parse_event_t; json_sax_dom_callback_parser(BasicJsonType& r, const parser_callback_t cb, const bool allow_exceptions_ = true) : root(r), callback(cb), allow_exceptions(allow_exceptions_) { keep_stack.push_back(true); } // make class move-only json_sax_dom_callback_parser(const json_sax_dom_callback_parser&) = delete; json_sax_dom_callback_parser(json_sax_dom_callback_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) json_sax_dom_callback_parser& operator=(const json_sax_dom_callback_parser&) = delete; json_sax_dom_callback_parser& operator=(json_sax_dom_callback_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) ~json_sax_dom_callback_parser() = default; bool null() { handle_value(nullptr); return true; } bool boolean(bool val) { handle_value(val); return true; } bool number_integer(number_integer_t val) { handle_value(val); return true; } bool number_unsigned(number_unsigned_t val) { handle_value(val); return true; } bool number_float(number_float_t val, const string_t& /*unused*/) { handle_value(val); return true; } bool string(string_t& val) { handle_value(val); return true; } bool binary(binary_t& val) { handle_value(std::move(val)); return true; } bool start_object(std::size_t len) { // check callback for object start const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::object_start, discarded); keep_stack.push_back(keep); auto val = handle_value(BasicJsonType::value_t::object, true); ref_stack.push_back(val.second); // check object limit if (ref_stack.back() && JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) && len > ref_stack.back()->max_size())) { JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len), *ref_stack.back())); } return true; } bool key(string_t& val) { BasicJsonType k = BasicJsonType(val); // check callback for key const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::key, k); key_keep_stack.push_back(keep); // add discarded value at given key and store the reference for later if (keep && ref_stack.back()) { object_element = &(ref_stack.back()->m_value.object->operator[](val) = discarded); } return true; } bool end_object() { if (ref_stack.back()) { if (!callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::object_end, *ref_stack.back())) { // discard object *ref_stack.back() = discarded; } else { ref_stack.back()->set_parents(); } } JSON_ASSERT(!ref_stack.empty()); JSON_ASSERT(!keep_stack.empty()); ref_stack.pop_back(); keep_stack.pop_back(); if (!ref_stack.empty() && ref_stack.back() && ref_stack.back()->is_structured()) { // remove discarded value for (auto it = ref_stack.back()->begin(); it != ref_stack.back()->end(); ++it) { if (it->is_discarded()) { ref_stack.back()->erase(it); break; } } } return true; } bool start_array(std::size_t len) { const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::array_start, discarded); keep_stack.push_back(keep); auto val = handle_value(BasicJsonType::value_t::array, true); ref_stack.push_back(val.second); // check array limit if (ref_stack.back() && JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) && len > ref_stack.back()->max_size())) { JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len), *ref_stack.back())); } return true; } bool end_array() { bool keep = true; if (ref_stack.back()) { keep = callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::array_end, *ref_stack.back()); if (keep) { ref_stack.back()->set_parents(); } else { // discard array *ref_stack.back() = discarded; } } JSON_ASSERT(!ref_stack.empty()); JSON_ASSERT(!keep_stack.empty()); ref_stack.pop_back(); keep_stack.pop_back(); // remove discarded value if (!keep && !ref_stack.empty() && ref_stack.back()->is_array()) { ref_stack.back()->m_value.array->pop_back(); } return true; } template<class Exception> bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const Exception& ex) { errored = true; static_cast<void>(ex); if (allow_exceptions) { JSON_THROW(ex); } return false; } constexpr bool is_errored() const { return errored; } private: /*! @param[in] v value to add to the JSON value we build during parsing @param[in] skip_callback whether we should skip calling the callback function; this is required after start_array() and start_object() SAX events, because otherwise we would call the callback function with an empty array or object, respectively. @invariant If the ref stack is empty, then the passed value will be the new root. @invariant If the ref stack contains a value, then it is an array or an object to which we can add elements @return pair of boolean (whether value should be kept) and pointer (to the passed value in the ref_stack hierarchy; nullptr if not kept) */ template<typename Value> std::pair<bool, BasicJsonType*> handle_value(Value&& v, const bool skip_callback = false) { JSON_ASSERT(!keep_stack.empty()); // do not handle this value if we know it would be added to a discarded // container if (!keep_stack.back()) { return {false, nullptr}; } // create value auto value = BasicJsonType(std::forward<Value>(v)); // check callback const bool keep = skip_callback || callback(static_cast<int>(ref_stack.size()), parse_event_t::value, value); // do not handle this value if we just learnt it shall be discarded if (!keep) { return {false, nullptr}; } if (ref_stack.empty()) { root = std::move(value); return {true, &root}; } // skip this value if we already decided to skip the parent // (https://github.com/nlohmann/json/issues/971#issuecomment-413678360) if (!ref_stack.back()) { return {false, nullptr}; } // we now only expect arrays and objects JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object()); // array if (ref_stack.back()->is_array()) { ref_stack.back()->m_value.array->emplace_back(std::move(value)); return {true, &(ref_stack.back()->m_value.array->back())}; } // object JSON_ASSERT(ref_stack.back()->is_object()); // check if we should store an element for the current key JSON_ASSERT(!key_keep_stack.empty()); const bool store_element = key_keep_stack.back(); key_keep_stack.pop_back(); if (!store_element) { return {false, nullptr}; } JSON_ASSERT(object_element); *object_element = std::move(value); return {true, object_element}; } /// the parsed JSON value BasicJsonType& root; /// stack to model hierarchy of values std::vector<BasicJsonType*> ref_stack {}; /// stack to manage which values to keep std::vector<bool> keep_stack {}; /// stack to manage which object keys to keep std::vector<bool> key_keep_stack {}; /// helper to hold the reference for the next object element BasicJsonType* object_element = nullptr; /// whether a syntax error occurred bool errored = false; /// callback function const parser_callback_t callback = nullptr; /// whether to throw exceptions in case of errors const bool allow_exceptions = true; /// a discarded value for the callback BasicJsonType discarded = BasicJsonType::value_t::discarded; }; template<typename BasicJsonType> class json_sax_acceptor { public: using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using binary_t = typename BasicJsonType::binary_t; bool null() { return true; } bool boolean(bool /*unused*/) { return true; } bool number_integer(number_integer_t /*unused*/) { return true; } bool number_unsigned(number_unsigned_t /*unused*/) { return true; } bool number_float(number_float_t /*unused*/, const string_t& /*unused*/) { return true; } bool string(string_t& /*unused*/) { return true; } bool binary(binary_t& /*unused*/) { return true; } bool start_object(std::size_t /*unused*/ = std::size_t(-1)) { return true; } bool key(string_t& /*unused*/) { return true; } bool end_object() { return true; } bool start_array(std::size_t /*unused*/ = std::size_t(-1)) { return true; } bool end_array() { return true; } bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const detail::exception& /*unused*/) { return false; } }; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/input/lexer.hpp> #include <array> // array #include <clocale> // localeconv #include <cstddef> // size_t #include <cstdio> // snprintf #include <cstdlib> // strtof, strtod, strtold, strtoll, strtoull #include <initializer_list> // initializer_list #include <string> // char_traits, string #include <utility> // move #include <vector> // vector // #include <nlohmann/detail/input/input_adapters.hpp> // #include <nlohmann/detail/input/position_t.hpp> // #include <nlohmann/detail/macro_scope.hpp> namespace nlohmann { namespace detail { /////////// // lexer // /////////// template<typename BasicJsonType> class lexer_base { public: /// token types for the parser enum class token_type { uninitialized, ///< indicating the scanner is uninitialized literal_true, ///< the `true` literal literal_false, ///< the `false` literal literal_null, ///< the `null` literal value_string, ///< a string -- use get_string() for actual value value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value value_integer, ///< a signed integer -- use get_number_integer() for actual value value_float, ///< an floating point number -- use get_number_float() for actual value begin_array, ///< the character for array begin `[` begin_object, ///< the character for object begin `{` end_array, ///< the character for array end `]` end_object, ///< the character for object end `}` name_separator, ///< the name separator `:` value_separator, ///< the value separator `,` parse_error, ///< indicating a parse error end_of_input, ///< indicating the end of the input buffer literal_or_value ///< a literal or the begin of a value (only for diagnostics) }; /// return name of values of type token_type (only used for errors) JSON_HEDLEY_RETURNS_NON_NULL JSON_HEDLEY_CONST static const char* token_type_name(const token_type t) noexcept { switch (t) { case token_type::uninitialized: return "<uninitialized>"; case token_type::literal_true: return "true literal"; case token_type::literal_false: return "false literal"; case token_type::literal_null: return "null literal"; case token_type::value_string: return "string literal"; case token_type::value_unsigned: case token_type::value_integer: case token_type::value_float: return "number literal"; case token_type::begin_array: return "'['"; case token_type::begin_object: return "'{'"; case token_type::end_array: return "']'"; case token_type::end_object: return "'}'"; case token_type::name_separator: return "':'"; case token_type::value_separator: return "','"; case token_type::parse_error: return "<parse error>"; case token_type::end_of_input: return "end of input"; case token_type::literal_or_value: return "'[', '{', or a literal"; // LCOV_EXCL_START default: // catch non-enum values return "unknown token"; // LCOV_EXCL_STOP } } }; /*! @brief lexical analysis This class organizes the lexical analysis during JSON deserialization. */ template<typename BasicJsonType, typename InputAdapterType> class lexer : public lexer_base<BasicJsonType> { using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using char_type = typename InputAdapterType::char_type; using char_int_type = typename std::char_traits<char_type>::int_type; public: using token_type = typename lexer_base<BasicJsonType>::token_type; explicit lexer(InputAdapterType&& adapter, bool ignore_comments_ = false) noexcept : ia(std::move(adapter)) , ignore_comments(ignore_comments_) , decimal_point_char(static_cast<char_int_type>(get_decimal_point())) {} // delete because of pointer members lexer(const lexer&) = delete; lexer(lexer&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) lexer& operator=(lexer&) = delete; lexer& operator=(lexer&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) ~lexer() = default; private: ///////////////////// // locales ///////////////////// /// return the locale-dependent decimal point JSON_HEDLEY_PURE static char get_decimal_point() noexcept { const auto* loc = localeconv(); JSON_ASSERT(loc != nullptr); return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point); } ///////////////////// // scan functions ///////////////////// /*! @brief get codepoint from 4 hex characters following `\u` For input "\u c1 c2 c3 c4" the codepoint is: (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4 = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0) Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f' must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The conversion is done by subtracting the offset (0x30, 0x37, and 0x57) between the ASCII value of the character and the desired integer value. @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or non-hex character) */ int get_codepoint() { // this function only makes sense after reading `\u` JSON_ASSERT(current == 'u'); int codepoint = 0; const auto factors = { 12u, 8u, 4u, 0u }; for (const auto factor : factors) { get(); if (current >= '0' && current <= '9') { codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x30u) << factor); } else if (current >= 'A' && current <= 'F') { codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x37u) << factor); } else if (current >= 'a' && current <= 'f') { codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x57u) << factor); } else { return -1; } } JSON_ASSERT(0x0000 <= codepoint && codepoint <= 0xFFFF); return codepoint; } /*! @brief check if the next byte(s) are inside a given range Adds the current byte and, for each passed range, reads a new byte and checks if it is inside the range. If a violation was detected, set up an error message and return false. Otherwise, return true. @param[in] ranges list of integers; interpreted as list of pairs of inclusive lower and upper bound, respectively @pre The passed list @a ranges must have 2, 4, or 6 elements; that is, 1, 2, or 3 pairs. This precondition is enforced by an assertion. @return true if and only if no range violation was detected */ bool next_byte_in_range(std::initializer_list<char_int_type> ranges) { JSON_ASSERT(ranges.size() == 2 || ranges.size() == 4 || ranges.size() == 6); add(current); for (auto range = ranges.begin(); range != ranges.end(); ++range) { get(); if (JSON_HEDLEY_LIKELY(*range <= current && current <= *(++range))) { add(current); } else { error_message = "invalid string: ill-formed UTF-8 byte"; return false; } } return true; } /*! @brief scan a string literal This function scans a string according to Sect. 7 of RFC 8259. While scanning, bytes are escaped and copied into buffer token_buffer. Then the function returns successfully, token_buffer is *not* null-terminated (as it may contain \0 bytes), and token_buffer.size() is the number of bytes in the string. @return token_type::value_string if string could be successfully scanned, token_type::parse_error otherwise @note In case of errors, variable error_message contains a textual description. */ token_type scan_string() { // reset token_buffer (ignore opening quote) reset(); // we entered the function by reading an open quote JSON_ASSERT(current == '\"'); while (true) { // get next character switch (get()) { // end of file while parsing string case std::char_traits<char_type>::eof(): { error_message = "invalid string: missing closing quote"; return token_type::parse_error; } // closing quote case '\"': { return token_type::value_string; } // escapes case '\\': { switch (get()) { // quotation mark case '\"': add('\"'); break; // reverse solidus case '\\': add('\\'); break; // solidus case '/': add('/'); break; // backspace case 'b': add('\b'); break; // form feed case 'f': add('\f'); break; // line feed case 'n': add('\n'); break; // carriage return case 'r': add('\r'); break; // tab case 't': add('\t'); break; // unicode escapes case 'u': { const int codepoint1 = get_codepoint(); int codepoint = codepoint1; // start with codepoint1 if (JSON_HEDLEY_UNLIKELY(codepoint1 == -1)) { error_message = "invalid string: '\\u' must be followed by 4 hex digits"; return token_type::parse_error; } // check if code point is a high surrogate if (0xD800 <= codepoint1 && codepoint1 <= 0xDBFF) { // expect next \uxxxx entry if (JSON_HEDLEY_LIKELY(get() == '\\' && get() == 'u')) { const int codepoint2 = get_codepoint(); if (JSON_HEDLEY_UNLIKELY(codepoint2 == -1)) { error_message = "invalid string: '\\u' must be followed by 4 hex digits"; return token_type::parse_error; } // check if codepoint2 is a low surrogate if (JSON_HEDLEY_LIKELY(0xDC00 <= codepoint2 && codepoint2 <= 0xDFFF)) { // overwrite codepoint codepoint = static_cast<int>( // high surrogate occupies the most significant 22 bits (static_cast<unsigned int>(codepoint1) << 10u) // low surrogate occupies the least significant 15 bits + static_cast<unsigned int>(codepoint2) // there is still the 0xD800, 0xDC00 and 0x10000 noise // in the result so we have to subtract with: // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00 - 0x35FDC00u); } else { error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF"; return token_type::parse_error; } } else { error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF"; return token_type::parse_error; } } else { if (JSON_HEDLEY_UNLIKELY(0xDC00 <= codepoint1 && codepoint1 <= 0xDFFF)) { error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF"; return token_type::parse_error; } } // result of the above calculation yields a proper codepoint JSON_ASSERT(0x00 <= codepoint && codepoint <= 0x10FFFF); // translate codepoint into bytes if (codepoint < 0x80) { // 1-byte characters: 0xxxxxxx (ASCII) add(static_cast<char_int_type>(codepoint)); } else if (codepoint <= 0x7FF) { // 2-byte characters: 110xxxxx 10xxxxxx add(static_cast<char_int_type>(0xC0u | (static_cast<unsigned int>(codepoint) >> 6u))); add(static_cast<char_int_type>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu))); } else if (codepoint <= 0xFFFF) { // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx add(static_cast<char_int_type>(0xE0u | (static_cast<unsigned int>(codepoint) >> 12u))); add(static_cast<char_int_type>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu))); add(static_cast<char_int_type>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu))); } else { // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx add(static_cast<char_int_type>(0xF0u | (static_cast<unsigned int>(codepoint) >> 18u))); add(static_cast<char_int_type>(0x80u | ((static_cast<unsigned int>(codepoint) >> 12u) & 0x3Fu))); add(static_cast<char_int_type>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu))); add(static_cast<char_int_type>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu))); } break; } // other characters after escape default: error_message = "invalid string: forbidden character after backslash"; return token_type::parse_error; } break; } // invalid control characters case 0x00: { error_message = "invalid string: control character U+0000 (NUL) must be escaped to \\u0000"; return token_type::parse_error; } case 0x01: { error_message = "invalid string: control character U+0001 (SOH) must be escaped to \\u0001"; return token_type::parse_error; } case 0x02: { error_message = "invalid string: control character U+0002 (STX) must be escaped to \\u0002"; return token_type::parse_error; } case 0x03: { error_message = "invalid string: control character U+0003 (ETX) must be escaped to \\u0003"; return token_type::parse_error; } case 0x04: { error_message = "invalid string: control character U+0004 (EOT) must be escaped to \\u0004"; return token_type::parse_error; } case 0x05: { error_message = "invalid string: control character U+0005 (ENQ) must be escaped to \\u0005"; return token_type::parse_error; } case 0x06: { error_message = "invalid string: control character U+0006 (ACK) must be escaped to \\u0006"; return token_type::parse_error; } case 0x07: { error_message = "invalid string: control character U+0007 (BEL) must be escaped to \\u0007"; return token_type::parse_error; } case 0x08: { error_message = "invalid string: control character U+0008 (BS) must be escaped to \\u0008 or \\b"; return token_type::parse_error; } case 0x09: { error_message = "invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\t"; return token_type::parse_error; } case 0x0A: { error_message = "invalid string: control character U+000A (LF) must be escaped to \\u000A or \\n"; return token_type::parse_error; } case 0x0B: { error_message = "invalid string: control character U+000B (VT) must be escaped to \\u000B"; return token_type::parse_error; } case 0x0C: { error_message = "invalid string: control character U+000C (FF) must be escaped to \\u000C or \\f"; return token_type::parse_error; } case 0x0D: { error_message = "invalid string: control character U+000D (CR) must be escaped to \\u000D or \\r"; return token_type::parse_error; } case 0x0E: { error_message = "invalid string: control character U+000E (SO) must be escaped to \\u000E"; return token_type::parse_error; } case 0x0F: { error_message = "invalid string: control character U+000F (SI) must be escaped to \\u000F"; return token_type::parse_error; } case 0x10: { error_message = "invalid string: control character U+0010 (DLE) must be escaped to \\u0010"; return token_type::parse_error; } case 0x11: { error_message = "invalid string: control character U+0011 (DC1) must be escaped to \\u0011"; return token_type::parse_error; } case 0x12: { error_message = "invalid string: control character U+0012 (DC2) must be escaped to \\u0012"; return token_type::parse_error; } case 0x13: { error_message = "invalid string: control character U+0013 (DC3) must be escaped to \\u0013"; return token_type::parse_error; } case 0x14: { error_message = "invalid string: control character U+0014 (DC4) must be escaped to \\u0014"; return token_type::parse_error; } case 0x15: { error_message = "invalid string: control character U+0015 (NAK) must be escaped to \\u0015"; return token_type::parse_error; } case 0x16: { error_message = "invalid string: control character U+0016 (SYN) must be escaped to \\u0016"; return token_type::parse_error; } case 0x17: { error_message = "invalid string: control character U+0017 (ETB) must be escaped to \\u0017"; return token_type::parse_error; } case 0x18: { error_message = "invalid string: control character U+0018 (CAN) must be escaped to \\u0018"; return token_type::parse_error; } case 0x19: { error_message = "invalid string: control character U+0019 (EM) must be escaped to \\u0019"; return token_type::parse_error; } case 0x1A: { error_message = "invalid string: control character U+001A (SUB) must be escaped to \\u001A"; return token_type::parse_error; } case 0x1B: { error_message = "invalid string: control character U+001B (ESC) must be escaped to \\u001B"; return token_type::parse_error; } case 0x1C: { error_message = "invalid string: control character U+001C (FS) must be escaped to \\u001C"; return token_type::parse_error; } case 0x1D: { error_message = "invalid string: control character U+001D (GS) must be escaped to \\u001D"; return token_type::parse_error; } case 0x1E: { error_message = "invalid string: control character U+001E (RS) must be escaped to \\u001E"; return token_type::parse_error; } case 0x1F: { error_message = "invalid string: control character U+001F (US) must be escaped to \\u001F"; return token_type::parse_error; } // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace)) case 0x20: case 0x21: case 0x23: case 0x24: case 0x25: case 0x26: case 0x27: case 0x28: case 0x29: case 0x2A: case 0x2B: case 0x2C: case 0x2D: case 0x2E: case 0x2F: case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: case 0x3A: case 0x3B: case 0x3C: case 0x3D: case 0x3E: case 0x3F: case 0x40: case 0x41: case 0x42: case 0x43: case 0x44: case 0x45: case 0x46: case 0x47: case 0x48: case 0x49: case 0x4A: case 0x4B: case 0x4C: case 0x4D: case 0x4E: case 0x4F: case 0x50: case 0x51: case 0x52: case 0x53: case 0x54: case 0x55: case 0x56: case 0x57: case 0x58: case 0x59: case 0x5A: case 0x5B: case 0x5D: case 0x5E: case 0x5F: case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: case 0x68: case 0x69: case 0x6A: case 0x6B: case 0x6C: case 0x6D: case 0x6E: case 0x6F: case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: case 0x78: case 0x79: case 0x7A: case 0x7B: case 0x7C: case 0x7D: case 0x7E: case 0x7F: { add(current); break; } // U+0080..U+07FF: bytes C2..DF 80..BF case 0xC2: case 0xC3: case 0xC4: case 0xC5: case 0xC6: case 0xC7: case 0xC8: case 0xC9: case 0xCA: case 0xCB: case 0xCC: case 0xCD: case 0xCE: case 0xCF: case 0xD0: case 0xD1: case 0xD2: case 0xD3: case 0xD4: case 0xD5: case 0xD6: case 0xD7: case 0xD8: case 0xD9: case 0xDA: case 0xDB: case 0xDC: case 0xDD: case 0xDE: case 0xDF: { if (JSON_HEDLEY_UNLIKELY(!next_byte_in_range({0x80, 0xBF}))) { return token_type::parse_error; } break; } // U+0800..U+0FFF: bytes E0 A0..BF 80..BF case 0xE0: { if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF case 0xE1: case 0xE2: case 0xE3: case 0xE4: case 0xE5: case 0xE6: case 0xE7: case 0xE8: case 0xE9: case 0xEA: case 0xEB: case 0xEC: case 0xEE: case 0xEF: { if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // U+D000..U+D7FF: bytes ED 80..9F 80..BF case 0xED: { if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x9F, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF case 0xF0: { if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF case 0xF1: case 0xF2: case 0xF3: { if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF case 0xF4: { if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // remaining bytes (80..C1 and F5..FF) are ill-formed default: { error_message = "invalid string: ill-formed UTF-8 byte"; return token_type::parse_error; } } } } /*! * @brief scan a comment * @return whether comment could be scanned successfully */ bool scan_comment() { switch (get()) { // single-line comments skip input until a newline or EOF is read case '/': { while (true) { switch (get()) { case '\n': case '\r': case std::char_traits<char_type>::eof(): case '\0': return true; default: break; } } } // multi-line comments skip input until */ is read case '*': { while (true) { switch (get()) { case std::char_traits<char_type>::eof(): case '\0': { error_message = "invalid comment; missing closing '*/'"; return false; } case '*': { switch (get()) { case '/': return true; default: { unget(); continue; } } } default: continue; } } } // unexpected character after reading '/' default: { error_message = "invalid comment; expecting '/' or '*' after '/'"; return false; } } } JSON_HEDLEY_NON_NULL(2) static void strtof(float& f, const char* str, char** endptr) noexcept { f = std::strtof(str, endptr); } JSON_HEDLEY_NON_NULL(2) static void strtof(double& f, const char* str, char** endptr) noexcept { f = std::strtod(str, endptr); } JSON_HEDLEY_NON_NULL(2) static void strtof(long double& f, const char* str, char** endptr) noexcept { f = std::strtold(str, endptr); } /*! @brief scan a number literal This function scans a string according to Sect. 6 of RFC 8259. The function is realized with a deterministic finite state machine derived from the grammar described in RFC 8259. Starting in state "init", the input is read and used to determined the next state. Only state "done" accepts the number. State "error" is a trap state to model errors. In the table below, "anything" means any character but the ones listed before. state | 0 | 1-9 | e E | + | - | . | anything ---------|----------|----------|----------|---------|---------|----------|----------- init | zero | any1 | [error] | [error] | minus | [error] | [error] minus | zero | any1 | [error] | [error] | [error] | [error] | [error] zero | done | done | exponent | done | done | decimal1 | done any1 | any1 | any1 | exponent | done | done | decimal1 | done decimal1 | decimal2 | decimal2 | [error] | [error] | [error] | [error] | [error] decimal2 | decimal2 | decimal2 | exponent | done | done | done | done exponent | any2 | any2 | [error] | sign | sign | [error] | [error] sign | any2 | any2 | [error] | [error] | [error] | [error] | [error] any2 | any2 | any2 | done | done | done | done | done The state machine is realized with one label per state (prefixed with "scan_number_") and `goto` statements between them. The state machine contains cycles, but any cycle can be left when EOF is read. Therefore, the function is guaranteed to terminate. During scanning, the read bytes are stored in token_buffer. This string is then converted to a signed integer, an unsigned integer, or a floating-point number. @return token_type::value_unsigned, token_type::value_integer, or token_type::value_float if number could be successfully scanned, token_type::parse_error otherwise @note The scanner is independent of the current locale. Internally, the locale's decimal point is used instead of `.` to work with the locale-dependent converters. */ token_type scan_number() // lgtm [cpp/use-of-goto] { // reset token_buffer to store the number's bytes reset(); // the type of the parsed number; initially set to unsigned; will be // changed if minus sign, decimal point or exponent is read token_type number_type = token_type::value_unsigned; // state (init): we just found out we need to scan a number switch (current) { case '-': { add(current); goto scan_number_minus; } case '0': { add(current); goto scan_number_zero; } case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any1; } // all other characters are rejected outside scan_number() default: // LCOV_EXCL_LINE JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE } scan_number_minus: // state: we just parsed a leading minus sign number_type = token_type::value_integer; switch (get()) { case '0': { add(current); goto scan_number_zero; } case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any1; } default: { error_message = "invalid number; expected digit after '-'"; return token_type::parse_error; } } scan_number_zero: // state: we just parse a zero (maybe with a leading minus sign) switch (get()) { case '.': { add(decimal_point_char); goto scan_number_decimal1; } case 'e': case 'E': { add(current); goto scan_number_exponent; } default: goto scan_number_done; } scan_number_any1: // state: we just parsed a number 0-9 (maybe with a leading minus sign) switch (get()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any1; } case '.': { add(decimal_point_char); goto scan_number_decimal1; } case 'e': case 'E': { add(current); goto scan_number_exponent; } default: goto scan_number_done; } scan_number_decimal1: // state: we just parsed a decimal point number_type = token_type::value_float; switch (get()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_decimal2; } default: { error_message = "invalid number; expected digit after '.'"; return token_type::parse_error; } } scan_number_decimal2: // we just parsed at least one number after a decimal point switch (get()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_decimal2; } case 'e': case 'E': { add(current); goto scan_number_exponent; } default: goto scan_number_done; } scan_number_exponent: // we just parsed an exponent number_type = token_type::value_float; switch (get()) { case '+': case '-': { add(current); goto scan_number_sign; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any2; } default: { error_message = "invalid number; expected '+', '-', or digit after exponent"; return token_type::parse_error; } } scan_number_sign: // we just parsed an exponent sign switch (get()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any2; } default: { error_message = "invalid number; expected digit after exponent sign"; return token_type::parse_error; } } scan_number_any2: // we just parsed a number after the exponent or exponent sign switch (get()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any2; } default: goto scan_number_done; } scan_number_done: // unget the character after the number (we only read it to know that // we are done scanning a number) unget(); char* endptr = nullptr; // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) errno = 0; // try to parse integers first and fall back to floats if (number_type == token_type::value_unsigned) { const auto x = std::strtoull(token_buffer.data(), &endptr, 10); // we checked the number format before JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size()); if (errno == 0) { value_unsigned = static_cast<number_unsigned_t>(x); if (value_unsigned == x) { return token_type::value_unsigned; } } } else if (number_type == token_type::value_integer) { const auto x = std::strtoll(token_buffer.data(), &endptr, 10); // we checked the number format before JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size()); if (errno == 0) { value_integer = static_cast<number_integer_t>(x); if (value_integer == x) { return token_type::value_integer; } } } // this code is reached if we parse a floating-point number or if an // integer conversion above failed strtof(value_float, token_buffer.data(), &endptr); // we checked the number format before JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size()); return token_type::value_float; } /*! @param[in] literal_text the literal text to expect @param[in] length the length of the passed literal text @param[in] return_type the token type to return on success */ JSON_HEDLEY_NON_NULL(2) token_type scan_literal(const char_type* literal_text, const std::size_t length, token_type return_type) { JSON_ASSERT(std::char_traits<char_type>::to_char_type(current) == literal_text[0]); for (std::size_t i = 1; i < length; ++i) { if (JSON_HEDLEY_UNLIKELY(std::char_traits<char_type>::to_char_type(get()) != literal_text[i])) { error_message = "invalid literal"; return token_type::parse_error; } } return return_type; } ///////////////////// // input management ///////////////////// /// reset token_buffer; current character is beginning of token void reset() noexcept { token_buffer.clear(); token_string.clear(); token_string.push_back(std::char_traits<char_type>::to_char_type(current)); } /* @brief get next character from the input This function provides the interface to the used input adapter. It does not throw in case the input reached EOF, but returns a `std::char_traits<char>::eof()` in that case. Stores the scanned characters for use in error messages. @return character read from the input */ char_int_type get() { ++position.chars_read_total; ++position.chars_read_current_line; if (next_unget) { // just reset the next_unget variable and work with current next_unget = false; } else { current = ia.get_character(); } if (JSON_HEDLEY_LIKELY(current != std::char_traits<char_type>::eof())) { token_string.push_back(std::char_traits<char_type>::to_char_type(current)); } if (current == '\n') { ++position.lines_read; position.chars_read_current_line = 0; } return current; } /*! @brief unget current character (read it again on next get) We implement unget by setting variable next_unget to true. The input is not changed - we just simulate ungetting by modifying chars_read_total, chars_read_current_line, and token_string. The next call to get() will behave as if the unget character is read again. */ void unget() { next_unget = true; --position.chars_read_total; // in case we "unget" a newline, we have to also decrement the lines_read if (position.chars_read_current_line == 0) { if (position.lines_read > 0) { --position.lines_read; } } else { --position.chars_read_current_line; } if (JSON_HEDLEY_LIKELY(current != std::char_traits<char_type>::eof())) { JSON_ASSERT(!token_string.empty()); token_string.pop_back(); } } /// add a character to token_buffer void add(char_int_type c) { token_buffer.push_back(static_cast<typename string_t::value_type>(c)); } public: ///////////////////// // value getters ///////////////////// /// return integer value constexpr number_integer_t get_number_integer() const noexcept { return value_integer; } /// return unsigned integer value constexpr number_unsigned_t get_number_unsigned() const noexcept { return value_unsigned; } /// return floating-point value constexpr number_float_t get_number_float() const noexcept { return value_float; } /// return current string value (implicitly resets the token; useful only once) string_t& get_string() { return token_buffer; } ///////////////////// // diagnostics ///////////////////// /// return position of last read token constexpr position_t get_position() const noexcept { return position; } /// return the last read token (for errors only). Will never contain EOF /// (an arbitrary value that is not a valid char value, often -1), because /// 255 may legitimately occur. May contain NUL, which should be escaped. std::string get_token_string() const { // escape control characters std::string result; for (const auto c : token_string) { if (static_cast<unsigned char>(c) <= '\x1F') { // escape control characters std::array<char, 9> cs{{}}; (std::snprintf)(cs.data(), cs.size(), "<U+%.4X>", static_cast<unsigned char>(c)); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) result += cs.data(); } else { // add character as is result.push_back(static_cast<std::string::value_type>(c)); } } return result; } /// return syntax error message JSON_HEDLEY_RETURNS_NON_NULL constexpr const char* get_error_message() const noexcept { return error_message; } ///////////////////// // actual scanner ///////////////////// /*! @brief skip the UTF-8 byte order mark @return true iff there is no BOM or the correct BOM has been skipped */ bool skip_bom() { if (get() == 0xEF) { // check if we completely parse the BOM return get() == 0xBB && get() == 0xBF; } // the first character is not the beginning of the BOM; unget it to // process is later unget(); return true; } void skip_whitespace() { do { get(); } while (current == ' ' || current == '\t' || current == '\n' || current == '\r'); } token_type scan() { // initially, skip the BOM if (position.chars_read_total == 0 && !skip_bom()) { error_message = "invalid BOM; must be 0xEF 0xBB 0xBF if given"; return token_type::parse_error; } // read next character and ignore whitespace skip_whitespace(); // ignore comments while (ignore_comments && current == '/') { if (!scan_comment()) { return token_type::parse_error; } // skip following whitespace skip_whitespace(); } switch (current) { // structural characters case '[': return token_type::begin_array; case ']': return token_type::end_array; case '{': return token_type::begin_object; case '}': return token_type::end_object; case ':': return token_type::name_separator; case ',': return token_type::value_separator; // literals case 't': { std::array<char_type, 4> true_literal = {{char_type('t'), char_type('r'), char_type('u'), char_type('e')}}; return scan_literal(true_literal.data(), true_literal.size(), token_type::literal_true); } case 'f': { std::array<char_type, 5> false_literal = {{char_type('f'), char_type('a'), char_type('l'), char_type('s'), char_type('e')}}; return scan_literal(false_literal.data(), false_literal.size(), token_type::literal_false); } case 'n': { std::array<char_type, 4> null_literal = {{char_type('n'), char_type('u'), char_type('l'), char_type('l')}}; return scan_literal(null_literal.data(), null_literal.size(), token_type::literal_null); } // string case '\"': return scan_string(); // number case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return scan_number(); // end of input (the null byte is needed when parsing from // string literals) case '\0': case std::char_traits<char_type>::eof(): return token_type::end_of_input; // error default: error_message = "invalid literal"; return token_type::parse_error; } } private: /// input adapter InputAdapterType ia; /// whether comments should be ignored (true) or signaled as errors (false) const bool ignore_comments = false; /// the current character char_int_type current = std::char_traits<char_type>::eof(); /// whether the next get() call should just return current bool next_unget = false; /// the start position of the current token position_t position {}; /// raw input token string (for error messages) std::vector<char_type> token_string {}; /// buffer for variable-length tokens (numbers, strings) string_t token_buffer {}; /// a description of occurred lexer errors const char* error_message = ""; // number values number_integer_t value_integer = 0; number_unsigned_t value_unsigned = 0; number_float_t value_float = 0; /// the decimal point const char_int_type decimal_point_char = '.'; }; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/macro_scope.hpp> // #include <nlohmann/detail/meta/is_sax.hpp> #include <cstdint> // size_t #include <utility> // declval #include <string> // string // #include <nlohmann/detail/meta/detected.hpp> // #include <nlohmann/detail/meta/type_traits.hpp> namespace nlohmann { namespace detail { template<typename T> using null_function_t = decltype(std::declval<T&>().null()); template<typename T> using boolean_function_t = decltype(std::declval<T&>().boolean(std::declval<bool>())); template<typename T, typename Integer> using number_integer_function_t = decltype(std::declval<T&>().number_integer(std::declval<Integer>())); template<typename T, typename Unsigned> using number_unsigned_function_t = decltype(std::declval<T&>().number_unsigned(std::declval<Unsigned>())); template<typename T, typename Float, typename String> using number_float_function_t = decltype(std::declval<T&>().number_float( std::declval<Float>(), std::declval<const String&>())); template<typename T, typename String> using string_function_t = decltype(std::declval<T&>().string(std::declval<String&>())); template<typename T, typename Binary> using binary_function_t = decltype(std::declval<T&>().binary(std::declval<Binary&>())); template<typename T> using start_object_function_t = decltype(std::declval<T&>().start_object(std::declval<std::size_t>())); template<typename T, typename String> using key_function_t = decltype(std::declval<T&>().key(std::declval<String&>())); template<typename T> using end_object_function_t = decltype(std::declval<T&>().end_object()); template<typename T> using start_array_function_t = decltype(std::declval<T&>().start_array(std::declval<std::size_t>())); template<typename T> using end_array_function_t = decltype(std::declval<T&>().end_array()); template<typename T, typename Exception> using parse_error_function_t = decltype(std::declval<T&>().parse_error( std::declval<std::size_t>(), std::declval<const std::string&>(), std::declval<const Exception&>())); template<typename SAX, typename BasicJsonType> struct is_sax { private: static_assert(is_basic_json<BasicJsonType>::value, "BasicJsonType must be of type basic_json<...>"); using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using binary_t = typename BasicJsonType::binary_t; using exception_t = typename BasicJsonType::exception; public: static constexpr bool value = is_detected_exact<bool, null_function_t, SAX>::value && is_detected_exact<bool, boolean_function_t, SAX>::value && is_detected_exact<bool, number_integer_function_t, SAX, number_integer_t>::value && is_detected_exact<bool, number_unsigned_function_t, SAX, number_unsigned_t>::value && is_detected_exact<bool, number_float_function_t, SAX, number_float_t, string_t>::value && is_detected_exact<bool, string_function_t, SAX, string_t>::value && is_detected_exact<bool, binary_function_t, SAX, binary_t>::value && is_detected_exact<bool, start_object_function_t, SAX>::value && is_detected_exact<bool, key_function_t, SAX, string_t>::value && is_detected_exact<bool, end_object_function_t, SAX>::value && is_detected_exact<bool, start_array_function_t, SAX>::value && is_detected_exact<bool, end_array_function_t, SAX>::value && is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value; }; template<typename SAX, typename BasicJsonType> struct is_sax_static_asserts { private: static_assert(is_basic_json<BasicJsonType>::value, "BasicJsonType must be of type basic_json<...>"); using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using binary_t = typename BasicJsonType::binary_t; using exception_t = typename BasicJsonType::exception; public: static_assert(is_detected_exact<bool, null_function_t, SAX>::value, "Missing/invalid function: bool null()"); static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value, "Missing/invalid function: bool boolean(bool)"); static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value, "Missing/invalid function: bool boolean(bool)"); static_assert( is_detected_exact<bool, number_integer_function_t, SAX, number_integer_t>::value, "Missing/invalid function: bool number_integer(number_integer_t)"); static_assert( is_detected_exact<bool, number_unsigned_function_t, SAX, number_unsigned_t>::value, "Missing/invalid function: bool number_unsigned(number_unsigned_t)"); static_assert(is_detected_exact<bool, number_float_function_t, SAX, number_float_t, string_t>::value, "Missing/invalid function: bool number_float(number_float_t, const string_t&)"); static_assert( is_detected_exact<bool, string_function_t, SAX, string_t>::value, "Missing/invalid function: bool string(string_t&)"); static_assert( is_detected_exact<bool, binary_function_t, SAX, binary_t>::value, "Missing/invalid function: bool binary(binary_t&)"); static_assert(is_detected_exact<bool, start_object_function_t, SAX>::value, "Missing/invalid function: bool start_object(std::size_t)"); static_assert(is_detected_exact<bool, key_function_t, SAX, string_t>::value, "Missing/invalid function: bool key(string_t&)"); static_assert(is_detected_exact<bool, end_object_function_t, SAX>::value, "Missing/invalid function: bool end_object()"); static_assert(is_detected_exact<bool, start_array_function_t, SAX>::value, "Missing/invalid function: bool start_array(std::size_t)"); static_assert(is_detected_exact<bool, end_array_function_t, SAX>::value, "Missing/invalid function: bool end_array()"); static_assert( is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value, "Missing/invalid function: bool parse_error(std::size_t, const " "std::string&, const exception&)"); }; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/value_t.hpp> namespace nlohmann { namespace detail { /// how to treat CBOR tags enum class cbor_tag_handler_t { error, ///< throw a parse_error exception in case of a tag ignore ///< ignore tags }; /*! @brief determine system byte order @return true if and only if system's byte order is little endian @note from https://stackoverflow.com/a/1001328/266378 */ static inline bool little_endianess(int num = 1) noexcept { return *reinterpret_cast<char*>(&num) == 1; } /////////////////// // binary reader // /////////////////// /*! @brief deserialization of CBOR, MessagePack, and UBJSON values */ template<typename BasicJsonType, typename InputAdapterType, typename SAX = json_sax_dom_parser<BasicJsonType>> class binary_reader { using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using binary_t = typename BasicJsonType::binary_t; using json_sax_t = SAX; using char_type = typename InputAdapterType::char_type; using char_int_type = typename std::char_traits<char_type>::int_type; public: /*! @brief create a binary reader @param[in] adapter input adapter to read from */ explicit binary_reader(InputAdapterType&& adapter) noexcept : ia(std::move(adapter)) { (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {}; } // make class move-only binary_reader(const binary_reader&) = delete; binary_reader(binary_reader&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) binary_reader& operator=(const binary_reader&) = delete; binary_reader& operator=(binary_reader&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) ~binary_reader() = default; /*! @param[in] format the binary format to parse @param[in] sax_ a SAX event processor @param[in] strict whether to expect the input to be consumed completed @param[in] tag_handler how to treat CBOR tags @return whether parsing was successful */ JSON_HEDLEY_NON_NULL(3) bool sax_parse(const input_format_t format, json_sax_t* sax_, const bool strict = true, const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) { sax = sax_; bool result = false; switch (format) { case input_format_t::bson: result = parse_bson_internal(); break; case input_format_t::cbor: result = parse_cbor_internal(true, tag_handler); break; case input_format_t::msgpack: result = parse_msgpack_internal(); break; case input_format_t::ubjson: result = parse_ubjson_internal(); break; default: // LCOV_EXCL_LINE JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE } // strict mode: next byte must be EOF if (result && strict) { if (format == input_format_t::ubjson) { get_ignore_noop(); } else { get(); } if (JSON_HEDLEY_UNLIKELY(current != std::char_traits<char_type>::eof())) { return sax->parse_error(chars_read, get_token_string(), parse_error::create(110, chars_read, exception_message(format, "expected end of input; last byte: 0x" + get_token_string(), "value"), BasicJsonType())); } } return result; } private: ////////// // BSON // ////////// /*! @brief Reads in a BSON-object and passes it to the SAX-parser. @return whether a valid BSON-value was passed to the SAX parser */ bool parse_bson_internal() { std::int32_t document_size{}; get_number<std::int32_t, true>(input_format_t::bson, document_size); if (JSON_HEDLEY_UNLIKELY(!sax->start_object(std::size_t(-1)))) { return false; } if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/false))) { return false; } return sax->end_object(); } /*! @brief Parses a C-style string from the BSON input. @param[in,out] result A reference to the string variable where the read string is to be stored. @return `true` if the \x00-byte indicating the end of the string was encountered before the EOF; false` indicates an unexpected EOF. */ bool get_bson_cstr(string_t& result) { auto out = std::back_inserter(result); while (true) { get(); if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, "cstring"))) { return false; } if (current == 0x00) { return true; } *out++ = static_cast<typename string_t::value_type>(current); } } /*! @brief Parses a zero-terminated string of length @a len from the BSON input. @param[in] len The length (including the zero-byte at the end) of the string to be read. @param[in,out] result A reference to the string variable where the read string is to be stored. @tparam NumberType The type of the length @a len @pre len >= 1 @return `true` if the string was successfully parsed */ template<typename NumberType> bool get_bson_string(const NumberType len, string_t& result) { if (JSON_HEDLEY_UNLIKELY(len < 1)) { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::bson, "string length must be at least 1, is " + std::to_string(len), "string"), BasicJsonType())); } return get_string(input_format_t::bson, len - static_cast<NumberType>(1), result) && get() != std::char_traits<char_type>::eof(); } /*! @brief Parses a byte array input of length @a len from the BSON input. @param[in] len The length of the byte array to be read. @param[in,out] result A reference to the binary variable where the read array is to be stored. @tparam NumberType The type of the length @a len @pre len >= 0 @return `true` if the byte array was successfully parsed */ template<typename NumberType> bool get_bson_binary(const NumberType len, binary_t& result) { if (JSON_HEDLEY_UNLIKELY(len < 0)) { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::bson, "byte array length cannot be negative, is " + std::to_string(len), "binary"), BasicJsonType())); } // All BSON binary values have a subtype std::uint8_t subtype{}; get_number<std::uint8_t>(input_format_t::bson, subtype); result.set_subtype(subtype); return get_binary(input_format_t::bson, len, result); } /*! @brief Read a BSON document element of the given @a element_type. @param[in] element_type The BSON element type, c.f. http://bsonspec.org/spec.html @param[in] element_type_parse_position The position in the input stream, where the `element_type` was read. @warning Not all BSON element types are supported yet. An unsupported @a element_type will give rise to a parse_error.114: Unsupported BSON record type 0x... @return whether a valid BSON-object/array was passed to the SAX parser */ bool parse_bson_element_internal(const char_int_type element_type, const std::size_t element_type_parse_position) { switch (element_type) { case 0x01: // double { double number{}; return get_number<double, true>(input_format_t::bson, number) && sax->number_float(static_cast<number_float_t>(number), ""); } case 0x02: // string { std::int32_t len{}; string_t value; return get_number<std::int32_t, true>(input_format_t::bson, len) && get_bson_string(len, value) && sax->string(value); } case 0x03: // object { return parse_bson_internal(); } case 0x04: // array { return parse_bson_array(); } case 0x05: // binary { std::int32_t len{}; binary_t value; return get_number<std::int32_t, true>(input_format_t::bson, len) && get_bson_binary(len, value) && sax->binary(value); } case 0x08: // boolean { return sax->boolean(get() != 0); } case 0x0A: // null { return sax->null(); } case 0x10: // int32 { std::int32_t value{}; return get_number<std::int32_t, true>(input_format_t::bson, value) && sax->number_integer(value); } case 0x12: // int64 { std::int64_t value{}; return get_number<std::int64_t, true>(input_format_t::bson, value) && sax->number_integer(value); } default: // anything else not supported (yet) { std::array<char, 3> cr{{}}; (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast<unsigned char>(element_type)); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) return sax->parse_error(element_type_parse_position, std::string(cr.data()), parse_error::create(114, element_type_parse_position, "Unsupported BSON record type 0x" + std::string(cr.data()), BasicJsonType())); } } } /*! @brief Read a BSON element list (as specified in the BSON-spec) The same binary layout is used for objects and arrays, hence it must be indicated with the argument @a is_array which one is expected (true --> array, false --> object). @param[in] is_array Determines if the element list being read is to be treated as an object (@a is_array == false), or as an array (@a is_array == true). @return whether a valid BSON-object/array was passed to the SAX parser */ bool parse_bson_element_list(const bool is_array) { string_t key; while (auto element_type = get()) { if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, "element list"))) { return false; } const std::size_t element_type_parse_position = chars_read; if (JSON_HEDLEY_UNLIKELY(!get_bson_cstr(key))) { return false; } if (!is_array && !sax->key(key)) { return false; } if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_internal(element_type, element_type_parse_position))) { return false; } // get_bson_cstr only appends key.clear(); } return true; } /*! @brief Reads an array from the BSON input and passes it to the SAX-parser. @return whether a valid BSON-array was passed to the SAX parser */ bool parse_bson_array() { std::int32_t document_size{}; get_number<std::int32_t, true>(input_format_t::bson, document_size); if (JSON_HEDLEY_UNLIKELY(!sax->start_array(std::size_t(-1)))) { return false; } if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/true))) { return false; } return sax->end_array(); } ////////// // CBOR // ////////// /*! @param[in] get_char whether a new character should be retrieved from the input (true) or whether the last read character should be considered instead (false) @param[in] tag_handler how CBOR tags should be treated @return whether a valid CBOR value was passed to the SAX parser */ bool parse_cbor_internal(const bool get_char, const cbor_tag_handler_t tag_handler) { switch (get_char ? get() : current) { // EOF case std::char_traits<char_type>::eof(): return unexpect_eof(input_format_t::cbor, "value"); // Integer 0x00..0x17 (0..23) case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: case 0x08: case 0x09: case 0x0A: case 0x0B: case 0x0C: case 0x0D: case 0x0E: case 0x0F: case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17: return sax->number_unsigned(static_cast<number_unsigned_t>(current)); case 0x18: // Unsigned integer (one-byte uint8_t follows) { std::uint8_t number{}; return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); } case 0x19: // Unsigned integer (two-byte uint16_t follows) { std::uint16_t number{}; return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); } case 0x1A: // Unsigned integer (four-byte uint32_t follows) { std::uint32_t number{}; return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); } case 0x1B: // Unsigned integer (eight-byte uint64_t follows) { std::uint64_t number{}; return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); } // Negative integer -1-0x00..-1-0x17 (-1..-24) case 0x20: case 0x21: case 0x22: case 0x23: case 0x24: case 0x25: case 0x26: case 0x27: case 0x28: case 0x29: case 0x2A: case 0x2B: case 0x2C: case 0x2D: case 0x2E: case 0x2F: case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: case 0x35: case 0x36: case 0x37: return sax->number_integer(static_cast<std::int8_t>(0x20 - 1 - current)); case 0x38: // Negative integer (one-byte uint8_t follows) { std::uint8_t number{}; return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast<number_integer_t>(-1) - number); } case 0x39: // Negative integer -1-n (two-byte uint16_t follows) { std::uint16_t number{}; return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast<number_integer_t>(-1) - number); } case 0x3A: // Negative integer -1-n (four-byte uint32_t follows) { std::uint32_t number{}; return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast<number_integer_t>(-1) - number); } case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows) { std::uint64_t number{}; return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast<number_integer_t>(-1) - static_cast<number_integer_t>(number)); } // Binary data (0x00..0x17 bytes follow) case 0x40: case 0x41: case 0x42: case 0x43: case 0x44: case 0x45: case 0x46: case 0x47: case 0x48: case 0x49: case 0x4A: case 0x4B: case 0x4C: case 0x4D: case 0x4E: case 0x4F: case 0x50: case 0x51: case 0x52: case 0x53: case 0x54: case 0x55: case 0x56: case 0x57: case 0x58: // Binary data (one-byte uint8_t for n follows) case 0x59: // Binary data (two-byte uint16_t for n follow) case 0x5A: // Binary data (four-byte uint32_t for n follow) case 0x5B: // Binary data (eight-byte uint64_t for n follow) case 0x5F: // Binary data (indefinite length) { binary_t b; return get_cbor_binary(b) && sax->binary(b); } // UTF-8 string (0x00..0x17 bytes follow) case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: case 0x68: case 0x69: case 0x6A: case 0x6B: case 0x6C: case 0x6D: case 0x6E: case 0x6F: case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: case 0x78: // UTF-8 string (one-byte uint8_t for n follows) case 0x79: // UTF-8 string (two-byte uint16_t for n follow) case 0x7A: // UTF-8 string (four-byte uint32_t for n follow) case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow) case 0x7F: // UTF-8 string (indefinite length) { string_t s; return get_cbor_string(s) && sax->string(s); } // array (0x00..0x17 data items follow) case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: case 0x88: case 0x89: case 0x8A: case 0x8B: case 0x8C: case 0x8D: case 0x8E: case 0x8F: case 0x90: case 0x91: case 0x92: case 0x93: case 0x94: case 0x95: case 0x96: case 0x97: return get_cbor_array(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu), tag_handler); case 0x98: // array (one-byte uint8_t for n follows) { std::uint8_t len{}; return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast<std::size_t>(len), tag_handler); } case 0x99: // array (two-byte uint16_t for n follow) { std::uint16_t len{}; return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast<std::size_t>(len), tag_handler); } case 0x9A: // array (four-byte uint32_t for n follow) { std::uint32_t len{}; return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast<std::size_t>(len), tag_handler); } case 0x9B: // array (eight-byte uint64_t for n follow) { std::uint64_t len{}; return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast<std::size_t>(len), tag_handler); } case 0x9F: // array (indefinite length) return get_cbor_array(std::size_t(-1), tag_handler); // map (0x00..0x17 pairs of data items follow) case 0xA0: case 0xA1: case 0xA2: case 0xA3: case 0xA4: case 0xA5: case 0xA6: case 0xA7: case 0xA8: case 0xA9: case 0xAA: case 0xAB: case 0xAC: case 0xAD: case 0xAE: case 0xAF: case 0xB0: case 0xB1: case 0xB2: case 0xB3: case 0xB4: case 0xB5: case 0xB6: case 0xB7: return get_cbor_object(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu), tag_handler); case 0xB8: // map (one-byte uint8_t for n follows) { std::uint8_t len{}; return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast<std::size_t>(len), tag_handler); } case 0xB9: // map (two-byte uint16_t for n follow) { std::uint16_t len{}; return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast<std::size_t>(len), tag_handler); } case 0xBA: // map (four-byte uint32_t for n follow) { std::uint32_t len{}; return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast<std::size_t>(len), tag_handler); } case 0xBB: // map (eight-byte uint64_t for n follow) { std::uint64_t len{}; return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast<std::size_t>(len), tag_handler); } case 0xBF: // map (indefinite length) return get_cbor_object(std::size_t(-1), tag_handler); case 0xC6: // tagged item case 0xC7: case 0xC8: case 0xC9: case 0xCA: case 0xCB: case 0xCC: case 0xCD: case 0xCE: case 0xCF: case 0xD0: case 0xD1: case 0xD2: case 0xD3: case 0xD4: case 0xD8: // tagged item (1 bytes follow) case 0xD9: // tagged item (2 bytes follow) case 0xDA: // tagged item (4 bytes follow) case 0xDB: // tagged item (8 bytes follow) { switch (tag_handler) { case cbor_tag_handler_t::error: { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::cbor, "invalid byte: 0x" + last_token, "value"), BasicJsonType())); } case cbor_tag_handler_t::ignore: { switch (current) { case 0xD8: { std::uint8_t len{}; get_number(input_format_t::cbor, len); break; } case 0xD9: { std::uint16_t len{}; get_number(input_format_t::cbor, len); break; } case 0xDA: { std::uint32_t len{}; get_number(input_format_t::cbor, len); break; } case 0xDB: { std::uint64_t len{}; get_number(input_format_t::cbor, len); break; } default: break; } return parse_cbor_internal(true, tag_handler); } default: // LCOV_EXCL_LINE JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE return false; // LCOV_EXCL_LINE } } case 0xF4: // false return sax->boolean(false); case 0xF5: // true return sax->boolean(true); case 0xF6: // null return sax->null(); case 0xF9: // Half-Precision Float (two-byte IEEE 754) { const auto byte1_raw = get(); if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "number"))) { return false; } const auto byte2_raw = get(); if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "number"))) { return false; } const auto byte1 = static_cast<unsigned char>(byte1_raw); const auto byte2 = static_cast<unsigned char>(byte2_raw); // code from RFC 7049, Appendix D, Figure 3: // As half-precision floating-point numbers were only added // to IEEE 754 in 2008, today's programming platforms often // still only have limited support for them. It is very // easy to include at least decoding support for them even // without such support. An example of a small decoder for // half-precision floating-point numbers in the C language // is shown in Fig. 3. const auto half = static_cast<unsigned int>((byte1 << 8u) + byte2); const double val = [&half] { const int exp = (half >> 10u) & 0x1Fu; const unsigned int mant = half & 0x3FFu; JSON_ASSERT(0 <= exp&& exp <= 32); JSON_ASSERT(mant <= 1024); switch (exp) { case 0: return std::ldexp(mant, -24); case 31: return (mant == 0) ? std::numeric_limits<double>::infinity() : std::numeric_limits<double>::quiet_NaN(); default: return std::ldexp(mant + 1024, exp - 25); } }(); return sax->number_float((half & 0x8000u) != 0 ? static_cast<number_float_t>(-val) : static_cast<number_float_t>(val), ""); } case 0xFA: // Single-Precision Float (four-byte IEEE 754) { float number{}; return get_number(input_format_t::cbor, number) && sax->number_float(static_cast<number_float_t>(number), ""); } case 0xFB: // Double-Precision Float (eight-byte IEEE 754) { double number{}; return get_number(input_format_t::cbor, number) && sax->number_float(static_cast<number_float_t>(number), ""); } default: // anything else (0xFF is handled inside the other types) { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::cbor, "invalid byte: 0x" + last_token, "value"), BasicJsonType())); } } } /*! @brief reads a CBOR string This function first reads starting bytes to determine the expected string length and then copies this number of bytes into a string. Additionally, CBOR's strings with indefinite lengths are supported. @param[out] result created string @return whether string creation completed */ bool get_cbor_string(string_t& result) { if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "string"))) { return false; } switch (current) { // UTF-8 string (0x00..0x17 bytes follow) case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: case 0x68: case 0x69: case 0x6A: case 0x6B: case 0x6C: case 0x6D: case 0x6E: case 0x6F: case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: { return get_string(input_format_t::cbor, static_cast<unsigned int>(current) & 0x1Fu, result); } case 0x78: // UTF-8 string (one-byte uint8_t for n follows) { std::uint8_t len{}; return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); } case 0x79: // UTF-8 string (two-byte uint16_t for n follow) { std::uint16_t len{}; return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); } case 0x7A: // UTF-8 string (four-byte uint32_t for n follow) { std::uint32_t len{}; return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); } case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow) { std::uint64_t len{}; return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); } case 0x7F: // UTF-8 string (indefinite length) { while (get() != 0xFF) { string_t chunk; if (!get_cbor_string(chunk)) { return false; } result.append(chunk); } return true; } default: { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::cbor, "expected length specification (0x60-0x7B) or indefinite string type (0x7F); last byte: 0x" + last_token, "string"), BasicJsonType())); } } } /*! @brief reads a CBOR byte array This function first reads starting bytes to determine the expected byte array length and then copies this number of bytes into the byte array. Additionally, CBOR's byte arrays with indefinite lengths are supported. @param[out] result created byte array @return whether byte array creation completed */ bool get_cbor_binary(binary_t& result) { if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "binary"))) { return false; } switch (current) { // Binary data (0x00..0x17 bytes follow) case 0x40: case 0x41: case 0x42: case 0x43: case 0x44: case 0x45: case 0x46: case 0x47: case 0x48: case 0x49: case 0x4A: case 0x4B: case 0x4C: case 0x4D: case 0x4E: case 0x4F: case 0x50: case 0x51: case 0x52: case 0x53: case 0x54: case 0x55: case 0x56: case 0x57: { return get_binary(input_format_t::cbor, static_cast<unsigned int>(current) & 0x1Fu, result); } case 0x58: // Binary data (one-byte uint8_t for n follows) { std::uint8_t len{}; return get_number(input_format_t::cbor, len) && get_binary(input_format_t::cbor, len, result); } case 0x59: // Binary data (two-byte uint16_t for n follow) { std::uint16_t len{}; return get_number(input_format_t::cbor, len) && get_binary(input_format_t::cbor, len, result); } case 0x5A: // Binary data (four-byte uint32_t for n follow) { std::uint32_t len{}; return get_number(input_format_t::cbor, len) && get_binary(input_format_t::cbor, len, result); } case 0x5B: // Binary data (eight-byte uint64_t for n follow) { std::uint64_t len{}; return get_number(input_format_t::cbor, len) && get_binary(input_format_t::cbor, len, result); } case 0x5F: // Binary data (indefinite length) { while (get() != 0xFF) { binary_t chunk; if (!get_cbor_binary(chunk)) { return false; } result.insert(result.end(), chunk.begin(), chunk.end()); } return true; } default: { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::cbor, "expected length specification (0x40-0x5B) or indefinite binary array type (0x5F); last byte: 0x" + last_token, "binary"), BasicJsonType())); } } } /*! @param[in] len the length of the array or std::size_t(-1) for an array of indefinite size @param[in] tag_handler how CBOR tags should be treated @return whether array creation completed */ bool get_cbor_array(const std::size_t len, const cbor_tag_handler_t tag_handler) { if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len))) { return false; } if (len != std::size_t(-1)) { for (std::size_t i = 0; i < len; ++i) { if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler))) { return false; } } } else { while (get() != 0xFF) { if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(false, tag_handler))) { return false; } } } return sax->end_array(); } /*! @param[in] len the length of the object or std::size_t(-1) for an object of indefinite size @param[in] tag_handler how CBOR tags should be treated @return whether object creation completed */ bool get_cbor_object(const std::size_t len, const cbor_tag_handler_t tag_handler) { if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len))) { return false; } if (len != 0) { string_t key; if (len != std::size_t(-1)) { for (std::size_t i = 0; i < len; ++i) { get(); if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key))) { return false; } if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler))) { return false; } key.clear(); } } else { while (get() != 0xFF) { if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key))) { return false; } if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler))) { return false; } key.clear(); } } } return sax->end_object(); } ///////////// // MsgPack // ///////////// /*! @return whether a valid MessagePack value was passed to the SAX parser */ bool parse_msgpack_internal() { switch (get()) { // EOF case std::char_traits<char_type>::eof(): return unexpect_eof(input_format_t::msgpack, "value"); // positive fixint case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: case 0x08: case 0x09: case 0x0A: case 0x0B: case 0x0C: case 0x0D: case 0x0E: case 0x0F: case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17: case 0x18: case 0x19: case 0x1A: case 0x1B: case 0x1C: case 0x1D: case 0x1E: case 0x1F: case 0x20: case 0x21: case 0x22: case 0x23: case 0x24: case 0x25: case 0x26: case 0x27: case 0x28: case 0x29: case 0x2A: case 0x2B: case 0x2C: case 0x2D: case 0x2E: case 0x2F: case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: case 0x3A: case 0x3B: case 0x3C: case 0x3D: case 0x3E: case 0x3F: case 0x40: case 0x41: case 0x42: case 0x43: case 0x44: case 0x45: case 0x46: case 0x47: case 0x48: case 0x49: case 0x4A: case 0x4B: case 0x4C: case 0x4D: case 0x4E: case 0x4F: case 0x50: case 0x51: case 0x52: case 0x53: case 0x54: case 0x55: case 0x56: case 0x57: case 0x58: case 0x59: case 0x5A: case 0x5B: case 0x5C: case 0x5D: case 0x5E: case 0x5F: case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: case 0x68: case 0x69: case 0x6A: case 0x6B: case 0x6C: case 0x6D: case 0x6E: case 0x6F: case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: case 0x78: case 0x79: case 0x7A: case 0x7B: case 0x7C: case 0x7D: case 0x7E: case 0x7F: return sax->number_unsigned(static_cast<number_unsigned_t>(current)); // fixmap case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: case 0x88: case 0x89: case 0x8A: case 0x8B: case 0x8C: case 0x8D: case 0x8E: case 0x8F: return get_msgpack_object(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu)); // fixarray case 0x90: case 0x91: case 0x92: case 0x93: case 0x94: case 0x95: case 0x96: case 0x97: case 0x98: case 0x99: case 0x9A: case 0x9B: case 0x9C: case 0x9D: case 0x9E: case 0x9F: return get_msgpack_array(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu)); // fixstr case 0xA0: case 0xA1: case 0xA2: case 0xA3: case 0xA4: case 0xA5: case 0xA6: case 0xA7: case 0xA8: case 0xA9: case 0xAA: case 0xAB: case 0xAC: case 0xAD: case 0xAE: case 0xAF: case 0xB0: case 0xB1: case 0xB2: case 0xB3: case 0xB4: case 0xB5: case 0xB6: case 0xB7: case 0xB8: case 0xB9: case 0xBA: case 0xBB: case 0xBC: case 0xBD: case 0xBE: case 0xBF: case 0xD9: // str 8 case 0xDA: // str 16 case 0xDB: // str 32 { string_t s; return get_msgpack_string(s) && sax->string(s); } case 0xC0: // nil return sax->null(); case 0xC2: // false return sax->boolean(false); case 0xC3: // true return sax->boolean(true); case 0xC4: // bin 8 case 0xC5: // bin 16 case 0xC6: // bin 32 case 0xC7: // ext 8 case 0xC8: // ext 16 case 0xC9: // ext 32 case 0xD4: // fixext 1 case 0xD5: // fixext 2 case 0xD6: // fixext 4 case 0xD7: // fixext 8 case 0xD8: // fixext 16 { binary_t b; return get_msgpack_binary(b) && sax->binary(b); } case 0xCA: // float 32 { float number{}; return get_number(input_format_t::msgpack, number) && sax->number_float(static_cast<number_float_t>(number), ""); } case 0xCB: // float 64 { double number{}; return get_number(input_format_t::msgpack, number) && sax->number_float(static_cast<number_float_t>(number), ""); } case 0xCC: // uint 8 { std::uint8_t number{}; return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); } case 0xCD: // uint 16 { std::uint16_t number{}; return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); } case 0xCE: // uint 32 { std::uint32_t number{}; return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); } case 0xCF: // uint 64 { std::uint64_t number{}; return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); } case 0xD0: // int 8 { std::int8_t number{}; return get_number(input_format_t::msgpack, number) && sax->number_integer(number); } case 0xD1: // int 16 { std::int16_t number{}; return get_number(input_format_t::msgpack, number) && sax->number_integer(number); } case 0xD2: // int 32 { std::int32_t number{}; return get_number(input_format_t::msgpack, number) && sax->number_integer(number); } case 0xD3: // int 64 { std::int64_t number{}; return get_number(input_format_t::msgpack, number) && sax->number_integer(number); } case 0xDC: // array 16 { std::uint16_t len{}; return get_number(input_format_t::msgpack, len) && get_msgpack_array(static_cast<std::size_t>(len)); } case 0xDD: // array 32 { std::uint32_t len{}; return get_number(input_format_t::msgpack, len) && get_msgpack_array(static_cast<std::size_t>(len)); } case 0xDE: // map 16 { std::uint16_t len{}; return get_number(input_format_t::msgpack, len) && get_msgpack_object(static_cast<std::size_t>(len)); } case 0xDF: // map 32 { std::uint32_t len{}; return get_number(input_format_t::msgpack, len) && get_msgpack_object(static_cast<std::size_t>(len)); } // negative fixint case 0xE0: case 0xE1: case 0xE2: case 0xE3: case 0xE4: case 0xE5: case 0xE6: case 0xE7: case 0xE8: case 0xE9: case 0xEA: case 0xEB: case 0xEC: case 0xED: case 0xEE: case 0xEF: case 0xF0: case 0xF1: case 0xF2: case 0xF3: case 0xF4: case 0xF5: case 0xF6: case 0xF7: case 0xF8: case 0xF9: case 0xFA: case 0xFB: case 0xFC: case 0xFD: case 0xFE: case 0xFF: return sax->number_integer(static_cast<std::int8_t>(current)); default: // anything else { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::msgpack, "invalid byte: 0x" + last_token, "value"), BasicJsonType())); } } } /*! @brief reads a MessagePack string This function first reads starting bytes to determine the expected string length and then copies this number of bytes into a string. @param[out] result created string @return whether string creation completed */ bool get_msgpack_string(string_t& result) { if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::msgpack, "string"))) { return false; } switch (current) { // fixstr case 0xA0: case 0xA1: case 0xA2: case 0xA3: case 0xA4: case 0xA5: case 0xA6: case 0xA7: case 0xA8: case 0xA9: case 0xAA: case 0xAB: case 0xAC: case 0xAD: case 0xAE: case 0xAF: case 0xB0: case 0xB1: case 0xB2: case 0xB3: case 0xB4: case 0xB5: case 0xB6: case 0xB7: case 0xB8: case 0xB9: case 0xBA: case 0xBB: case 0xBC: case 0xBD: case 0xBE: case 0xBF: { return get_string(input_format_t::msgpack, static_cast<unsigned int>(current) & 0x1Fu, result); } case 0xD9: // str 8 { std::uint8_t len{}; return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result); } case 0xDA: // str 16 { std::uint16_t len{}; return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result); } case 0xDB: // str 32 { std::uint32_t len{}; return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result); } default: { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::msgpack, "expected length specification (0xA0-0xBF, 0xD9-0xDB); last byte: 0x" + last_token, "string"), BasicJsonType())); } } } /*! @brief reads a MessagePack byte array This function first reads starting bytes to determine the expected byte array length and then copies this number of bytes into a byte array. @param[out] result created byte array @return whether byte array creation completed */ bool get_msgpack_binary(binary_t& result) { // helper function to set the subtype auto assign_and_return_true = [&result](std::int8_t subtype) { result.set_subtype(static_cast<std::uint8_t>(subtype)); return true; }; switch (current) { case 0xC4: // bin 8 { std::uint8_t len{}; return get_number(input_format_t::msgpack, len) && get_binary(input_format_t::msgpack, len, result); } case 0xC5: // bin 16 { std::uint16_t len{}; return get_number(input_format_t::msgpack, len) && get_binary(input_format_t::msgpack, len, result); } case 0xC6: // bin 32 { std::uint32_t len{}; return get_number(input_format_t::msgpack, len) && get_binary(input_format_t::msgpack, len, result); } case 0xC7: // ext 8 { std::uint8_t len{}; std::int8_t subtype{}; return get_number(input_format_t::msgpack, len) && get_number(input_format_t::msgpack, subtype) && get_binary(input_format_t::msgpack, len, result) && assign_and_return_true(subtype); } case 0xC8: // ext 16 { std::uint16_t len{}; std::int8_t subtype{}; return get_number(input_format_t::msgpack, len) && get_number(input_format_t::msgpack, subtype) && get_binary(input_format_t::msgpack, len, result) && assign_and_return_true(subtype); } case 0xC9: // ext 32 { std::uint32_t len{}; std::int8_t subtype{}; return get_number(input_format_t::msgpack, len) && get_number(input_format_t::msgpack, subtype) && get_binary(input_format_t::msgpack, len, result) && assign_and_return_true(subtype); } case 0xD4: // fixext 1 { std::int8_t subtype{}; return get_number(input_format_t::msgpack, subtype) && get_binary(input_format_t::msgpack, 1, result) && assign_and_return_true(subtype); } case 0xD5: // fixext 2 { std::int8_t subtype{}; return get_number(input_format_t::msgpack, subtype) && get_binary(input_format_t::msgpack, 2, result) && assign_and_return_true(subtype); } case 0xD6: // fixext 4 { std::int8_t subtype{}; return get_number(input_format_t::msgpack, subtype) && get_binary(input_format_t::msgpack, 4, result) && assign_and_return_true(subtype); } case 0xD7: // fixext 8 { std::int8_t subtype{}; return get_number(input_format_t::msgpack, subtype) && get_binary(input_format_t::msgpack, 8, result) && assign_and_return_true(subtype); } case 0xD8: // fixext 16 { std::int8_t subtype{}; return get_number(input_format_t::msgpack, subtype) && get_binary(input_format_t::msgpack, 16, result) && assign_and_return_true(subtype); } default: // LCOV_EXCL_LINE return false; // LCOV_EXCL_LINE } } /*! @param[in] len the length of the array @return whether array creation completed */ bool get_msgpack_array(const std::size_t len) { if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len))) { return false; } for (std::size_t i = 0; i < len; ++i) { if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal())) { return false; } } return sax->end_array(); } /*! @param[in] len the length of the object @return whether object creation completed */ bool get_msgpack_object(const std::size_t len) { if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len))) { return false; } string_t key; for (std::size_t i = 0; i < len; ++i) { get(); if (JSON_HEDLEY_UNLIKELY(!get_msgpack_string(key) || !sax->key(key))) { return false; } if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal())) { return false; } key.clear(); } return sax->end_object(); } //////////// // UBJSON // //////////// /*! @param[in] get_char whether a new character should be retrieved from the input (true, default) or whether the last read character should be considered instead @return whether a valid UBJSON value was passed to the SAX parser */ bool parse_ubjson_internal(const bool get_char = true) { return get_ubjson_value(get_char ? get_ignore_noop() : current); } /*! @brief reads a UBJSON string This function is either called after reading the 'S' byte explicitly indicating a string, or in case of an object key where the 'S' byte can be left out. @param[out] result created string @param[in] get_char whether a new character should be retrieved from the input (true, default) or whether the last read character should be considered instead @return whether string creation completed */ bool get_ubjson_string(string_t& result, const bool get_char = true) { if (get_char) { get(); // TODO(niels): may we ignore N here? } if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "value"))) { return false; } switch (current) { case 'U': { std::uint8_t len{}; return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); } case 'i': { std::int8_t len{}; return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); } case 'I': { std::int16_t len{}; return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); } case 'l': { std::int32_t len{}; return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); } case 'L': { std::int64_t len{}; return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); } default: auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "expected length type specification (U, i, I, l, L); last byte: 0x" + last_token, "string"), BasicJsonType())); } } /*! @param[out] result determined size @return whether size determination completed */ bool get_ubjson_size_value(std::size_t& result) { switch (get_ignore_noop()) { case 'U': { std::uint8_t number{}; if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) { return false; } result = static_cast<std::size_t>(number); return true; } case 'i': { std::int8_t number{}; if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) { return false; } result = static_cast<std::size_t>(number); // NOLINT(bugprone-signed-char-misuse,cert-str34-c): number is not a char return true; } case 'I': { std::int16_t number{}; if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) { return false; } result = static_cast<std::size_t>(number); return true; } case 'l': { std::int32_t number{}; if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) { return false; } result = static_cast<std::size_t>(number); return true; } case 'L': { std::int64_t number{}; if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) { return false; } result = static_cast<std::size_t>(number); return true; } default: { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "expected length type specification (U, i, I, l, L) after '#'; last byte: 0x" + last_token, "size"), BasicJsonType())); } } } /*! @brief determine the type and size for a container In the optimized UBJSON format, a type and a size can be provided to allow for a more compact representation. @param[out] result pair of the size and the type @return whether pair creation completed */ bool get_ubjson_size_type(std::pair<std::size_t, char_int_type>& result) { result.first = string_t::npos; // size result.second = 0; // type get_ignore_noop(); if (current == '$') { result.second = get(); // must not ignore 'N', because 'N' maybe the type if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "type"))) { return false; } get_ignore_noop(); if (JSON_HEDLEY_UNLIKELY(current != '#')) { if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "value"))) { return false; } auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::ubjson, "expected '#' after type information; last byte: 0x" + last_token, "size"), BasicJsonType())); } return get_ubjson_size_value(result.first); } if (current == '#') { return get_ubjson_size_value(result.first); } return true; } /*! @param prefix the previously read or set type prefix @return whether value creation completed */ bool get_ubjson_value(const char_int_type prefix) { switch (prefix) { case std::char_traits<char_type>::eof(): // EOF return unexpect_eof(input_format_t::ubjson, "value"); case 'T': // true return sax->boolean(true); case 'F': // false return sax->boolean(false); case 'Z': // null return sax->null(); case 'U': { std::uint8_t number{}; return get_number(input_format_t::ubjson, number) && sax->number_unsigned(number); } case 'i': { std::int8_t number{}; return get_number(input_format_t::ubjson, number) && sax->number_integer(number); } case 'I': { std::int16_t number{}; return get_number(input_format_t::ubjson, number) && sax->number_integer(number); } case 'l': { std::int32_t number{}; return get_number(input_format_t::ubjson, number) && sax->number_integer(number); } case 'L': { std::int64_t number{}; return get_number(input_format_t::ubjson, number) && sax->number_integer(number); } case 'd': { float number{}; return get_number(input_format_t::ubjson, number) && sax->number_float(static_cast<number_float_t>(number), ""); } case 'D': { double number{}; return get_number(input_format_t::ubjson, number) && sax->number_float(static_cast<number_float_t>(number), ""); } case 'H': { return get_ubjson_high_precision_number(); } case 'C': // char { get(); if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "char"))) { return false; } if (JSON_HEDLEY_UNLIKELY(current > 127)) { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "byte after 'C' must be in range 0x00..0x7F; last byte: 0x" + last_token, "char"), BasicJsonType())); } string_t s(1, static_cast<typename string_t::value_type>(current)); return sax->string(s); } case 'S': // string { string_t s; return get_ubjson_string(s) && sax->string(s); } case '[': // array return get_ubjson_array(); case '{': // object return get_ubjson_object(); default: // anything else { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::ubjson, "invalid byte: 0x" + last_token, "value"), BasicJsonType())); } } } /*! @return whether array creation completed */ bool get_ubjson_array() { std::pair<std::size_t, char_int_type> size_and_type; if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type))) { return false; } if (size_and_type.first != string_t::npos) { if (JSON_HEDLEY_UNLIKELY(!sax->start_array(size_and_type.first))) { return false; } if (size_and_type.second != 0) { if (size_and_type.second != 'N') { for (std::size_t i = 0; i < size_and_type.first; ++i) { if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second))) { return false; } } } } else { for (std::size_t i = 0; i < size_and_type.first; ++i) { if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal())) { return false; } } } } else { if (JSON_HEDLEY_UNLIKELY(!sax->start_array(std::size_t(-1)))) { return false; } while (current != ']') { if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal(false))) { return false; } get_ignore_noop(); } } return sax->end_array(); } /*! @return whether object creation completed */ bool get_ubjson_object() { std::pair<std::size_t, char_int_type> size_and_type; if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type))) { return false; } string_t key; if (size_and_type.first != string_t::npos) { if (JSON_HEDLEY_UNLIKELY(!sax->start_object(size_and_type.first))) { return false; } if (size_and_type.second != 0) { for (std::size_t i = 0; i < size_and_type.first; ++i) { if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key))) { return false; } if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second))) { return false; } key.clear(); } } else { for (std::size_t i = 0; i < size_and_type.first; ++i) { if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key))) { return false; } if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal())) { return false; } key.clear(); } } } else { if (JSON_HEDLEY_UNLIKELY(!sax->start_object(std::size_t(-1)))) { return false; } while (current != '}') { if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key, false) || !sax->key(key))) { return false; } if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal())) { return false; } get_ignore_noop(); key.clear(); } } return sax->end_object(); } // Note, no reader for UBJSON binary types is implemented because they do // not exist bool get_ubjson_high_precision_number() { // get size of following number string std::size_t size{}; auto res = get_ubjson_size_value(size); if (JSON_HEDLEY_UNLIKELY(!res)) { return res; } // get number string std::vector<char> number_vector; for (std::size_t i = 0; i < size; ++i) { get(); if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "number"))) { return false; } number_vector.push_back(static_cast<char>(current)); } // parse number string using ia_type = decltype(detail::input_adapter(number_vector)); auto number_lexer = detail::lexer<BasicJsonType, ia_type>(detail::input_adapter(number_vector), false); const auto result_number = number_lexer.scan(); const auto number_string = number_lexer.get_token_string(); const auto result_remainder = number_lexer.scan(); using token_type = typename detail::lexer_base<BasicJsonType>::token_type; if (JSON_HEDLEY_UNLIKELY(result_remainder != token_type::end_of_input)) { return sax->parse_error(chars_read, number_string, parse_error::create(115, chars_read, exception_message(input_format_t::ubjson, "invalid number text: " + number_lexer.get_token_string(), "high-precision number"), BasicJsonType())); } switch (result_number) { case token_type::value_integer: return sax->number_integer(number_lexer.get_number_integer()); case token_type::value_unsigned: return sax->number_unsigned(number_lexer.get_number_unsigned()); case token_type::value_float: return sax->number_float(number_lexer.get_number_float(), std::move(number_string)); default: return sax->parse_error(chars_read, number_string, parse_error::create(115, chars_read, exception_message(input_format_t::ubjson, "invalid number text: " + number_lexer.get_token_string(), "high-precision number"), BasicJsonType())); } } /////////////////////// // Utility functions // /////////////////////// /*! @brief get next character from the input This function provides the interface to the used input adapter. It does not throw in case the input reached EOF, but returns a -'ve valued `std::char_traits<char_type>::eof()` in that case. @return character read from the input */ char_int_type get() { ++chars_read; return current = ia.get_character(); } /*! @return character read from the input after ignoring all 'N' entries */ char_int_type get_ignore_noop() { do { get(); } while (current == 'N'); return current; } /* @brief read a number from the input @tparam NumberType the type of the number @param[in] format the current format (for diagnostics) @param[out] result number of type @a NumberType @return whether conversion completed @note This function needs to respect the system's endianess, because bytes in CBOR, MessagePack, and UBJSON are stored in network order (big endian) and therefore need reordering on little endian systems. */ template<typename NumberType, bool InputIsLittleEndian = false> bool get_number(const input_format_t format, NumberType& result) { // step 1: read input into array with system's byte order std::array<std::uint8_t, sizeof(NumberType)> vec{}; for (std::size_t i = 0; i < sizeof(NumberType); ++i) { get(); if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "number"))) { return false; } // reverse byte order prior to conversion if necessary if (is_little_endian != InputIsLittleEndian) { vec[sizeof(NumberType) - i - 1] = static_cast<std::uint8_t>(current); } else { vec[i] = static_cast<std::uint8_t>(current); // LCOV_EXCL_LINE } } // step 2: convert array into number of type T and return std::memcpy(&result, vec.data(), sizeof(NumberType)); return true; } /*! @brief create a string by reading characters from the input @tparam NumberType the type of the number @param[in] format the current format (for diagnostics) @param[in] len number of characters to read @param[out] result string created by reading @a len bytes @return whether string creation completed @note We can not reserve @a len bytes for the result, because @a len may be too large. Usually, @ref unexpect_eof() detects the end of the input before we run out of string memory. */ template<typename NumberType> bool get_string(const input_format_t format, const NumberType len, string_t& result) { bool success = true; for (NumberType i = 0; i < len; i++) { get(); if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "string"))) { success = false; break; } result.push_back(static_cast<typename string_t::value_type>(current)); } return success; } /*! @brief create a byte array by reading bytes from the input @tparam NumberType the type of the number @param[in] format the current format (for diagnostics) @param[in] len number of bytes to read @param[out] result byte array created by reading @a len bytes @return whether byte array creation completed @note We can not reserve @a len bytes for the result, because @a len may be too large. Usually, @ref unexpect_eof() detects the end of the input before we run out of memory. */ template<typename NumberType> bool get_binary(const input_format_t format, const NumberType len, binary_t& result) { bool success = true; for (NumberType i = 0; i < len; i++) { get(); if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "binary"))) { success = false; break; } result.push_back(static_cast<std::uint8_t>(current)); } return success; } /*! @param[in] format the current format (for diagnostics) @param[in] context further context information (for diagnostics) @return whether the last read character is not EOF */ JSON_HEDLEY_NON_NULL(3) bool unexpect_eof(const input_format_t format, const char* context) const { if (JSON_HEDLEY_UNLIKELY(current == std::char_traits<char_type>::eof())) { return sax->parse_error(chars_read, "<end of file>", parse_error::create(110, chars_read, exception_message(format, "unexpected end of input", context), BasicJsonType())); } return true; } /*! @return a string representation of the last read byte */ std::string get_token_string() const { std::array<char, 3> cr{{}}; (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast<unsigned char>(current)); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) return std::string{cr.data()}; } /*! @param[in] format the current format @param[in] detail a detailed error message @param[in] context further context information @return a message string to use in the parse_error exceptions */ std::string exception_message(const input_format_t format, const std::string& detail, const std::string& context) const { std::string error_msg = "syntax error while parsing "; switch (format) { case input_format_t::cbor: error_msg += "CBOR"; break; case input_format_t::msgpack: error_msg += "MessagePack"; break; case input_format_t::ubjson: error_msg += "UBJSON"; break; case input_format_t::bson: error_msg += "BSON"; break; default: // LCOV_EXCL_LINE JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE } return error_msg + " " + context + ": " + detail; } private: /// input adapter InputAdapterType ia; /// the current character char_int_type current = std::char_traits<char_type>::eof(); /// the number of characters read std::size_t chars_read = 0; /// whether we can assume little endianess const bool is_little_endian = little_endianess(); /// the SAX parser json_sax_t* sax = nullptr; }; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/input/input_adapters.hpp> // #include <nlohmann/detail/input/lexer.hpp> // #include <nlohmann/detail/input/parser.hpp> #include <cmath> // isfinite #include <cstdint> // uint8_t #include <functional> // function #include <string> // string #include <utility> // move #include <vector> // vector // #include <nlohmann/detail/exceptions.hpp> // #include <nlohmann/detail/input/input_adapters.hpp> // #include <nlohmann/detail/input/json_sax.hpp> // #include <nlohmann/detail/input/lexer.hpp> // #include <nlohmann/detail/macro_scope.hpp> // #include <nlohmann/detail/meta/is_sax.hpp> // #include <nlohmann/detail/value_t.hpp> namespace nlohmann { namespace detail { //////////// // parser // //////////// enum class parse_event_t : uint8_t { /// the parser read `{` and started to process a JSON object object_start, /// the parser read `}` and finished processing a JSON object object_end, /// the parser read `[` and started to process a JSON array array_start, /// the parser read `]` and finished processing a JSON array array_end, /// the parser read a key of a value in an object key, /// the parser finished reading a JSON value value }; template<typename BasicJsonType> using parser_callback_t = std::function<bool(int /*depth*/, parse_event_t /*event*/, BasicJsonType& /*parsed*/)>; /*! @brief syntax analysis This class implements a recursive descent parser. */ template<typename BasicJsonType, typename InputAdapterType> class parser { using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using lexer_t = lexer<BasicJsonType, InputAdapterType>; using token_type = typename lexer_t::token_type; public: /// a parser reading from an input adapter explicit parser(InputAdapterType&& adapter, const parser_callback_t<BasicJsonType> cb = nullptr, const bool allow_exceptions_ = true, const bool skip_comments = false) : callback(cb) , m_lexer(std::move(adapter), skip_comments) , allow_exceptions(allow_exceptions_) { // read first token get_token(); } /*! @brief public parser interface @param[in] strict whether to expect the last token to be EOF @param[in,out] result parsed JSON value @throw parse_error.101 in case of an unexpected token @throw parse_error.102 if to_unicode fails or surrogate error @throw parse_error.103 if to_unicode fails */ void parse(const bool strict, BasicJsonType& result) { if (callback) { json_sax_dom_callback_parser<BasicJsonType> sdp(result, callback, allow_exceptions); sax_parse_internal(&sdp); // in strict mode, input must be completely read if (strict && (get_token() != token_type::end_of_input)) { sdp.parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"), BasicJsonType())); } // in case of an error, return discarded value if (sdp.is_errored()) { result = value_t::discarded; return; } // set top-level value to null if it was discarded by the callback // function if (result.is_discarded()) { result = nullptr; } } else { json_sax_dom_parser<BasicJsonType> sdp(result, allow_exceptions); sax_parse_internal(&sdp); // in strict mode, input must be completely read if (strict && (get_token() != token_type::end_of_input)) { sdp.parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"), BasicJsonType())); } // in case of an error, return discarded value if (sdp.is_errored()) { result = value_t::discarded; return; } } result.assert_invariant(); } /*! @brief public accept interface @param[in] strict whether to expect the last token to be EOF @return whether the input is a proper JSON text */ bool accept(const bool strict = true) { json_sax_acceptor<BasicJsonType> sax_acceptor; return sax_parse(&sax_acceptor, strict); } template<typename SAX> JSON_HEDLEY_NON_NULL(2) bool sax_parse(SAX* sax, const bool strict = true) { (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {}; const bool result = sax_parse_internal(sax); // strict mode: next byte must be EOF if (result && strict && (get_token() != token_type::end_of_input)) { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"), BasicJsonType())); } return result; } private: template<typename SAX> JSON_HEDLEY_NON_NULL(2) bool sax_parse_internal(SAX* sax) { // stack to remember the hierarchy of structured values we are parsing // true = array; false = object std::vector<bool> states; // value to avoid a goto (see comment where set to true) bool skip_to_state_evaluation = false; while (true) { if (!skip_to_state_evaluation) { // invariant: get_token() was called before each iteration switch (last_token) { case token_type::begin_object: { if (JSON_HEDLEY_UNLIKELY(!sax->start_object(std::size_t(-1)))) { return false; } // closing } -> we are done if (get_token() == token_type::end_object) { if (JSON_HEDLEY_UNLIKELY(!sax->end_object())) { return false; } break; } // parse key if (JSON_HEDLEY_UNLIKELY(last_token != token_type::value_string)) { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::value_string, "object key"), BasicJsonType())); } if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string()))) { return false; } // parse separator (:) if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator)) { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::name_separator, "object separator"), BasicJsonType())); } // remember we are now inside an object states.push_back(false); // parse values get_token(); continue; } case token_type::begin_array: { if (JSON_HEDLEY_UNLIKELY(!sax->start_array(std::size_t(-1)))) { return false; } // closing ] -> we are done if (get_token() == token_type::end_array) { if (JSON_HEDLEY_UNLIKELY(!sax->end_array())) { return false; } break; } // remember we are now inside an array states.push_back(true); // parse values (no need to call get_token) continue; } case token_type::value_float: { const auto res = m_lexer.get_number_float(); if (JSON_HEDLEY_UNLIKELY(!std::isfinite(res))) { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), out_of_range::create(406, "number overflow parsing '" + m_lexer.get_token_string() + "'", BasicJsonType())); } if (JSON_HEDLEY_UNLIKELY(!sax->number_float(res, m_lexer.get_string()))) { return false; } break; } case token_type::literal_false: { if (JSON_HEDLEY_UNLIKELY(!sax->boolean(false))) { return false; } break; } case token_type::literal_null: { if (JSON_HEDLEY_UNLIKELY(!sax->null())) { return false; } break; } case token_type::literal_true: { if (JSON_HEDLEY_UNLIKELY(!sax->boolean(true))) { return false; } break; } case token_type::value_integer: { if (JSON_HEDLEY_UNLIKELY(!sax->number_integer(m_lexer.get_number_integer()))) { return false; } break; } case token_type::value_string: { if (JSON_HEDLEY_UNLIKELY(!sax->string(m_lexer.get_string()))) { return false; } break; } case token_type::value_unsigned: { if (JSON_HEDLEY_UNLIKELY(!sax->number_unsigned(m_lexer.get_number_unsigned()))) { return false; } break; } case token_type::parse_error: { // using "uninitialized" to avoid "expected" message return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::uninitialized, "value"), BasicJsonType())); } default: // the last token was unexpected { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::literal_or_value, "value"), BasicJsonType())); } } } else { skip_to_state_evaluation = false; } // we reached this line after we successfully parsed a value if (states.empty()) { // empty stack: we reached the end of the hierarchy: done return true; } if (states.back()) // array { // comma -> next value if (get_token() == token_type::value_separator) { // parse a new value get_token(); continue; } // closing ] if (JSON_HEDLEY_LIKELY(last_token == token_type::end_array)) { if (JSON_HEDLEY_UNLIKELY(!sax->end_array())) { return false; } // We are done with this array. Before we can parse a // new value, we need to evaluate the new state first. // By setting skip_to_state_evaluation to false, we // are effectively jumping to the beginning of this if. JSON_ASSERT(!states.empty()); states.pop_back(); skip_to_state_evaluation = true; continue; } return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_array, "array"), BasicJsonType())); } // states.back() is false -> object // comma -> next value if (get_token() == token_type::value_separator) { // parse key if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::value_string)) { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::value_string, "object key"), BasicJsonType())); } if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string()))) { return false; } // parse separator (:) if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator)) { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::name_separator, "object separator"), BasicJsonType())); } // parse values get_token(); continue; } // closing } if (JSON_HEDLEY_LIKELY(last_token == token_type::end_object)) { if (JSON_HEDLEY_UNLIKELY(!sax->end_object())) { return false; } // We are done with this object. Before we can parse a // new value, we need to evaluate the new state first. // By setting skip_to_state_evaluation to false, we // are effectively jumping to the beginning of this if. JSON_ASSERT(!states.empty()); states.pop_back(); skip_to_state_evaluation = true; continue; } return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_object, "object"), BasicJsonType())); } } /// get next token from lexer token_type get_token() { return last_token = m_lexer.scan(); } std::string exception_message(const token_type expected, const std::string& context) { std::string error_msg = "syntax error "; if (!context.empty()) { error_msg += "while parsing " + context + " "; } error_msg += "- "; if (last_token == token_type::parse_error) { error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" + m_lexer.get_token_string() + "'"; } else { error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token)); } if (expected != token_type::uninitialized) { error_msg += "; expected " + std::string(lexer_t::token_type_name(expected)); } return error_msg; } private: /// callback function const parser_callback_t<BasicJsonType> callback = nullptr; /// the type of the last read token token_type last_token = token_type::uninitialized; /// the lexer lexer_t m_lexer; /// whether to throw exceptions in case of errors const bool allow_exceptions = true; }; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/iterators/internal_iterator.hpp> // #include <nlohmann/detail/iterators/primitive_iterator.hpp> #include <cstddef> // ptrdiff_t #include <limits> // numeric_limits // #include <nlohmann/detail/macro_scope.hpp> namespace nlohmann { namespace detail { /* @brief an iterator for primitive JSON types This class models an iterator for primitive JSON types (boolean, number, string). It's only purpose is to allow the iterator/const_iterator classes to "iterate" over primitive values. Internally, the iterator is modeled by a `difference_type` variable. Value begin_value (`0`) models the begin, end_value (`1`) models past the end. */ class primitive_iterator_t { private: using difference_type = std::ptrdiff_t; static constexpr difference_type begin_value = 0; static constexpr difference_type end_value = begin_value + 1; JSON_PRIVATE_UNLESS_TESTED: /// iterator as signed integer type difference_type m_it = (std::numeric_limits<std::ptrdiff_t>::min)(); public: constexpr difference_type get_value() const noexcept { return m_it; } /// set iterator to a defined beginning void set_begin() noexcept { m_it = begin_value; } /// set iterator to a defined past the end void set_end() noexcept { m_it = end_value; } /// return whether the iterator can be dereferenced constexpr bool is_begin() const noexcept { return m_it == begin_value; } /// return whether the iterator is at end constexpr bool is_end() const noexcept { return m_it == end_value; } friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept { return lhs.m_it == rhs.m_it; } friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept { return lhs.m_it < rhs.m_it; } primitive_iterator_t operator+(difference_type n) noexcept { auto result = *this; result += n; return result; } friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept { return lhs.m_it - rhs.m_it; } primitive_iterator_t& operator++() noexcept { ++m_it; return *this; } primitive_iterator_t const operator++(int) noexcept // NOLINT(readability-const-return-type) { auto result = *this; ++m_it; return result; } primitive_iterator_t& operator--() noexcept { --m_it; return *this; } primitive_iterator_t const operator--(int) noexcept // NOLINT(readability-const-return-type) { auto result = *this; --m_it; return result; } primitive_iterator_t& operator+=(difference_type n) noexcept { m_it += n; return *this; } primitive_iterator_t& operator-=(difference_type n) noexcept { m_it -= n; return *this; } }; } // namespace detail } // namespace nlohmann namespace nlohmann { namespace detail { /*! @brief an iterator value @note This structure could easily be a union, but MSVC currently does not allow unions members with complex constructors, see https://github.com/nlohmann/json/pull/105. */ template<typename BasicJsonType> struct internal_iterator { /// iterator for JSON objects typename BasicJsonType::object_t::iterator object_iterator {}; /// iterator for JSON arrays typename BasicJsonType::array_t::iterator array_iterator {}; /// generic iterator for all other types primitive_iterator_t primitive_iterator {}; }; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/iterators/iter_impl.hpp> #include <iterator> // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next #include <type_traits> // conditional, is_const, remove_const // #include <nlohmann/detail/exceptions.hpp> // #include <nlohmann/detail/iterators/internal_iterator.hpp> // #include <nlohmann/detail/iterators/primitive_iterator.hpp> // #include <nlohmann/detail/macro_scope.hpp> // #include <nlohmann/detail/meta/cpp_future.hpp> // #include <nlohmann/detail/meta/type_traits.hpp> // #include <nlohmann/detail/value_t.hpp> namespace nlohmann { namespace detail { // forward declare, to be able to friend it later on template<typename IteratorType> class iteration_proxy; template<typename IteratorType> class iteration_proxy_value; /*! @brief a template for a bidirectional iterator for the @ref basic_json class This class implements a both iterators (iterator and const_iterator) for the @ref basic_json class. @note An iterator is called *initialized* when a pointer to a JSON value has been set (e.g., by a constructor or a copy assignment). If the iterator is default-constructed, it is *uninitialized* and most methods are undefined. **The library uses assertions to detect calls on uninitialized iterators.** @requirement The class satisfies the following concept requirements: - [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator): The iterator that can be moved can be moved in both directions (i.e. incremented and decremented). @since version 1.0.0, simplified in version 2.0.9, change to bidirectional iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593) */ template<typename BasicJsonType> class iter_impl { /// the iterator with BasicJsonType of different const-ness using other_iter_impl = iter_impl<typename std::conditional<std::is_const<BasicJsonType>::value, typename std::remove_const<BasicJsonType>::type, const BasicJsonType>::type>; /// allow basic_json to access private members friend other_iter_impl; friend BasicJsonType; friend iteration_proxy<iter_impl>; friend iteration_proxy_value<iter_impl>; using object_t = typename BasicJsonType::object_t; using array_t = typename BasicJsonType::array_t; // make sure BasicJsonType is basic_json or const basic_json static_assert(is_basic_json<typename std::remove_const<BasicJsonType>::type>::value, "iter_impl only accepts (const) basic_json"); public: /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17. /// The C++ Standard has never required user-defined iterators to derive from std::iterator. /// A user-defined iterator should provide publicly accessible typedefs named /// iterator_category, value_type, difference_type, pointer, and reference. /// Note that value_type is required to be non-const, even for constant iterators. using iterator_category = std::bidirectional_iterator_tag; /// the type of the values when the iterator is dereferenced using value_type = typename BasicJsonType::value_type; /// a type to represent differences between iterators using difference_type = typename BasicJsonType::difference_type; /// defines a pointer to the type iterated over (value_type) using pointer = typename std::conditional<std::is_const<BasicJsonType>::value, typename BasicJsonType::const_pointer, typename BasicJsonType::pointer>::type; /// defines a reference to the type iterated over (value_type) using reference = typename std::conditional<std::is_const<BasicJsonType>::value, typename BasicJsonType::const_reference, typename BasicJsonType::reference>::type; iter_impl() = default; ~iter_impl() = default; iter_impl(iter_impl&&) noexcept = default; iter_impl& operator=(iter_impl&&) noexcept = default; /*! @brief constructor for a given JSON instance @param[in] object pointer to a JSON object for this iterator @pre object != nullptr @post The iterator is initialized; i.e. `m_object != nullptr`. */ explicit iter_impl(pointer object) noexcept : m_object(object) { JSON_ASSERT(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { m_it.object_iterator = typename object_t::iterator(); break; } case value_t::array: { m_it.array_iterator = typename array_t::iterator(); break; } default: { m_it.primitive_iterator = primitive_iterator_t(); break; } } } /*! @note The conventional copy constructor and copy assignment are implicitly defined. Combined with the following converting constructor and assignment, they support: (1) copy from iterator to iterator, (2) copy from const iterator to const iterator, and (3) conversion from iterator to const iterator. However conversion from const iterator to iterator is not defined. */ /*! @brief const copy constructor @param[in] other const iterator to copy from @note This copy constructor had to be defined explicitly to circumvent a bug occurring on msvc v19.0 compiler (VS 2015) debug build. For more information refer to: https://github.com/nlohmann/json/issues/1608 */ iter_impl(const iter_impl<const BasicJsonType>& other) noexcept : m_object(other.m_object), m_it(other.m_it) {} /*! @brief converting assignment @param[in] other const iterator to copy from @return const/non-const iterator @note It is not checked whether @a other is initialized. */ iter_impl& operator=(const iter_impl<const BasicJsonType>& other) noexcept { if (&other != this) { m_object = other.m_object; m_it = other.m_it; } return *this; } /*! @brief converting constructor @param[in] other non-const iterator to copy from @note It is not checked whether @a other is initialized. */ iter_impl(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept : m_object(other.m_object), m_it(other.m_it) {} /*! @brief converting assignment @param[in] other non-const iterator to copy from @return const/non-const iterator @note It is not checked whether @a other is initialized. */ iter_impl& operator=(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept // NOLINT(cert-oop54-cpp) { m_object = other.m_object; m_it = other.m_it; return *this; } JSON_PRIVATE_UNLESS_TESTED: /*! @brief set the iterator to the first value @pre The iterator is initialized; i.e. `m_object != nullptr`. */ void set_begin() noexcept { JSON_ASSERT(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { m_it.object_iterator = m_object->m_value.object->begin(); break; } case value_t::array: { m_it.array_iterator = m_object->m_value.array->begin(); break; } case value_t::null: { // set to end so begin()==end() is true: null is empty m_it.primitive_iterator.set_end(); break; } default: { m_it.primitive_iterator.set_begin(); break; } } } /*! @brief set the iterator past the last value @pre The iterator is initialized; i.e. `m_object != nullptr`. */ void set_end() noexcept { JSON_ASSERT(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { m_it.object_iterator = m_object->m_value.object->end(); break; } case value_t::array: { m_it.array_iterator = m_object->m_value.array->end(); break; } default: { m_it.primitive_iterator.set_end(); break; } } } public: /*! @brief return a reference to the value pointed to by the iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ reference operator*() const { JSON_ASSERT(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { JSON_ASSERT(m_it.object_iterator != m_object->m_value.object->end()); return m_it.object_iterator->second; } case value_t::array: { JSON_ASSERT(m_it.array_iterator != m_object->m_value.array->end()); return *m_it.array_iterator; } case value_t::null: JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object)); default: { if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin())) { return *m_object; } JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object)); } } } /*! @brief dereference the iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ pointer operator->() const { JSON_ASSERT(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { JSON_ASSERT(m_it.object_iterator != m_object->m_value.object->end()); return &(m_it.object_iterator->second); } case value_t::array: { JSON_ASSERT(m_it.array_iterator != m_object->m_value.array->end()); return &*m_it.array_iterator; } default: { if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin())) { return m_object; } JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object)); } } } /*! @brief post-increment (it++) @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl const operator++(int) // NOLINT(readability-const-return-type) { auto result = *this; ++(*this); return result; } /*! @brief pre-increment (++it) @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl& operator++() { JSON_ASSERT(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { std::advance(m_it.object_iterator, 1); break; } case value_t::array: { std::advance(m_it.array_iterator, 1); break; } default: { ++m_it.primitive_iterator; break; } } return *this; } /*! @brief post-decrement (it--) @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl const operator--(int) // NOLINT(readability-const-return-type) { auto result = *this; --(*this); return result; } /*! @brief pre-decrement (--it) @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl& operator--() { JSON_ASSERT(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { std::advance(m_it.object_iterator, -1); break; } case value_t::array: { std::advance(m_it.array_iterator, -1); break; } default: { --m_it.primitive_iterator; break; } } return *this; } /*! @brief comparison: equal @pre The iterator is initialized; i.e. `m_object != nullptr`. */ template < typename IterImpl, detail::enable_if_t < (std::is_same<IterImpl, iter_impl>::value || std::is_same<IterImpl, other_iter_impl>::value), std::nullptr_t > = nullptr > bool operator==(const IterImpl& other) const { // if objects are not the same, the comparison is undefined if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object)) { JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers", *m_object)); } JSON_ASSERT(m_object != nullptr); switch (m_object->m_type) { case value_t::object: return (m_it.object_iterator == other.m_it.object_iterator); case value_t::array: return (m_it.array_iterator == other.m_it.array_iterator); default: return (m_it.primitive_iterator == other.m_it.primitive_iterator); } } /*! @brief comparison: not equal @pre The iterator is initialized; i.e. `m_object != nullptr`. */ template < typename IterImpl, detail::enable_if_t < (std::is_same<IterImpl, iter_impl>::value || std::is_same<IterImpl, other_iter_impl>::value), std::nullptr_t > = nullptr > bool operator!=(const IterImpl& other) const { return !operator==(other); } /*! @brief comparison: smaller @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator<(const iter_impl& other) const { // if objects are not the same, the comparison is undefined if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object)) { JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers", *m_object)); } JSON_ASSERT(m_object != nullptr); switch (m_object->m_type) { case value_t::object: JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators", *m_object)); case value_t::array: return (m_it.array_iterator < other.m_it.array_iterator); default: return (m_it.primitive_iterator < other.m_it.primitive_iterator); } } /*! @brief comparison: less than or equal @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator<=(const iter_impl& other) const { return !other.operator < (*this); } /*! @brief comparison: greater than @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator>(const iter_impl& other) const { return !operator<=(other); } /*! @brief comparison: greater than or equal @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator>=(const iter_impl& other) const { return !operator<(other); } /*! @brief add to iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl& operator+=(difference_type i) { JSON_ASSERT(m_object != nullptr); switch (m_object->m_type) { case value_t::object: JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators", *m_object)); case value_t::array: { std::advance(m_it.array_iterator, i); break; } default: { m_it.primitive_iterator += i; break; } } return *this; } /*! @brief subtract from iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl& operator-=(difference_type i) { return operator+=(-i); } /*! @brief add to iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl operator+(difference_type i) const { auto result = *this; result += i; return result; } /*! @brief addition of distance and iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ friend iter_impl operator+(difference_type i, const iter_impl& it) { auto result = it; result += i; return result; } /*! @brief subtract from iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl operator-(difference_type i) const { auto result = *this; result -= i; return result; } /*! @brief return difference @pre The iterator is initialized; i.e. `m_object != nullptr`. */ difference_type operator-(const iter_impl& other) const { JSON_ASSERT(m_object != nullptr); switch (m_object->m_type) { case value_t::object: JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators", *m_object)); case value_t::array: return m_it.array_iterator - other.m_it.array_iterator; default: return m_it.primitive_iterator - other.m_it.primitive_iterator; } } /*! @brief access to successor @pre The iterator is initialized; i.e. `m_object != nullptr`. */ reference operator[](difference_type n) const { JSON_ASSERT(m_object != nullptr); switch (m_object->m_type) { case value_t::object: JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators", *m_object)); case value_t::array: return *std::next(m_it.array_iterator, n); case value_t::null: JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object)); default: { if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.get_value() == -n)) { return *m_object; } JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object)); } } } /*! @brief return the key of an object iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ const typename object_t::key_type& key() const { JSON_ASSERT(m_object != nullptr); if (JSON_HEDLEY_LIKELY(m_object->is_object())) { return m_it.object_iterator->first; } JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators", *m_object)); } /*! @brief return the value of an iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ reference value() const { return operator*(); } JSON_PRIVATE_UNLESS_TESTED: /// associated JSON instance pointer m_object = nullptr; /// the actual iterator of the associated instance internal_iterator<typename std::remove_const<BasicJsonType>::type> m_it {}; }; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/iterators/iteration_proxy.hpp> // #include <nlohmann/detail/iterators/json_reverse_iterator.hpp> #include <cstddef> // ptrdiff_t #include <iterator> // reverse_iterator #include <utility> // declval namespace nlohmann { namespace detail { ////////////////////// // reverse_iterator // ////////////////////// /*! @brief a template for a reverse iterator class @tparam Base the base iterator type to reverse. Valid types are @ref iterator (to create @ref reverse_iterator) and @ref const_iterator (to create @ref const_reverse_iterator). @requirement The class satisfies the following concept requirements: - [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator): The iterator that can be moved can be moved in both directions (i.e. incremented and decremented). - [OutputIterator](https://en.cppreference.com/w/cpp/named_req/OutputIterator): It is possible to write to the pointed-to element (only if @a Base is @ref iterator). @since version 1.0.0 */ template<typename Base> class json_reverse_iterator : public std::reverse_iterator<Base> { public: using difference_type = std::ptrdiff_t; /// shortcut to the reverse iterator adapter using base_iterator = std::reverse_iterator<Base>; /// the reference type for the pointed-to element using reference = typename Base::reference; /// create reverse iterator from iterator explicit json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept : base_iterator(it) {} /// create reverse iterator from base class explicit json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {} /// post-increment (it++) json_reverse_iterator const operator++(int) // NOLINT(readability-const-return-type) { return static_cast<json_reverse_iterator>(base_iterator::operator++(1)); } /// pre-increment (++it) json_reverse_iterator& operator++() { return static_cast<json_reverse_iterator&>(base_iterator::operator++()); } /// post-decrement (it--) json_reverse_iterator const operator--(int) // NOLINT(readability-const-return-type) { return static_cast<json_reverse_iterator>(base_iterator::operator--(1)); } /// pre-decrement (--it) json_reverse_iterator& operator--() { return static_cast<json_reverse_iterator&>(base_iterator::operator--()); } /// add to iterator json_reverse_iterator& operator+=(difference_type i) { return static_cast<json_reverse_iterator&>(base_iterator::operator+=(i)); } /// add to iterator json_reverse_iterator operator+(difference_type i) const { return static_cast<json_reverse_iterator>(base_iterator::operator+(i)); } /// subtract from iterator json_reverse_iterator operator-(difference_type i) const { return static_cast<json_reverse_iterator>(base_iterator::operator-(i)); } /// return difference difference_type operator-(const json_reverse_iterator& other) const { return base_iterator(*this) - base_iterator(other); } /// access to successor reference operator[](difference_type n) const { return *(this->operator+(n)); } /// return the key of an object iterator auto key() const -> decltype(std::declval<Base>().key()) { auto it = --this->base(); return it.key(); } /// return the value of an iterator reference value() const { auto it = --this->base(); return it.operator * (); } }; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/iterators/primitive_iterator.hpp> // #include <nlohmann/detail/json_pointer.hpp> #include <algorithm> // all_of #include <cctype> // isdigit #include <limits> // max #include <numeric> // accumulate #include <string> // string #include <utility> // move #include <vector> // vector // #include <nlohmann/detail/exceptions.hpp> // #include <nlohmann/detail/macro_scope.hpp> // #include <nlohmann/detail/string_escape.hpp> // #include <nlohmann/detail/value_t.hpp> namespace nlohmann { template<typename BasicJsonType> class json_pointer { // allow basic_json to access private members NLOHMANN_BASIC_JSON_TPL_DECLARATION friend class basic_json; public: /*! @brief create JSON pointer Create a JSON pointer according to the syntax described in [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3). @param[in] s string representing the JSON pointer; if omitted, the empty string is assumed which references the whole JSON value @throw parse_error.107 if the given JSON pointer @a s is nonempty and does not begin with a slash (`/`); see example below @throw parse_error.108 if a tilde (`~`) in the given JSON pointer @a s is not followed by `0` (representing `~`) or `1` (representing `/`); see example below @liveexample{The example shows the construction several valid JSON pointers as well as the exceptional behavior.,json_pointer} @since version 2.0.0 */ explicit json_pointer(const std::string& s = "") : reference_tokens(split(s)) {} /*! @brief return a string representation of the JSON pointer @invariant For each JSON pointer `ptr`, it holds: @code {.cpp} ptr == json_pointer(ptr.to_string()); @endcode @return a string representation of the JSON pointer @liveexample{The example shows the result of `to_string`.,json_pointer__to_string} @since version 2.0.0 */ std::string to_string() const { return std::accumulate(reference_tokens.begin(), reference_tokens.end(), std::string{}, [](const std::string & a, const std::string & b) { return a + "/" + detail::escape(b); }); } /// @copydoc to_string() operator std::string() const { return to_string(); } /*! @brief append another JSON pointer at the end of this JSON pointer @param[in] ptr JSON pointer to append @return JSON pointer with @a ptr appended @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add} @complexity Linear in the length of @a ptr. @sa see @ref operator/=(std::string) to append a reference token @sa see @ref operator/=(std::size_t) to append an array index @sa see @ref operator/(const json_pointer&, const json_pointer&) for a binary operator @since version 3.6.0 */ json_pointer& operator/=(const json_pointer& ptr) { reference_tokens.insert(reference_tokens.end(), ptr.reference_tokens.begin(), ptr.reference_tokens.end()); return *this; } /*! @brief append an unescaped reference token at the end of this JSON pointer @param[in] token reference token to append @return JSON pointer with @a token appended without escaping @a token @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add} @complexity Amortized constant. @sa see @ref operator/=(const json_pointer&) to append a JSON pointer @sa see @ref operator/=(std::size_t) to append an array index @sa see @ref operator/(const json_pointer&, std::size_t) for a binary operator @since version 3.6.0 */ json_pointer& operator/=(std::string token) { push_back(std::move(token)); return *this; } /*! @brief append an array index at the end of this JSON pointer @param[in] array_idx array index to append @return JSON pointer with @a array_idx appended @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add} @complexity Amortized constant. @sa see @ref operator/=(const json_pointer&) to append a JSON pointer @sa see @ref operator/=(std::string) to append a reference token @sa see @ref operator/(const json_pointer&, std::string) for a binary operator @since version 3.6.0 */ json_pointer& operator/=(std::size_t array_idx) { return *this /= std::to_string(array_idx); } /*! @brief create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer @param[in] lhs JSON pointer @param[in] rhs JSON pointer @return a new JSON pointer with @a rhs appended to @a lhs @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary} @complexity Linear in the length of @a lhs and @a rhs. @sa see @ref operator/=(const json_pointer&) to append a JSON pointer @since version 3.6.0 */ friend json_pointer operator/(const json_pointer& lhs, const json_pointer& rhs) { return json_pointer(lhs) /= rhs; } /*! @brief create a new JSON pointer by appending the unescaped token at the end of the JSON pointer @param[in] ptr JSON pointer @param[in] token reference token @return a new JSON pointer with unescaped @a token appended to @a ptr @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary} @complexity Linear in the length of @a ptr. @sa see @ref operator/=(std::string) to append a reference token @since version 3.6.0 */ friend json_pointer operator/(const json_pointer& ptr, std::string token) // NOLINT(performance-unnecessary-value-param) { return json_pointer(ptr) /= std::move(token); } /*! @brief create a new JSON pointer by appending the array-index-token at the end of the JSON pointer @param[in] ptr JSON pointer @param[in] array_idx array index @return a new JSON pointer with @a array_idx appended to @a ptr @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary} @complexity Linear in the length of @a ptr. @sa see @ref operator/=(std::size_t) to append an array index @since version 3.6.0 */ friend json_pointer operator/(const json_pointer& ptr, std::size_t array_idx) { return json_pointer(ptr) /= array_idx; } /*! @brief returns the parent of this JSON pointer @return parent of this JSON pointer; in case this JSON pointer is the root, the root itself is returned @complexity Linear in the length of the JSON pointer. @liveexample{The example shows the result of `parent_pointer` for different JSON Pointers.,json_pointer__parent_pointer} @since version 3.6.0 */ json_pointer parent_pointer() const { if (empty()) { return *this; } json_pointer res = *this; res.pop_back(); return res; } /*! @brief remove last reference token @pre not `empty()` @liveexample{The example shows the usage of `pop_back`.,json_pointer__pop_back} @complexity Constant. @throw out_of_range.405 if JSON pointer has no parent @since version 3.6.0 */ void pop_back() { if (JSON_HEDLEY_UNLIKELY(empty())) { JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType())); } reference_tokens.pop_back(); } /*! @brief return last reference token @pre not `empty()` @return last reference token @liveexample{The example shows the usage of `back`.,json_pointer__back} @complexity Constant. @throw out_of_range.405 if JSON pointer has no parent @since version 3.6.0 */ const std::string& back() const { if (JSON_HEDLEY_UNLIKELY(empty())) { JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType())); } return reference_tokens.back(); } /*! @brief append an unescaped token at the end of the reference pointer @param[in] token token to add @complexity Amortized constant. @liveexample{The example shows the result of `push_back` for different JSON Pointers.,json_pointer__push_back} @since version 3.6.0 */ void push_back(const std::string& token) { reference_tokens.push_back(token); } /// @copydoc push_back(const std::string&) void push_back(std::string&& token) { reference_tokens.push_back(std::move(token)); } /*! @brief return whether pointer points to the root document @return true iff the JSON pointer points to the root document @complexity Constant. @exceptionsafety No-throw guarantee: this function never throws exceptions. @liveexample{The example shows the result of `empty` for different JSON Pointers.,json_pointer__empty} @since version 3.6.0 */ bool empty() const noexcept { return reference_tokens.empty(); } private: /*! @param[in] s reference token to be converted into an array index @return integer representation of @a s @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index begins not with a digit @throw out_of_range.404 if string @a s could not be converted to an integer @throw out_of_range.410 if an array index exceeds size_type */ static typename BasicJsonType::size_type array_index(const std::string& s) { using size_type = typename BasicJsonType::size_type; // error condition (cf. RFC 6901, Sect. 4) if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && s[0] == '0')) { JSON_THROW(detail::parse_error::create(106, 0, "array index '" + s + "' must not begin with '0'", BasicJsonType())); } // error condition (cf. RFC 6901, Sect. 4) if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && !(s[0] >= '1' && s[0] <= '9'))) { JSON_THROW(detail::parse_error::create(109, 0, "array index '" + s + "' is not a number", BasicJsonType())); } std::size_t processed_chars = 0; unsigned long long res = 0; // NOLINT(runtime/int) JSON_TRY { res = std::stoull(s, &processed_chars); } JSON_CATCH(std::out_of_range&) { JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'", BasicJsonType())); } // check if the string was completely read if (JSON_HEDLEY_UNLIKELY(processed_chars != s.size())) { JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'", BasicJsonType())); } // only triggered on special platforms (like 32bit), see also // https://github.com/nlohmann/json/pull/2203 if (res >= static_cast<unsigned long long>((std::numeric_limits<size_type>::max)())) // NOLINT(runtime/int) { JSON_THROW(detail::out_of_range::create(410, "array index " + s + " exceeds size_type", BasicJsonType())); // LCOV_EXCL_LINE } return static_cast<size_type>(res); } JSON_PRIVATE_UNLESS_TESTED: json_pointer top() const { if (JSON_HEDLEY_UNLIKELY(empty())) { JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType())); } json_pointer result = *this; result.reference_tokens = {reference_tokens[0]}; return result; } private: /*! @brief create and return a reference to the pointed to value @complexity Linear in the number of reference tokens. @throw parse_error.109 if array index is not a number @throw type_error.313 if value cannot be unflattened */ BasicJsonType& get_and_create(BasicJsonType& j) const { auto* result = &j; // in case no reference tokens exist, return a reference to the JSON value // j which will be overwritten by a primitive value for (const auto& reference_token : reference_tokens) { switch (result->type()) { case detail::value_t::null: { if (reference_token == "0") { // start a new array if reference token is 0 result = &result->operator[](0); } else { // start a new object otherwise result = &result->operator[](reference_token); } break; } case detail::value_t::object: { // create an entry in the object result = &result->operator[](reference_token); break; } case detail::value_t::array: { // create an entry in the array result = &result->operator[](array_index(reference_token)); break; } /* The following code is only reached if there exists a reference token _and_ the current value is primitive. In this case, we have an error situation, because primitive values may only occur as single value; that is, with an empty list of reference tokens. */ default: JSON_THROW(detail::type_error::create(313, "invalid value to unflatten", j)); } } return *result; } /*! @brief return a reference to the pointed to value @note This version does not throw if a value is not present, but tries to create nested values instead. For instance, calling this function with pointer `"/this/that"` on a null value is equivalent to calling `operator[]("this").operator[]("that")` on that value, effectively changing the null value to an object. @param[in] ptr a JSON value @return reference to the JSON value pointed to by the JSON pointer @complexity Linear in the length of the JSON pointer. @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.404 if the JSON pointer can not be resolved */ BasicJsonType& get_unchecked(BasicJsonType* ptr) const { for (const auto& reference_token : reference_tokens) { // convert null values to arrays or objects before continuing if (ptr->is_null()) { // check if reference token is a number const bool nums = std::all_of(reference_token.begin(), reference_token.end(), [](const unsigned char x) { return std::isdigit(x); }); // change value to array for numbers or "-" or to object otherwise *ptr = (nums || reference_token == "-") ? detail::value_t::array : detail::value_t::object; } switch (ptr->type()) { case detail::value_t::object: { // use unchecked object access ptr = &ptr->operator[](reference_token); break; } case detail::value_t::array: { if (reference_token == "-") { // explicitly treat "-" as index beyond the end ptr = &ptr->operator[](ptr->m_value.array->size()); } else { // convert array index to number; unchecked access ptr = &ptr->operator[](array_index(reference_token)); } break; } default: JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr)); } } return *ptr; } /*! @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.402 if the array index '-' is used @throw out_of_range.404 if the JSON pointer can not be resolved */ BasicJsonType& get_checked(BasicJsonType* ptr) const { for (const auto& reference_token : reference_tokens) { switch (ptr->type()) { case detail::value_t::object: { // note: at performs range check ptr = &ptr->at(reference_token); break; } case detail::value_t::array: { if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) { // "-" always fails the range check JSON_THROW(detail::out_of_range::create(402, "array index '-' (" + std::to_string(ptr->m_value.array->size()) + ") is out of range", *ptr)); } // note: at performs range check ptr = &ptr->at(array_index(reference_token)); break; } default: JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr)); } } return *ptr; } /*! @brief return a const reference to the pointed to value @param[in] ptr a JSON value @return const reference to the JSON value pointed to by the JSON pointer @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.402 if the array index '-' is used @throw out_of_range.404 if the JSON pointer can not be resolved */ const BasicJsonType& get_unchecked(const BasicJsonType* ptr) const { for (const auto& reference_token : reference_tokens) { switch (ptr->type()) { case detail::value_t::object: { // use unchecked object access ptr = &ptr->operator[](reference_token); break; } case detail::value_t::array: { if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) { // "-" cannot be used for const access JSON_THROW(detail::out_of_range::create(402, "array index '-' (" + std::to_string(ptr->m_value.array->size()) + ") is out of range", *ptr)); } // use unchecked array access ptr = &ptr->operator[](array_index(reference_token)); break; } default: JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr)); } } return *ptr; } /*! @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.402 if the array index '-' is used @throw out_of_range.404 if the JSON pointer can not be resolved */ const BasicJsonType& get_checked(const BasicJsonType* ptr) const { for (const auto& reference_token : reference_tokens) { switch (ptr->type()) { case detail::value_t::object: { // note: at performs range check ptr = &ptr->at(reference_token); break; } case detail::value_t::array: { if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) { // "-" always fails the range check JSON_THROW(detail::out_of_range::create(402, "array index '-' (" + std::to_string(ptr->m_value.array->size()) + ") is out of range", *ptr)); } // note: at performs range check ptr = &ptr->at(array_index(reference_token)); break; } default: JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr)); } } return *ptr; } /*! @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number */ bool contains(const BasicJsonType* ptr) const { for (const auto& reference_token : reference_tokens) { switch (ptr->type()) { case detail::value_t::object: { if (!ptr->contains(reference_token)) { // we did not find the key in the object return false; } ptr = &ptr->operator[](reference_token); break; } case detail::value_t::array: { if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) { // "-" always fails the range check return false; } if (JSON_HEDLEY_UNLIKELY(reference_token.size() == 1 && !("0" <= reference_token && reference_token <= "9"))) { // invalid char return false; } if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1)) { if (JSON_HEDLEY_UNLIKELY(!('1' <= reference_token[0] && reference_token[0] <= '9'))) { // first char should be between '1' and '9' return false; } for (std::size_t i = 1; i < reference_token.size(); i++) { if (JSON_HEDLEY_UNLIKELY(!('0' <= reference_token[i] && reference_token[i] <= '9'))) { // other char should be between '0' and '9' return false; } } } const auto idx = array_index(reference_token); if (idx >= ptr->size()) { // index out of range return false; } ptr = &ptr->operator[](idx); break; } default: { // we do not expect primitive values if there is still a // reference token to process return false; } } } // no reference token left means we found a primitive value return true; } /*! @brief split the string input to reference tokens @note This function is only called by the json_pointer constructor. All exceptions below are documented there. @throw parse_error.107 if the pointer is not empty or begins with '/' @throw parse_error.108 if character '~' is not followed by '0' or '1' */ static std::vector<std::string> split(const std::string& reference_string) { std::vector<std::string> result; // special case: empty reference string -> no reference tokens if (reference_string.empty()) { return result; } // check if nonempty reference string begins with slash if (JSON_HEDLEY_UNLIKELY(reference_string[0] != '/')) { JSON_THROW(detail::parse_error::create(107, 1, "JSON pointer must be empty or begin with '/' - was: '" + reference_string + "'", BasicJsonType())); } // extract the reference tokens: // - slash: position of the last read slash (or end of string) // - start: position after the previous slash for ( // search for the first slash after the first character std::size_t slash = reference_string.find_first_of('/', 1), // set the beginning of the first reference token start = 1; // we can stop if start == 0 (if slash == std::string::npos) start != 0; // set the beginning of the next reference token // (will eventually be 0 if slash == std::string::npos) start = (slash == std::string::npos) ? 0 : slash + 1, // find next slash slash = reference_string.find_first_of('/', start)) { // use the text between the beginning of the reference token // (start) and the last slash (slash). auto reference_token = reference_string.substr(start, slash - start); // check reference tokens are properly escaped for (std::size_t pos = reference_token.find_first_of('~'); pos != std::string::npos; pos = reference_token.find_first_of('~', pos + 1)) { JSON_ASSERT(reference_token[pos] == '~'); // ~ must be followed by 0 or 1 if (JSON_HEDLEY_UNLIKELY(pos == reference_token.size() - 1 || (reference_token[pos + 1] != '0' && reference_token[pos + 1] != '1'))) { JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'", BasicJsonType())); } } // finally, store the reference token detail::unescape(reference_token); result.push_back(reference_token); } return result; } private: /*! @param[in] reference_string the reference string to the current value @param[in] value the value to consider @param[in,out] result the result object to insert values to @note Empty objects or arrays are flattened to `null`. */ static void flatten(const std::string& reference_string, const BasicJsonType& value, BasicJsonType& result) { switch (value.type()) { case detail::value_t::array: { if (value.m_value.array->empty()) { // flatten empty array as null result[reference_string] = nullptr; } else { // iterate array and use index as reference string for (std::size_t i = 0; i < value.m_value.array->size(); ++i) { flatten(reference_string + "/" + std::to_string(i), value.m_value.array->operator[](i), result); } } break; } case detail::value_t::object: { if (value.m_value.object->empty()) { // flatten empty object as null result[reference_string] = nullptr; } else { // iterate object and use keys as reference string for (const auto& element : *value.m_value.object) { flatten(reference_string + "/" + detail::escape(element.first), element.second, result); } } break; } default: { // add primitive value with its reference string result[reference_string] = value; break; } } } /*! @param[in] value flattened JSON @return unflattened JSON @throw parse_error.109 if array index is not a number @throw type_error.314 if value is not an object @throw type_error.315 if object values are not primitive @throw type_error.313 if value cannot be unflattened */ static BasicJsonType unflatten(const BasicJsonType& value) { if (JSON_HEDLEY_UNLIKELY(!value.is_object())) { JSON_THROW(detail::type_error::create(314, "only objects can be unflattened", value)); } BasicJsonType result; // iterate the JSON object values for (const auto& element : *value.m_value.object) { if (JSON_HEDLEY_UNLIKELY(!element.second.is_primitive())) { JSON_THROW(detail::type_error::create(315, "values in object must be primitive", element.second)); } // assign value to reference pointed to by JSON pointer; Note that if // the JSON pointer is "" (i.e., points to the whole value), function // get_and_create returns a reference to result itself. An assignment // will then create a primitive value. json_pointer(element.first).get_and_create(result) = element.second; } return result; } /*! @brief compares two JSON pointers for equality @param[in] lhs JSON pointer to compare @param[in] rhs JSON pointer to compare @return whether @a lhs is equal to @a rhs @complexity Linear in the length of the JSON pointer @exceptionsafety No-throw guarantee: this function never throws exceptions. */ friend bool operator==(json_pointer const& lhs, json_pointer const& rhs) noexcept { return lhs.reference_tokens == rhs.reference_tokens; } /*! @brief compares two JSON pointers for inequality @param[in] lhs JSON pointer to compare @param[in] rhs JSON pointer to compare @return whether @a lhs is not equal @a rhs @complexity Linear in the length of the JSON pointer @exceptionsafety No-throw guarantee: this function never throws exceptions. */ friend bool operator!=(json_pointer const& lhs, json_pointer const& rhs) noexcept { return !(lhs == rhs); } /// the reference tokens std::vector<std::string> reference_tokens; }; } // namespace nlohmann // #include <nlohmann/detail/json_ref.hpp> #include <initializer_list> #include <utility> // #include <nlohmann/detail/meta/type_traits.hpp> namespace nlohmann { namespace detail { template<typename BasicJsonType> class json_ref { public: using value_type = BasicJsonType; json_ref(value_type&& value) : owned_value(std::move(value)) {} json_ref(const value_type& value) : value_ref(&value) {} json_ref(std::initializer_list<json_ref> init) : owned_value(init) {} template < class... Args, enable_if_t<std::is_constructible<value_type, Args...>::value, int> = 0 > json_ref(Args && ... args) : owned_value(std::forward<Args>(args)...) {} // class should be movable only json_ref(json_ref&&) noexcept = default; json_ref(const json_ref&) = delete; json_ref& operator=(const json_ref&) = delete; json_ref& operator=(json_ref&&) = delete; ~json_ref() = default; value_type moved_or_copied() const { if (value_ref == nullptr) { return std::move(owned_value); } return *value_ref; } value_type const& operator*() const { return value_ref ? *value_ref : owned_value; } value_type const* operator->() const { return &** this; } private: mutable value_type owned_value = nullptr; value_type const* value_ref = nullptr; }; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/macro_scope.hpp> // #include <nlohmann/detail/string_escape.hpp> // #include <nlohmann/detail/meta/cpp_future.hpp> // #include <nlohmann/detail/meta/type_traits.hpp> // #include <nlohmann/detail/output/binary_writer.hpp> #include <algorithm> // reverse #include <array> // array #include <cmath> // isnan, isinf #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t #include <cstring> // memcpy #include <limits> // numeric_limits #include <string> // string #include <utility> // move // #include <nlohmann/detail/input/binary_reader.hpp> // #include <nlohmann/detail/macro_scope.hpp> // #include <nlohmann/detail/output/output_adapters.hpp> #include <algorithm> // copy #include <cstddef> // size_t #include <iterator> // back_inserter #include <memory> // shared_ptr, make_shared #include <string> // basic_string #include <vector> // vector #ifndef JSON_NO_IO #include <ios> // streamsize #include <ostream> // basic_ostream #endif // JSON_NO_IO // #include <nlohmann/detail/macro_scope.hpp> namespace nlohmann { namespace detail { /// abstract output adapter interface template<typename CharType> struct output_adapter_protocol { virtual void write_character(CharType c) = 0; virtual void write_characters(const CharType* s, std::size_t length) = 0; virtual ~output_adapter_protocol() = default; output_adapter_protocol() = default; output_adapter_protocol(const output_adapter_protocol&) = default; output_adapter_protocol(output_adapter_protocol&&) noexcept = default; output_adapter_protocol& operator=(const output_adapter_protocol&) = default; output_adapter_protocol& operator=(output_adapter_protocol&&) noexcept = default; }; /// a type to simplify interfaces template<typename CharType> using output_adapter_t = std::shared_ptr<output_adapter_protocol<CharType>>; /// output adapter for byte vectors template<typename CharType> class output_vector_adapter : public output_adapter_protocol<CharType> { public: explicit output_vector_adapter(std::vector<CharType>& vec) noexcept : v(vec) {} void write_character(CharType c) override { v.push_back(c); } JSON_HEDLEY_NON_NULL(2) void write_characters(const CharType* s, std::size_t length) override { std::copy(s, s + length, std::back_inserter(v)); } private: std::vector<CharType>& v; }; #ifndef JSON_NO_IO /// output adapter for output streams template<typename CharType> class output_stream_adapter : public output_adapter_protocol<CharType> { public: explicit output_stream_adapter(std::basic_ostream<CharType>& s) noexcept : stream(s) {} void write_character(CharType c) override { stream.put(c); } JSON_HEDLEY_NON_NULL(2) void write_characters(const CharType* s, std::size_t length) override { stream.write(s, static_cast<std::streamsize>(length)); } private: std::basic_ostream<CharType>& stream; }; #endif // JSON_NO_IO /// output adapter for basic_string template<typename CharType, typename StringType = std::basic_string<CharType>> class output_string_adapter : public output_adapter_protocol<CharType> { public: explicit output_string_adapter(StringType& s) noexcept : str(s) {} void write_character(CharType c) override { str.push_back(c); } JSON_HEDLEY_NON_NULL(2) void write_characters(const CharType* s, std::size_t length) override { str.append(s, length); } private: StringType& str; }; template<typename CharType, typename StringType = std::basic_string<CharType>> class output_adapter { public: output_adapter(std::vector<CharType>& vec) : oa(std::make_shared<output_vector_adapter<CharType>>(vec)) {} #ifndef JSON_NO_IO output_adapter(std::basic_ostream<CharType>& s) : oa(std::make_shared<output_stream_adapter<CharType>>(s)) {} #endif // JSON_NO_IO output_adapter(StringType& s) : oa(std::make_shared<output_string_adapter<CharType, StringType>>(s)) {} operator output_adapter_t<CharType>() { return oa; } private: output_adapter_t<CharType> oa = nullptr; }; } // namespace detail } // namespace nlohmann namespace nlohmann { namespace detail { /////////////////// // binary writer // /////////////////// /*! @brief serialization to CBOR and MessagePack values */ template<typename BasicJsonType, typename CharType> class binary_writer { using string_t = typename BasicJsonType::string_t; using binary_t = typename BasicJsonType::binary_t; using number_float_t = typename BasicJsonType::number_float_t; public: /*! @brief create a binary writer @param[in] adapter output adapter to write to */ explicit binary_writer(output_adapter_t<CharType> adapter) : oa(std::move(adapter)) { JSON_ASSERT(oa); } /*! @param[in] j JSON value to serialize @pre j.type() == value_t::object */ void write_bson(const BasicJsonType& j) { switch (j.type()) { case value_t::object: { write_bson_object(*j.m_value.object); break; } default: { JSON_THROW(type_error::create(317, "to serialize to BSON, top-level type must be object, but is " + std::string(j.type_name()), j));; } } } /*! @param[in] j JSON value to serialize */ void write_cbor(const BasicJsonType& j) { switch (j.type()) { case value_t::null: { oa->write_character(to_char_type(0xF6)); break; } case value_t::boolean: { oa->write_character(j.m_value.boolean ? to_char_type(0xF5) : to_char_type(0xF4)); break; } case value_t::number_integer: { if (j.m_value.number_integer >= 0) { // CBOR does not differentiate between positive signed // integers and unsigned integers. Therefore, we used the // code from the value_t::number_unsigned case here. if (j.m_value.number_integer <= 0x17) { write_number(static_cast<std::uint8_t>(j.m_value.number_integer)); } else if (j.m_value.number_integer <= (std::numeric_limits<std::uint8_t>::max)()) { oa->write_character(to_char_type(0x18)); write_number(static_cast<std::uint8_t>(j.m_value.number_integer)); } else if (j.m_value.number_integer <= (std::numeric_limits<std::uint16_t>::max)()) { oa->write_character(to_char_type(0x19)); write_number(static_cast<std::uint16_t>(j.m_value.number_integer)); } else if (j.m_value.number_integer <= (std::numeric_limits<std::uint32_t>::max)()) { oa->write_character(to_char_type(0x1A)); write_number(static_cast<std::uint32_t>(j.m_value.number_integer)); } else { oa->write_character(to_char_type(0x1B)); write_number(static_cast<std::uint64_t>(j.m_value.number_integer)); } } else { // The conversions below encode the sign in the first // byte, and the value is converted to a positive number. const auto positive_number = -1 - j.m_value.number_integer; if (j.m_value.number_integer >= -24) { write_number(static_cast<std::uint8_t>(0x20 + positive_number)); } else if (positive_number <= (std::numeric_limits<std::uint8_t>::max)()) { oa->write_character(to_char_type(0x38)); write_number(static_cast<std::uint8_t>(positive_number)); } else if (positive_number <= (std::numeric_limits<std::uint16_t>::max)()) { oa->write_character(to_char_type(0x39)); write_number(static_cast<std::uint16_t>(positive_number)); } else if (positive_number <= (std::numeric_limits<std::uint32_t>::max)()) { oa->write_character(to_char_type(0x3A)); write_number(static_cast<std::uint32_t>(positive_number)); } else { oa->write_character(to_char_type(0x3B)); write_number(static_cast<std::uint64_t>(positive_number)); } } break; } case value_t::number_unsigned: { if (j.m_value.number_unsigned <= 0x17) { write_number(static_cast<std::uint8_t>(j.m_value.number_unsigned)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)()) { oa->write_character(to_char_type(0x18)); write_number(static_cast<std::uint8_t>(j.m_value.number_unsigned)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)()) { oa->write_character(to_char_type(0x19)); write_number(static_cast<std::uint16_t>(j.m_value.number_unsigned)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)()) { oa->write_character(to_char_type(0x1A)); write_number(static_cast<std::uint32_t>(j.m_value.number_unsigned)); } else { oa->write_character(to_char_type(0x1B)); write_number(static_cast<std::uint64_t>(j.m_value.number_unsigned)); } break; } case value_t::number_float: { if (std::isnan(j.m_value.number_float)) { // NaN is 0xf97e00 in CBOR oa->write_character(to_char_type(0xF9)); oa->write_character(to_char_type(0x7E)); oa->write_character(to_char_type(0x00)); } else if (std::isinf(j.m_value.number_float)) { // Infinity is 0xf97c00, -Infinity is 0xf9fc00 oa->write_character(to_char_type(0xf9)); oa->write_character(j.m_value.number_float > 0 ? to_char_type(0x7C) : to_char_type(0xFC)); oa->write_character(to_char_type(0x00)); } else { write_compact_float(j.m_value.number_float, detail::input_format_t::cbor); } break; } case value_t::string: { // step 1: write control byte and the string length const auto N = j.m_value.string->size(); if (N <= 0x17) { write_number(static_cast<std::uint8_t>(0x60 + N)); } else if (N <= (std::numeric_limits<std::uint8_t>::max)()) { oa->write_character(to_char_type(0x78)); write_number(static_cast<std::uint8_t>(N)); } else if (N <= (std::numeric_limits<std::uint16_t>::max)()) { oa->write_character(to_char_type(0x79)); write_number(static_cast<std::uint16_t>(N)); } else if (N <= (std::numeric_limits<std::uint32_t>::max)()) { oa->write_character(to_char_type(0x7A)); write_number(static_cast<std::uint32_t>(N)); } // LCOV_EXCL_START else if (N <= (std::numeric_limits<std::uint64_t>::max)()) { oa->write_character(to_char_type(0x7B)); write_number(static_cast<std::uint64_t>(N)); } // LCOV_EXCL_STOP // step 2: write the string oa->write_characters( reinterpret_cast<const CharType*>(j.m_value.string->c_str()), j.m_value.string->size()); break; } case value_t::array: { // step 1: write control byte and the array size const auto N = j.m_value.array->size(); if (N <= 0x17) { write_number(static_cast<std::uint8_t>(0x80 + N)); } else if (N <= (std::numeric_limits<std::uint8_t>::max)()) { oa->write_character(to_char_type(0x98)); write_number(static_cast<std::uint8_t>(N)); } else if (N <= (std::numeric_limits<std::uint16_t>::max)()) { oa->write_character(to_char_type(0x99)); write_number(static_cast<std::uint16_t>(N)); } else if (N <= (std::numeric_limits<std::uint32_t>::max)()) { oa->write_character(to_char_type(0x9A)); write_number(static_cast<std::uint32_t>(N)); } // LCOV_EXCL_START else if (N <= (std::numeric_limits<std::uint64_t>::max)()) { oa->write_character(to_char_type(0x9B)); write_number(static_cast<std::uint64_t>(N)); } // LCOV_EXCL_STOP // step 2: write each element for (const auto& el : *j.m_value.array) { write_cbor(el); } break; } case value_t::binary: { if (j.m_value.binary->has_subtype()) { write_number(static_cast<std::uint8_t>(0xd8)); write_number(j.m_value.binary->subtype()); } // step 1: write control byte and the binary array size const auto N = j.m_value.binary->size(); if (N <= 0x17) { write_number(static_cast<std::uint8_t>(0x40 + N)); } else if (N <= (std::numeric_limits<std::uint8_t>::max)()) { oa->write_character(to_char_type(0x58)); write_number(static_cast<std::uint8_t>(N)); } else if (N <= (std::numeric_limits<std::uint16_t>::max)()) { oa->write_character(to_char_type(0x59)); write_number(static_cast<std::uint16_t>(N)); } else if (N <= (std::numeric_limits<std::uint32_t>::max)()) { oa->write_character(to_char_type(0x5A)); write_number(static_cast<std::uint32_t>(N)); } // LCOV_EXCL_START else if (N <= (std::numeric_limits<std::uint64_t>::max)()) { oa->write_character(to_char_type(0x5B)); write_number(static_cast<std::uint64_t>(N)); } // LCOV_EXCL_STOP // step 2: write each element oa->write_characters( reinterpret_cast<const CharType*>(j.m_value.binary->data()), N); break; } case value_t::object: { // step 1: write control byte and the object size const auto N = j.m_value.object->size(); if (N <= 0x17) { write_number(static_cast<std::uint8_t>(0xA0 + N)); } else if (N <= (std::numeric_limits<std::uint8_t>::max)()) { oa->write_character(to_char_type(0xB8)); write_number(static_cast<std::uint8_t>(N)); } else if (N <= (std::numeric_limits<std::uint16_t>::max)()) { oa->write_character(to_char_type(0xB9)); write_number(static_cast<std::uint16_t>(N)); } else if (N <= (std::numeric_limits<std::uint32_t>::max)()) { oa->write_character(to_char_type(0xBA)); write_number(static_cast<std::uint32_t>(N)); } // LCOV_EXCL_START else if (N <= (std::numeric_limits<std::uint64_t>::max)()) { oa->write_character(to_char_type(0xBB)); write_number(static_cast<std::uint64_t>(N)); } // LCOV_EXCL_STOP // step 2: write each element for (const auto& el : *j.m_value.object) { write_cbor(el.first); write_cbor(el.second); } break; } default: break; } } /*! @param[in] j JSON value to serialize */ void write_msgpack(const BasicJsonType& j) { switch (j.type()) { case value_t::null: // nil { oa->write_character(to_char_type(0xC0)); break; } case value_t::boolean: // true and false { oa->write_character(j.m_value.boolean ? to_char_type(0xC3) : to_char_type(0xC2)); break; } case value_t::number_integer: { if (j.m_value.number_integer >= 0) { // MessagePack does not differentiate between positive // signed integers and unsigned integers. Therefore, we used // the code from the value_t::number_unsigned case here. if (j.m_value.number_unsigned < 128) { // positive fixnum write_number(static_cast<std::uint8_t>(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)()) { // uint 8 oa->write_character(to_char_type(0xCC)); write_number(static_cast<std::uint8_t>(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)()) { // uint 16 oa->write_character(to_char_type(0xCD)); write_number(static_cast<std::uint16_t>(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)()) { // uint 32 oa->write_character(to_char_type(0xCE)); write_number(static_cast<std::uint32_t>(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)()) { // uint 64 oa->write_character(to_char_type(0xCF)); write_number(static_cast<std::uint64_t>(j.m_value.number_integer)); } } else { if (j.m_value.number_integer >= -32) { // negative fixnum write_number(static_cast<std::int8_t>(j.m_value.number_integer)); } else if (j.m_value.number_integer >= (std::numeric_limits<std::int8_t>::min)() && j.m_value.number_integer <= (std::numeric_limits<std::int8_t>::max)()) { // int 8 oa->write_character(to_char_type(0xD0)); write_number(static_cast<std::int8_t>(j.m_value.number_integer)); } else if (j.m_value.number_integer >= (std::numeric_limits<std::int16_t>::min)() && j.m_value.number_integer <= (std::numeric_limits<std::int16_t>::max)()) { // int 16 oa->write_character(to_char_type(0xD1)); write_number(static_cast<std::int16_t>(j.m_value.number_integer)); } else if (j.m_value.number_integer >= (std::numeric_limits<std::int32_t>::min)() && j.m_value.number_integer <= (std::numeric_limits<std::int32_t>::max)()) { // int 32 oa->write_character(to_char_type(0xD2)); write_number(static_cast<std::int32_t>(j.m_value.number_integer)); } else if (j.m_value.number_integer >= (std::numeric_limits<std::int64_t>::min)() && j.m_value.number_integer <= (std::numeric_limits<std::int64_t>::max)()) { // int 64 oa->write_character(to_char_type(0xD3)); write_number(static_cast<std::int64_t>(j.m_value.number_integer)); } } break; } case value_t::number_unsigned: { if (j.m_value.number_unsigned < 128) { // positive fixnum write_number(static_cast<std::uint8_t>(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)()) { // uint 8 oa->write_character(to_char_type(0xCC)); write_number(static_cast<std::uint8_t>(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)()) { // uint 16 oa->write_character(to_char_type(0xCD)); write_number(static_cast<std::uint16_t>(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)()) { // uint 32 oa->write_character(to_char_type(0xCE)); write_number(static_cast<std::uint32_t>(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)()) { // uint 64 oa->write_character(to_char_type(0xCF)); write_number(static_cast<std::uint64_t>(j.m_value.number_integer)); } break; } case value_t::number_float: { write_compact_float(j.m_value.number_float, detail::input_format_t::msgpack); break; } case value_t::string: { // step 1: write control byte and the string length const auto N = j.m_value.string->size(); if (N <= 31) { // fixstr write_number(static_cast<std::uint8_t>(0xA0 | N)); } else if (N <= (std::numeric_limits<std::uint8_t>::max)()) { // str 8 oa->write_character(to_char_type(0xD9)); write_number(static_cast<std::uint8_t>(N)); } else if (N <= (std::numeric_limits<std::uint16_t>::max)()) { // str 16 oa->write_character(to_char_type(0xDA)); write_number(static_cast<std::uint16_t>(N)); } else if (N <= (std::numeric_limits<std::uint32_t>::max)()) { // str 32 oa->write_character(to_char_type(0xDB)); write_number(static_cast<std::uint32_t>(N)); } // step 2: write the string oa->write_characters( reinterpret_cast<const CharType*>(j.m_value.string->c_str()), j.m_value.string->size()); break; } case value_t::array: { // step 1: write control byte and the array size const auto N = j.m_value.array->size(); if (N <= 15) { // fixarray write_number(static_cast<std::uint8_t>(0x90 | N)); } else if (N <= (std::numeric_limits<std::uint16_t>::max)()) { // array 16 oa->write_character(to_char_type(0xDC)); write_number(static_cast<std::uint16_t>(N)); } else if (N <= (std::numeric_limits<std::uint32_t>::max)()) { // array 32 oa->write_character(to_char_type(0xDD)); write_number(static_cast<std::uint32_t>(N)); } // step 2: write each element for (const auto& el : *j.m_value.array) { write_msgpack(el); } break; } case value_t::binary: { // step 0: determine if the binary type has a set subtype to // determine whether or not to use the ext or fixext types const bool use_ext = j.m_value.binary->has_subtype(); // step 1: write control byte and the byte string length const auto N = j.m_value.binary->size(); if (N <= (std::numeric_limits<std::uint8_t>::max)()) { std::uint8_t output_type{}; bool fixed = true; if (use_ext) { switch (N) { case 1: output_type = 0xD4; // fixext 1 break; case 2: output_type = 0xD5; // fixext 2 break; case 4: output_type = 0xD6; // fixext 4 break; case 8: output_type = 0xD7; // fixext 8 break; case 16: output_type = 0xD8; // fixext 16 break; default: output_type = 0xC7; // ext 8 fixed = false; break; } } else { output_type = 0xC4; // bin 8 fixed = false; } oa->write_character(to_char_type(output_type)); if (!fixed) { write_number(static_cast<std::uint8_t>(N)); } } else if (N <= (std::numeric_limits<std::uint16_t>::max)()) { std::uint8_t output_type = use_ext ? 0xC8 // ext 16 : 0xC5; // bin 16 oa->write_character(to_char_type(output_type)); write_number(static_cast<std::uint16_t>(N)); } else if (N <= (std::numeric_limits<std::uint32_t>::max)()) { std::uint8_t output_type = use_ext ? 0xC9 // ext 32 : 0xC6; // bin 32 oa->write_character(to_char_type(output_type)); write_number(static_cast<std::uint32_t>(N)); } // step 1.5: if this is an ext type, write the subtype if (use_ext) { write_number(static_cast<std::int8_t>(j.m_value.binary->subtype())); } // step 2: write the byte string oa->write_characters( reinterpret_cast<const CharType*>(j.m_value.binary->data()), N); break; } case value_t::object: { // step 1: write control byte and the object size const auto N = j.m_value.object->size(); if (N <= 15) { // fixmap write_number(static_cast<std::uint8_t>(0x80 | (N & 0xF))); } else if (N <= (std::numeric_limits<std::uint16_t>::max)()) { // map 16 oa->write_character(to_char_type(0xDE)); write_number(static_cast<std::uint16_t>(N)); } else if (N <= (std::numeric_limits<std::uint32_t>::max)()) { // map 32 oa->write_character(to_char_type(0xDF)); write_number(static_cast<std::uint32_t>(N)); } // step 2: write each element for (const auto& el : *j.m_value.object) { write_msgpack(el.first); write_msgpack(el.second); } break; } default: break; } } /*! @param[in] j JSON value to serialize @param[in] use_count whether to use '#' prefixes (optimized format) @param[in] use_type whether to use '$' prefixes (optimized format) @param[in] add_prefix whether prefixes need to be used for this value */ void write_ubjson(const BasicJsonType& j, const bool use_count, const bool use_type, const bool add_prefix = true) { switch (j.type()) { case value_t::null: { if (add_prefix) { oa->write_character(to_char_type('Z')); } break; } case value_t::boolean: { if (add_prefix) { oa->write_character(j.m_value.boolean ? to_char_type('T') : to_char_type('F')); } break; } case value_t::number_integer: { write_number_with_ubjson_prefix(j.m_value.number_integer, add_prefix); break; } case value_t::number_unsigned: { write_number_with_ubjson_prefix(j.m_value.number_unsigned, add_prefix); break; } case value_t::number_float: { write_number_with_ubjson_prefix(j.m_value.number_float, add_prefix); break; } case value_t::string: { if (add_prefix) { oa->write_character(to_char_type('S')); } write_number_with_ubjson_prefix(j.m_value.string->size(), true); oa->write_characters( reinterpret_cast<const CharType*>(j.m_value.string->c_str()), j.m_value.string->size()); break; } case value_t::array: { if (add_prefix) { oa->write_character(to_char_type('[')); } bool prefix_required = true; if (use_type && !j.m_value.array->empty()) { JSON_ASSERT(use_count); const CharType first_prefix = ubjson_prefix(j.front()); const bool same_prefix = std::all_of(j.begin() + 1, j.end(), [this, first_prefix](const BasicJsonType & v) { return ubjson_prefix(v) == first_prefix; }); if (same_prefix) { prefix_required = false; oa->write_character(to_char_type('$')); oa->write_character(first_prefix); } } if (use_count) { oa->write_character(to_char_type('#')); write_number_with_ubjson_prefix(j.m_value.array->size(), true); } for (const auto& el : *j.m_value.array) { write_ubjson(el, use_count, use_type, prefix_required); } if (!use_count) { oa->write_character(to_char_type(']')); } break; } case value_t::binary: { if (add_prefix) { oa->write_character(to_char_type('[')); } if (use_type && !j.m_value.binary->empty()) { JSON_ASSERT(use_count); oa->write_character(to_char_type('$')); oa->write_character('U'); } if (use_count) { oa->write_character(to_char_type('#')); write_number_with_ubjson_prefix(j.m_value.binary->size(), true); } if (use_type) { oa->write_characters( reinterpret_cast<const CharType*>(j.m_value.binary->data()), j.m_value.binary->size()); } else { for (size_t i = 0; i < j.m_value.binary->size(); ++i) { oa->write_character(to_char_type('U')); oa->write_character(j.m_value.binary->data()[i]); } } if (!use_count) { oa->write_character(to_char_type(']')); } break; } case value_t::object: { if (add_prefix) { oa->write_character(to_char_type('{')); } bool prefix_required = true; if (use_type && !j.m_value.object->empty()) { JSON_ASSERT(use_count); const CharType first_prefix = ubjson_prefix(j.front()); const bool same_prefix = std::all_of(j.begin(), j.end(), [this, first_prefix](const BasicJsonType & v) { return ubjson_prefix(v) == first_prefix; }); if (same_prefix) { prefix_required = false; oa->write_character(to_char_type('$')); oa->write_character(first_prefix); } } if (use_count) { oa->write_character(to_char_type('#')); write_number_with_ubjson_prefix(j.m_value.object->size(), true); } for (const auto& el : *j.m_value.object) { write_number_with_ubjson_prefix(el.first.size(), true); oa->write_characters( reinterpret_cast<const CharType*>(el.first.c_str()), el.first.size()); write_ubjson(el.second, use_count, use_type, prefix_required); } if (!use_count) { oa->write_character(to_char_type('}')); } break; } default: break; } } private: ////////// // BSON // ////////// /*! @return The size of a BSON document entry header, including the id marker and the entry name size (and its null-terminator). */ static std::size_t calc_bson_entry_header_size(const string_t& name, const BasicJsonType& j) { const auto it = name.find(static_cast<typename string_t::value_type>(0)); if (JSON_HEDLEY_UNLIKELY(it != BasicJsonType::string_t::npos)) { JSON_THROW(out_of_range::create(409, "BSON key cannot contain code point U+0000 (at byte " + std::to_string(it) + ")", j)); } return /*id*/ 1ul + name.size() + /*zero-terminator*/1u; } /*! @brief Writes the given @a element_type and @a name to the output adapter */ void write_bson_entry_header(const string_t& name, const std::uint8_t element_type) { oa->write_character(to_char_type(element_type)); // boolean oa->write_characters( reinterpret_cast<const CharType*>(name.c_str()), name.size() + 1u); } /*! @brief Writes a BSON element with key @a name and boolean value @a value */ void write_bson_boolean(const string_t& name, const bool value) { write_bson_entry_header(name, 0x08); oa->write_character(value ? to_char_type(0x01) : to_char_type(0x00)); } /*! @brief Writes a BSON element with key @a name and double value @a value */ void write_bson_double(const string_t& name, const double value) { write_bson_entry_header(name, 0x01); write_number<double, true>(value); } /*! @return The size of the BSON-encoded string in @a value */ static std::size_t calc_bson_string_size(const string_t& value) { return sizeof(std::int32_t) + value.size() + 1ul; } /*! @brief Writes a BSON element with key @a name and string value @a value */ void write_bson_string(const string_t& name, const string_t& value) { write_bson_entry_header(name, 0x02); write_number<std::int32_t, true>(static_cast<std::int32_t>(value.size() + 1ul)); oa->write_characters( reinterpret_cast<const CharType*>(value.c_str()), value.size() + 1); } /*! @brief Writes a BSON element with key @a name and null value */ void write_bson_null(const string_t& name) { write_bson_entry_header(name, 0x0A); } /*! @return The size of the BSON-encoded integer @a value */ static std::size_t calc_bson_integer_size(const std::int64_t value) { return (std::numeric_limits<std::int32_t>::min)() <= value && value <= (std::numeric_limits<std::int32_t>::max)() ? sizeof(std::int32_t) : sizeof(std::int64_t); } /*! @brief Writes a BSON element with key @a name and integer @a value */ void write_bson_integer(const string_t& name, const std::int64_t value) { if ((std::numeric_limits<std::int32_t>::min)() <= value && value <= (std::numeric_limits<std::int32_t>::max)()) { write_bson_entry_header(name, 0x10); // int32 write_number<std::int32_t, true>(static_cast<std::int32_t>(value)); } else { write_bson_entry_header(name, 0x12); // int64 write_number<std::int64_t, true>(static_cast<std::int64_t>(value)); } } /*! @return The size of the BSON-encoded unsigned integer in @a j */ static constexpr std::size_t calc_bson_unsigned_size(const std::uint64_t value) noexcept { return (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)())) ? sizeof(std::int32_t) : sizeof(std::int64_t); } /*! @brief Writes a BSON element with key @a name and unsigned @a value */ void write_bson_unsigned(const string_t& name, const BasicJsonType& j) { if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)())) { write_bson_entry_header(name, 0x10 /* int32 */); write_number<std::int32_t, true>(static_cast<std::int32_t>(j.m_value.number_unsigned)); } else if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)())) { write_bson_entry_header(name, 0x12 /* int64 */); write_number<std::int64_t, true>(static_cast<std::int64_t>(j.m_value.number_unsigned)); } else { JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(j.m_value.number_unsigned) + " cannot be represented by BSON as it does not fit int64", j)); } } /*! @brief Writes a BSON element with key @a name and object @a value */ void write_bson_object_entry(const string_t& name, const typename BasicJsonType::object_t& value) { write_bson_entry_header(name, 0x03); // object write_bson_object(value); } /*! @return The size of the BSON-encoded array @a value */ static std::size_t calc_bson_array_size(const typename BasicJsonType::array_t& value) { std::size_t array_index = 0ul; const std::size_t embedded_document_size = std::accumulate(std::begin(value), std::end(value), std::size_t(0), [&array_index](std::size_t result, const typename BasicJsonType::array_t::value_type & el) { return result + calc_bson_element_size(std::to_string(array_index++), el); }); return sizeof(std::int32_t) + embedded_document_size + 1ul; } /*! @return The size of the BSON-encoded binary array @a value */ static std::size_t calc_bson_binary_size(const typename BasicJsonType::binary_t& value) { return sizeof(std::int32_t) + value.size() + 1ul; } /*! @brief Writes a BSON element with key @a name and array @a value */ void write_bson_array(const string_t& name, const typename BasicJsonType::array_t& value) { write_bson_entry_header(name, 0x04); // array write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_array_size(value))); std::size_t array_index = 0ul; for (const auto& el : value) { write_bson_element(std::to_string(array_index++), el); } oa->write_character(to_char_type(0x00)); } /*! @brief Writes a BSON element with key @a name and binary value @a value */ void write_bson_binary(const string_t& name, const binary_t& value) { write_bson_entry_header(name, 0x05); write_number<std::int32_t, true>(static_cast<std::int32_t>(value.size())); write_number(value.has_subtype() ? value.subtype() : std::uint8_t(0x00)); oa->write_characters(reinterpret_cast<const CharType*>(value.data()), value.size()); } /*! @brief Calculates the size necessary to serialize the JSON value @a j with its @a name @return The calculated size for the BSON document entry for @a j with the given @a name. */ static std::size_t calc_bson_element_size(const string_t& name, const BasicJsonType& j) { const auto header_size = calc_bson_entry_header_size(name, j); switch (j.type()) { case value_t::object: return header_size + calc_bson_object_size(*j.m_value.object); case value_t::array: return header_size + calc_bson_array_size(*j.m_value.array); case value_t::binary: return header_size + calc_bson_binary_size(*j.m_value.binary); case value_t::boolean: return header_size + 1ul; case value_t::number_float: return header_size + 8ul; case value_t::number_integer: return header_size + calc_bson_integer_size(j.m_value.number_integer); case value_t::number_unsigned: return header_size + calc_bson_unsigned_size(j.m_value.number_unsigned); case value_t::string: return header_size + calc_bson_string_size(*j.m_value.string); case value_t::null: return header_size + 0ul; // LCOV_EXCL_START default: JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) return 0ul; // LCOV_EXCL_STOP } } /*! @brief Serializes the JSON value @a j to BSON and associates it with the key @a name. @param name The name to associate with the JSON entity @a j within the current BSON document */ void write_bson_element(const string_t& name, const BasicJsonType& j) { switch (j.type()) { case value_t::object: return write_bson_object_entry(name, *j.m_value.object); case value_t::array: return write_bson_array(name, *j.m_value.array); case value_t::binary: return write_bson_binary(name, *j.m_value.binary); case value_t::boolean: return write_bson_boolean(name, j.m_value.boolean); case value_t::number_float: return write_bson_double(name, j.m_value.number_float); case value_t::number_integer: return write_bson_integer(name, j.m_value.number_integer); case value_t::number_unsigned: return write_bson_unsigned(name, j); case value_t::string: return write_bson_string(name, *j.m_value.string); case value_t::null: return write_bson_null(name); // LCOV_EXCL_START default: JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) return; // LCOV_EXCL_STOP } } /*! @brief Calculates the size of the BSON serialization of the given JSON-object @a j. @param[in] value JSON value to serialize @pre value.type() == value_t::object */ static std::size_t calc_bson_object_size(const typename BasicJsonType::object_t& value) { std::size_t document_size = std::accumulate(value.begin(), value.end(), std::size_t(0), [](size_t result, const typename BasicJsonType::object_t::value_type & el) { return result += calc_bson_element_size(el.first, el.second); }); return sizeof(std::int32_t) + document_size + 1ul; } /*! @param[in] value JSON value to serialize @pre value.type() == value_t::object */ void write_bson_object(const typename BasicJsonType::object_t& value) { write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_object_size(value))); for (const auto& el : value) { write_bson_element(el.first, el.second); } oa->write_character(to_char_type(0x00)); } ////////// // CBOR // ////////// static constexpr CharType get_cbor_float_prefix(float /*unused*/) { return to_char_type(0xFA); // Single-Precision Float } static constexpr CharType get_cbor_float_prefix(double /*unused*/) { return to_char_type(0xFB); // Double-Precision Float } ///////////// // MsgPack // ///////////// static constexpr CharType get_msgpack_float_prefix(float /*unused*/) { return to_char_type(0xCA); // float 32 } static constexpr CharType get_msgpack_float_prefix(double /*unused*/) { return to_char_type(0xCB); // float 64 } //////////// // UBJSON // //////////// // UBJSON: write number (floating point) template<typename NumberType, typename std::enable_if< std::is_floating_point<NumberType>::value, int>::type = 0> void write_number_with_ubjson_prefix(const NumberType n, const bool add_prefix) { if (add_prefix) { oa->write_character(get_ubjson_float_prefix(n)); } write_number(n); } // UBJSON: write number (unsigned integer) template<typename NumberType, typename std::enable_if< std::is_unsigned<NumberType>::value, int>::type = 0> void write_number_with_ubjson_prefix(const NumberType n, const bool add_prefix) { if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)())) { if (add_prefix) { oa->write_character(to_char_type('i')); // int8 } write_number(static_cast<std::uint8_t>(n)); } else if (n <= (std::numeric_limits<std::uint8_t>::max)()) { if (add_prefix) { oa->write_character(to_char_type('U')); // uint8 } write_number(static_cast<std::uint8_t>(n)); } else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)())) { if (add_prefix) { oa->write_character(to_char_type('I')); // int16 } write_number(static_cast<std::int16_t>(n)); } else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)())) { if (add_prefix) { oa->write_character(to_char_type('l')); // int32 } write_number(static_cast<std::int32_t>(n)); } else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)())) { if (add_prefix) { oa->write_character(to_char_type('L')); // int64 } write_number(static_cast<std::int64_t>(n)); } else { if (add_prefix) { oa->write_character(to_char_type('H')); // high-precision number } const auto number = BasicJsonType(n).dump(); write_number_with_ubjson_prefix(number.size(), true); for (std::size_t i = 0; i < number.size(); ++i) { oa->write_character(to_char_type(static_cast<std::uint8_t>(number[i]))); } } } // UBJSON: write number (signed integer) template < typename NumberType, typename std::enable_if < std::is_signed<NumberType>::value&& !std::is_floating_point<NumberType>::value, int >::type = 0 > void write_number_with_ubjson_prefix(const NumberType n, const bool add_prefix) { if ((std::numeric_limits<std::int8_t>::min)() <= n && n <= (std::numeric_limits<std::int8_t>::max)()) { if (add_prefix) { oa->write_character(to_char_type('i')); // int8 } write_number(static_cast<std::int8_t>(n)); } else if (static_cast<std::int64_t>((std::numeric_limits<std::uint8_t>::min)()) <= n && n <= static_cast<std::int64_t>((std::numeric_limits<std::uint8_t>::max)())) { if (add_prefix) { oa->write_character(to_char_type('U')); // uint8 } write_number(static_cast<std::uint8_t>(n)); } else if ((std::numeric_limits<std::int16_t>::min)() <= n && n <= (std::numeric_limits<std::int16_t>::max)()) { if (add_prefix) { oa->write_character(to_char_type('I')); // int16 } write_number(static_cast<std::int16_t>(n)); } else if ((std::numeric_limits<std::int32_t>::min)() <= n && n <= (std::numeric_limits<std::int32_t>::max)()) { if (add_prefix) { oa->write_character(to_char_type('l')); // int32 } write_number(static_cast<std::int32_t>(n)); } else if ((std::numeric_limits<std::int64_t>::min)() <= n && n <= (std::numeric_limits<std::int64_t>::max)()) { if (add_prefix) { oa->write_character(to_char_type('L')); // int64 } write_number(static_cast<std::int64_t>(n)); } // LCOV_EXCL_START else { if (add_prefix) { oa->write_character(to_char_type('H')); // high-precision number } const auto number = BasicJsonType(n).dump(); write_number_with_ubjson_prefix(number.size(), true); for (std::size_t i = 0; i < number.size(); ++i) { oa->write_character(to_char_type(static_cast<std::uint8_t>(number[i]))); } } // LCOV_EXCL_STOP } /*! @brief determine the type prefix of container values */ CharType ubjson_prefix(const BasicJsonType& j) const noexcept { switch (j.type()) { case value_t::null: return 'Z'; case value_t::boolean: return j.m_value.boolean ? 'T' : 'F'; case value_t::number_integer: { if ((std::numeric_limits<std::int8_t>::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits<std::int8_t>::max)()) { return 'i'; } if ((std::numeric_limits<std::uint8_t>::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits<std::uint8_t>::max)()) { return 'U'; } if ((std::numeric_limits<std::int16_t>::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits<std::int16_t>::max)()) { return 'I'; } if ((std::numeric_limits<std::int32_t>::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits<std::int32_t>::max)()) { return 'l'; } if ((std::numeric_limits<std::int64_t>::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits<std::int64_t>::max)()) { return 'L'; } // anything else is treated as high-precision number return 'H'; // LCOV_EXCL_LINE } case value_t::number_unsigned: { if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)())) { return 'i'; } if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::uint8_t>::max)())) { return 'U'; } if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)())) { return 'I'; } if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)())) { return 'l'; } if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)())) { return 'L'; } // anything else is treated as high-precision number return 'H'; // LCOV_EXCL_LINE } case value_t::number_float: return get_ubjson_float_prefix(j.m_value.number_float); case value_t::string: return 'S'; case value_t::array: // fallthrough case value_t::binary: return '['; case value_t::object: return '{'; default: // discarded values return 'N'; } } static constexpr CharType get_ubjson_float_prefix(float /*unused*/) { return 'd'; // float 32 } static constexpr CharType get_ubjson_float_prefix(double /*unused*/) { return 'D'; // float 64 } /////////////////////// // Utility functions // /////////////////////// /* @brief write a number to output input @param[in] n number of type @a NumberType @tparam NumberType the type of the number @tparam OutputIsLittleEndian Set to true if output data is required to be little endian @note This function needs to respect the system's endianess, because bytes in CBOR, MessagePack, and UBJSON are stored in network order (big endian) and therefore need reordering on little endian systems. */ template<typename NumberType, bool OutputIsLittleEndian = false> void write_number(const NumberType n) { // step 1: write number to array of length NumberType std::array<CharType, sizeof(NumberType)> vec{}; std::memcpy(vec.data(), &n, sizeof(NumberType)); // step 2: write array to output (with possible reordering) if (is_little_endian != OutputIsLittleEndian) { // reverse byte order prior to conversion if necessary std::reverse(vec.begin(), vec.end()); } oa->write_characters(vec.data(), sizeof(NumberType)); } void write_compact_float(const number_float_t n, detail::input_format_t format) { if (static_cast<double>(n) >= static_cast<double>(std::numeric_limits<float>::lowest()) && static_cast<double>(n) <= static_cast<double>((std::numeric_limits<float>::max)()) && static_cast<double>(static_cast<float>(n)) == static_cast<double>(n)) { oa->write_character(format == detail::input_format_t::cbor ? get_cbor_float_prefix(static_cast<float>(n)) : get_msgpack_float_prefix(static_cast<float>(n))); write_number(static_cast<float>(n)); } else { oa->write_character(format == detail::input_format_t::cbor ? get_cbor_float_prefix(n) : get_msgpack_float_prefix(n)); write_number(n); } } public: // The following to_char_type functions are implement the conversion // between uint8_t and CharType. In case CharType is not unsigned, // such a conversion is required to allow values greater than 128. // See <https://github.com/nlohmann/json/issues/1286> for a discussion. template < typename C = CharType, enable_if_t < std::is_signed<C>::value && std::is_signed<char>::value > * = nullptr > static constexpr CharType to_char_type(std::uint8_t x) noexcept { return *reinterpret_cast<char*>(&x); } template < typename C = CharType, enable_if_t < std::is_signed<C>::value && std::is_unsigned<char>::value > * = nullptr > static CharType to_char_type(std::uint8_t x) noexcept { static_assert(sizeof(std::uint8_t) == sizeof(CharType), "size of CharType must be equal to std::uint8_t"); static_assert(std::is_trivial<CharType>::value, "CharType must be trivial"); CharType result; std::memcpy(&result, &x, sizeof(x)); return result; } template<typename C = CharType, enable_if_t<std::is_unsigned<C>::value>* = nullptr> static constexpr CharType to_char_type(std::uint8_t x) noexcept { return x; } template < typename InputCharType, typename C = CharType, enable_if_t < std::is_signed<C>::value && std::is_signed<char>::value && std::is_same<char, typename std::remove_cv<InputCharType>::type>::value > * = nullptr > static constexpr CharType to_char_type(InputCharType x) noexcept { return x; } private: /// whether we can assume little endianess const bool is_little_endian = little_endianess(); /// the output output_adapter_t<CharType> oa = nullptr; }; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/output/output_adapters.hpp> // #include <nlohmann/detail/output/serializer.hpp> #include <algorithm> // reverse, remove, fill, find, none_of #include <array> // array #include <clocale> // localeconv, lconv #include <cmath> // labs, isfinite, isnan, signbit #include <cstddef> // size_t, ptrdiff_t #include <cstdint> // uint8_t #include <cstdio> // snprintf #include <limits> // numeric_limits #include <string> // string, char_traits #include <type_traits> // is_same #include <utility> // move // #include <nlohmann/detail/conversions/to_chars.hpp> #include <array> // array #include <cmath> // signbit, isfinite #include <cstdint> // intN_t, uintN_t #include <cstring> // memcpy, memmove #include <limits> // numeric_limits #include <type_traits> // conditional // #include <nlohmann/detail/macro_scope.hpp> namespace nlohmann { namespace detail { /*! @brief implements the Grisu2 algorithm for binary to decimal floating-point conversion. This implementation is a slightly modified version of the reference implementation which may be obtained from http://florian.loitsch.com/publications (bench.tar.gz). The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch. For a detailed description of the algorithm see: [1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming Language Design and Implementation, PLDI 2010 [2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately", Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language Design and Implementation, PLDI 1996 */ namespace dtoa_impl { template<typename Target, typename Source> Target reinterpret_bits(const Source source) { static_assert(sizeof(Target) == sizeof(Source), "size mismatch"); Target target; std::memcpy(&target, &source, sizeof(Source)); return target; } struct diyfp // f * 2^e { static constexpr int kPrecision = 64; // = q std::uint64_t f = 0; int e = 0; constexpr diyfp(std::uint64_t f_, int e_) noexcept : f(f_), e(e_) {} /*! @brief returns x - y @pre x.e == y.e and x.f >= y.f */ static diyfp sub(const diyfp& x, const diyfp& y) noexcept { JSON_ASSERT(x.e == y.e); JSON_ASSERT(x.f >= y.f); return {x.f - y.f, x.e}; } /*! @brief returns x * y @note The result is rounded. (Only the upper q bits are returned.) */ static diyfp mul(const diyfp& x, const diyfp& y) noexcept { static_assert(kPrecision == 64, "internal error"); // Computes: // f = round((x.f * y.f) / 2^q) // e = x.e + y.e + q // Emulate the 64-bit * 64-bit multiplication: // // p = u * v // = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi) // = (u_lo v_lo ) + 2^32 ((u_lo v_hi ) + (u_hi v_lo )) + 2^64 (u_hi v_hi ) // = (p0 ) + 2^32 ((p1 ) + (p2 )) + 2^64 (p3 ) // = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 ) // = (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi + p2_hi + p3) // = (p0_lo ) + 2^32 (Q ) + 2^64 (H ) // = (p0_lo ) + 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H ) // // (Since Q might be larger than 2^32 - 1) // // = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H) // // (Q_hi + H does not overflow a 64-bit int) // // = p_lo + 2^64 p_hi const std::uint64_t u_lo = x.f & 0xFFFFFFFFu; const std::uint64_t u_hi = x.f >> 32u; const std::uint64_t v_lo = y.f & 0xFFFFFFFFu; const std::uint64_t v_hi = y.f >> 32u; const std::uint64_t p0 = u_lo * v_lo; const std::uint64_t p1 = u_lo * v_hi; const std::uint64_t p2 = u_hi * v_lo; const std::uint64_t p3 = u_hi * v_hi; const std::uint64_t p0_hi = p0 >> 32u; const std::uint64_t p1_lo = p1 & 0xFFFFFFFFu; const std::uint64_t p1_hi = p1 >> 32u; const std::uint64_t p2_lo = p2 & 0xFFFFFFFFu; const std::uint64_t p2_hi = p2 >> 32u; std::uint64_t Q = p0_hi + p1_lo + p2_lo; // The full product might now be computed as // // p_hi = p3 + p2_hi + p1_hi + (Q >> 32) // p_lo = p0_lo + (Q << 32) // // But in this particular case here, the full p_lo is not required. // Effectively we only need to add the highest bit in p_lo to p_hi (and // Q_hi + 1 does not overflow). Q += std::uint64_t{1} << (64u - 32u - 1u); // round, ties up const std::uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32u); return {h, x.e + y.e + 64}; } /*! @brief normalize x such that the significand is >= 2^(q-1) @pre x.f != 0 */ static diyfp normalize(diyfp x) noexcept { JSON_ASSERT(x.f != 0); while ((x.f >> 63u) == 0) { x.f <<= 1u; x.e--; } return x; } /*! @brief normalize x such that the result has the exponent E @pre e >= x.e and the upper e - x.e bits of x.f must be zero. */ static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept { const int delta = x.e - target_exponent; JSON_ASSERT(delta >= 0); JSON_ASSERT(((x.f << delta) >> delta) == x.f); return {x.f << delta, target_exponent}; } }; struct boundaries { diyfp w; diyfp minus; diyfp plus; }; /*! Compute the (normalized) diyfp representing the input number 'value' and its boundaries. @pre value must be finite and positive */ template<typename FloatType> boundaries compute_boundaries(FloatType value) { JSON_ASSERT(std::isfinite(value)); JSON_ASSERT(value > 0); // Convert the IEEE representation into a diyfp. // // If v is denormal: // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1)) // If v is normalized: // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1)) static_assert(std::numeric_limits<FloatType>::is_iec559, "internal error: dtoa_short requires an IEEE-754 floating-point implementation"); constexpr int kPrecision = std::numeric_limits<FloatType>::digits; // = p (includes the hidden bit) constexpr int kBias = std::numeric_limits<FloatType>::max_exponent - 1 + (kPrecision - 1); constexpr int kMinExp = 1 - kBias; constexpr std::uint64_t kHiddenBit = std::uint64_t{1} << (kPrecision - 1); // = 2^(p-1) using bits_type = typename std::conditional<kPrecision == 24, std::uint32_t, std::uint64_t >::type; const auto bits = static_cast<std::uint64_t>(reinterpret_bits<bits_type>(value)); const std::uint64_t E = bits >> (kPrecision - 1); const std::uint64_t F = bits & (kHiddenBit - 1); const bool is_denormal = E == 0; const diyfp v = is_denormal ? diyfp(F, kMinExp) : diyfp(F + kHiddenBit, static_cast<int>(E) - kBias); // Compute the boundaries m- and m+ of the floating-point value // v = f * 2^e. // // Determine v- and v+, the floating-point predecessor and successor if v, // respectively. // // v- = v - 2^e if f != 2^(p-1) or e == e_min (A) // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B) // // v+ = v + 2^e // // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_ // between m- and m+ round to v, regardless of how the input rounding // algorithm breaks ties. // // ---+-------------+-------------+-------------+-------------+--- (A) // v- m- v m+ v+ // // -----------------+------+------+-------------+-------------+--- (B) // v- m- v m+ v+ const bool lower_boundary_is_closer = F == 0 && E > 1; const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1); const diyfp m_minus = lower_boundary_is_closer ? diyfp(4 * v.f - 1, v.e - 2) // (B) : diyfp(2 * v.f - 1, v.e - 1); // (A) // Determine the normalized w+ = m+. const diyfp w_plus = diyfp::normalize(m_plus); // Determine w- = m- such that e_(w-) = e_(w+). const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e); return {diyfp::normalize(v), w_minus, w_plus}; } // Given normalized diyfp w, Grisu needs to find a (normalized) cached // power-of-ten c, such that the exponent of the product c * w = f * 2^e lies // within a certain range [alpha, gamma] (Definition 3.2 from [1]) // // alpha <= e = e_c + e_w + q <= gamma // // or // // f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q // <= f_c * f_w * 2^gamma // // Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies // // 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma // // or // // 2^(q - 2 + alpha) <= c * w < 2^(q + gamma) // // The choice of (alpha,gamma) determines the size of the table and the form of // the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well // in practice: // // The idea is to cut the number c * w = f * 2^e into two parts, which can be // processed independently: An integral part p1, and a fractional part p2: // // f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e // = (f div 2^-e) + (f mod 2^-e) * 2^e // = p1 + p2 * 2^e // // The conversion of p1 into decimal form requires a series of divisions and // modulos by (a power of) 10. These operations are faster for 32-bit than for // 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be // achieved by choosing // // -e >= 32 or e <= -32 := gamma // // In order to convert the fractional part // // p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ... // // into decimal form, the fraction is repeatedly multiplied by 10 and the digits // d[-i] are extracted in order: // // (10 * p2) div 2^-e = d[-1] // (10 * p2) mod 2^-e = d[-2] / 10^1 + ... // // The multiplication by 10 must not overflow. It is sufficient to choose // // 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64. // // Since p2 = f mod 2^-e < 2^-e, // // -e <= 60 or e >= -60 := alpha constexpr int kAlpha = -60; constexpr int kGamma = -32; struct cached_power // c = f * 2^e ~= 10^k { std::uint64_t f; int e; int k; }; /*! For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c satisfies (Definition 3.2 from [1]) alpha <= e_c + e + q <= gamma. */ inline cached_power get_cached_power_for_binary_exponent(int e) { // Now // // alpha <= e_c + e + q <= gamma (1) // ==> f_c * 2^alpha <= c * 2^e * 2^q // // and since the c's are normalized, 2^(q-1) <= f_c, // // ==> 2^(q - 1 + alpha) <= c * 2^(e + q) // ==> 2^(alpha - e - 1) <= c // // If c were an exact power of ten, i.e. c = 10^k, one may determine k as // // k = ceil( log_10( 2^(alpha - e - 1) ) ) // = ceil( (alpha - e - 1) * log_10(2) ) // // From the paper: // "In theory the result of the procedure could be wrong since c is rounded, // and the computation itself is approximated [...]. In practice, however, // this simple function is sufficient." // // For IEEE double precision floating-point numbers converted into // normalized diyfp's w = f * 2^e, with q = 64, // // e >= -1022 (min IEEE exponent) // -52 (p - 1) // -52 (p - 1, possibly normalize denormal IEEE numbers) // -11 (normalize the diyfp) // = -1137 // // and // // e <= +1023 (max IEEE exponent) // -52 (p - 1) // -11 (normalize the diyfp) // = 960 // // This binary exponent range [-1137,960] results in a decimal exponent // range [-307,324]. One does not need to store a cached power for each // k in this range. For each such k it suffices to find a cached power // such that the exponent of the product lies in [alpha,gamma]. // This implies that the difference of the decimal exponents of adjacent // table entries must be less than or equal to // // floor( (gamma - alpha) * log_10(2) ) = 8. // // (A smaller distance gamma-alpha would require a larger table.) // NB: // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34. constexpr int kCachedPowersMinDecExp = -300; constexpr int kCachedPowersDecStep = 8; static constexpr std::array<cached_power, 79> kCachedPowers = { { { 0xAB70FE17C79AC6CA, -1060, -300 }, { 0xFF77B1FCBEBCDC4F, -1034, -292 }, { 0xBE5691EF416BD60C, -1007, -284 }, { 0x8DD01FAD907FFC3C, -980, -276 }, { 0xD3515C2831559A83, -954, -268 }, { 0x9D71AC8FADA6C9B5, -927, -260 }, { 0xEA9C227723EE8BCB, -901, -252 }, { 0xAECC49914078536D, -874, -244 }, { 0x823C12795DB6CE57, -847, -236 }, { 0xC21094364DFB5637, -821, -228 }, { 0x9096EA6F3848984F, -794, -220 }, { 0xD77485CB25823AC7, -768, -212 }, { 0xA086CFCD97BF97F4, -741, -204 }, { 0xEF340A98172AACE5, -715, -196 }, { 0xB23867FB2A35B28E, -688, -188 }, { 0x84C8D4DFD2C63F3B, -661, -180 }, { 0xC5DD44271AD3CDBA, -635, -172 }, { 0x936B9FCEBB25C996, -608, -164 }, { 0xDBAC6C247D62A584, -582, -156 }, { 0xA3AB66580D5FDAF6, -555, -148 }, { 0xF3E2F893DEC3F126, -529, -140 }, { 0xB5B5ADA8AAFF80B8, -502, -132 }, { 0x87625F056C7C4A8B, -475, -124 }, { 0xC9BCFF6034C13053, -449, -116 }, { 0x964E858C91BA2655, -422, -108 }, { 0xDFF9772470297EBD, -396, -100 }, { 0xA6DFBD9FB8E5B88F, -369, -92 }, { 0xF8A95FCF88747D94, -343, -84 }, { 0xB94470938FA89BCF, -316, -76 }, { 0x8A08F0F8BF0F156B, -289, -68 }, { 0xCDB02555653131B6, -263, -60 }, { 0x993FE2C6D07B7FAC, -236, -52 }, { 0xE45C10C42A2B3B06, -210, -44 }, { 0xAA242499697392D3, -183, -36 }, { 0xFD87B5F28300CA0E, -157, -28 }, { 0xBCE5086492111AEB, -130, -20 }, { 0x8CBCCC096F5088CC, -103, -12 }, { 0xD1B71758E219652C, -77, -4 }, { 0x9C40000000000000, -50, 4 }, { 0xE8D4A51000000000, -24, 12 }, { 0xAD78EBC5AC620000, 3, 20 }, { 0x813F3978F8940984, 30, 28 }, { 0xC097CE7BC90715B3, 56, 36 }, { 0x8F7E32CE7BEA5C70, 83, 44 }, { 0xD5D238A4ABE98068, 109, 52 }, { 0x9F4F2726179A2245, 136, 60 }, { 0xED63A231D4C4FB27, 162, 68 }, { 0xB0DE65388CC8ADA8, 189, 76 }, { 0x83C7088E1AAB65DB, 216, 84 }, { 0xC45D1DF942711D9A, 242, 92 }, { 0x924D692CA61BE758, 269, 100 }, { 0xDA01EE641A708DEA, 295, 108 }, { 0xA26DA3999AEF774A, 322, 116 }, { 0xF209787BB47D6B85, 348, 124 }, { 0xB454E4A179DD1877, 375, 132 }, { 0x865B86925B9BC5C2, 402, 140 }, { 0xC83553C5C8965D3D, 428, 148 }, { 0x952AB45CFA97A0B3, 455, 156 }, { 0xDE469FBD99A05FE3, 481, 164 }, { 0xA59BC234DB398C25, 508, 172 }, { 0xF6C69A72A3989F5C, 534, 180 }, { 0xB7DCBF5354E9BECE, 561, 188 }, { 0x88FCF317F22241E2, 588, 196 }, { 0xCC20CE9BD35C78A5, 614, 204 }, { 0x98165AF37B2153DF, 641, 212 }, { 0xE2A0B5DC971F303A, 667, 220 }, { 0xA8D9D1535CE3B396, 694, 228 }, { 0xFB9B7CD9A4A7443C, 720, 236 }, { 0xBB764C4CA7A44410, 747, 244 }, { 0x8BAB8EEFB6409C1A, 774, 252 }, { 0xD01FEF10A657842C, 800, 260 }, { 0x9B10A4E5E9913129, 827, 268 }, { 0xE7109BFBA19C0C9D, 853, 276 }, { 0xAC2820D9623BF429, 880, 284 }, { 0x80444B5E7AA7CF85, 907, 292 }, { 0xBF21E44003ACDD2D, 933, 300 }, { 0x8E679C2F5E44FF8F, 960, 308 }, { 0xD433179D9C8CB841, 986, 316 }, { 0x9E19DB92B4E31BA9, 1013, 324 }, } }; // This computation gives exactly the same results for k as // k = ceil((kAlpha - e - 1) * 0.30102999566398114) // for |e| <= 1500, but doesn't require floating-point operations. // NB: log_10(2) ~= 78913 / 2^18 JSON_ASSERT(e >= -1500); JSON_ASSERT(e <= 1500); const int f = kAlpha - e - 1; const int k = (f * 78913) / (1 << 18) + static_cast<int>(f > 0); const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep; JSON_ASSERT(index >= 0); JSON_ASSERT(static_cast<std::size_t>(index) < kCachedPowers.size()); const cached_power cached = kCachedPowers[static_cast<std::size_t>(index)]; JSON_ASSERT(kAlpha <= cached.e + e + 64); JSON_ASSERT(kGamma >= cached.e + e + 64); return cached; } /*! For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k. For n == 0, returns 1 and sets pow10 := 1. */ inline int find_largest_pow10(const std::uint32_t n, std::uint32_t& pow10) { // LCOV_EXCL_START if (n >= 1000000000) { pow10 = 1000000000; return 10; } // LCOV_EXCL_STOP if (n >= 100000000) { pow10 = 100000000; return 9; } if (n >= 10000000) { pow10 = 10000000; return 8; } if (n >= 1000000) { pow10 = 1000000; return 7; } if (n >= 100000) { pow10 = 100000; return 6; } if (n >= 10000) { pow10 = 10000; return 5; } if (n >= 1000) { pow10 = 1000; return 4; } if (n >= 100) { pow10 = 100; return 3; } if (n >= 10) { pow10 = 10; return 2; } pow10 = 1; return 1; } inline void grisu2_round(char* buf, int len, std::uint64_t dist, std::uint64_t delta, std::uint64_t rest, std::uint64_t ten_k) { JSON_ASSERT(len >= 1); JSON_ASSERT(dist <= delta); JSON_ASSERT(rest <= delta); JSON_ASSERT(ten_k > 0); // <--------------------------- delta ----> // <---- dist ---------> // --------------[------------------+-------------------]-------------- // M- w M+ // // ten_k // <------> // <---- rest ----> // --------------[------------------+----+--------------]-------------- // w V // = buf * 10^k // // ten_k represents a unit-in-the-last-place in the decimal representation // stored in buf. // Decrement buf by ten_k while this takes buf closer to w. // The tests are written in this order to avoid overflow in unsigned // integer arithmetic. while (rest < dist && delta - rest >= ten_k && (rest + ten_k < dist || dist - rest > rest + ten_k - dist)) { JSON_ASSERT(buf[len - 1] != '0'); buf[len - 1]--; rest += ten_k; } } /*! Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+. M- and M+ must be normalized and share the same exponent -60 <= e <= -32. */ inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent, diyfp M_minus, diyfp w, diyfp M_plus) { static_assert(kAlpha >= -60, "internal error"); static_assert(kGamma <= -32, "internal error"); // Generates the digits (and the exponent) of a decimal floating-point // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma. // // <--------------------------- delta ----> // <---- dist ---------> // --------------[------------------+-------------------]-------------- // M- w M+ // // Grisu2 generates the digits of M+ from left to right and stops as soon as // V is in [M-,M+]. JSON_ASSERT(M_plus.e >= kAlpha); JSON_ASSERT(M_plus.e <= kGamma); std::uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e) std::uint64_t dist = diyfp::sub(M_plus, w ).f; // (significand of (M+ - w ), implicit exponent is e) // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0): // // M+ = f * 2^e // = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e // = ((p1 ) * 2^-e + (p2 )) * 2^e // = p1 + p2 * 2^e const diyfp one(std::uint64_t{1} << -M_plus.e, M_plus.e); auto p1 = static_cast<std::uint32_t>(M_plus.f >> -one.e); // p1 = f div 2^-e (Since -e >= 32, p1 fits into a 32-bit int.) std::uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e // 1) // // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0] JSON_ASSERT(p1 > 0); std::uint32_t pow10{}; const int k = find_largest_pow10(p1, pow10); // 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1) // // p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1)) // = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1)) // // M+ = p1 + p2 * 2^e // = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e // = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e // = d[k-1] * 10^(k-1) + ( rest) * 2^e // // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0) // // p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0] // // but stop as soon as // // rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e int n = k; while (n > 0) { // Invariants: // M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k) // pow10 = 10^(n-1) <= p1 < 10^n // const std::uint32_t d = p1 / pow10; // d = p1 div 10^(n-1) const std::uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1) // // M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e // = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e) // JSON_ASSERT(d <= 9); buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d // // M+ = buffer * 10^(n-1) + (r + p2 * 2^e) // p1 = r; n--; // // M+ = buffer * 10^n + (p1 + p2 * 2^e) // pow10 = 10^n // // Now check if enough digits have been generated. // Compute // // p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e // // Note: // Since rest and delta share the same exponent e, it suffices to // compare the significands. const std::uint64_t rest = (std::uint64_t{p1} << -one.e) + p2; if (rest <= delta) { // V = buffer * 10^n, with M- <= V <= M+. decimal_exponent += n; // We may now just stop. But instead look if the buffer could be // decremented to bring V closer to w. // // pow10 = 10^n is now 1 ulp in the decimal representation V. // The rounding procedure works with diyfp's with an implicit // exponent of e. // // 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e // const std::uint64_t ten_n = std::uint64_t{pow10} << -one.e; grisu2_round(buffer, length, dist, delta, rest, ten_n); return; } pow10 /= 10; // // pow10 = 10^(n-1) <= p1 < 10^n // Invariants restored. } // 2) // // The digits of the integral part have been generated: // // M+ = d[k-1]...d[1]d[0] + p2 * 2^e // = buffer + p2 * 2^e // // Now generate the digits of the fractional part p2 * 2^e. // // Note: // No decimal point is generated: the exponent is adjusted instead. // // p2 actually represents the fraction // // p2 * 2^e // = p2 / 2^-e // = d[-1] / 10^1 + d[-2] / 10^2 + ... // // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...) // // p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m // + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...) // // using // // 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e) // = ( d) * 2^-e + ( r) // // or // 10^m * p2 * 2^e = d + r * 2^e // // i.e. // // M+ = buffer + p2 * 2^e // = buffer + 10^-m * (d + r * 2^e) // = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e // // and stop as soon as 10^-m * r * 2^e <= delta * 2^e JSON_ASSERT(p2 > delta); int m = 0; for (;;) { // Invariant: // M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e // = buffer * 10^-m + 10^-m * (p2 ) * 2^e // = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e // = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e // JSON_ASSERT(p2 <= (std::numeric_limits<std::uint64_t>::max)() / 10); p2 *= 10; const std::uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e const std::uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e // // M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e // = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e)) // = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e // JSON_ASSERT(d <= 9); buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d // // M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e // p2 = r; m++; // // M+ = buffer * 10^-m + 10^-m * p2 * 2^e // Invariant restored. // Check if enough digits have been generated. // // 10^-m * p2 * 2^e <= delta * 2^e // p2 * 2^e <= 10^m * delta * 2^e // p2 <= 10^m * delta delta *= 10; dist *= 10; if (p2 <= delta) { break; } } // V = buffer * 10^-m, with M- <= V <= M+. decimal_exponent -= m; // 1 ulp in the decimal representation is now 10^-m. // Since delta and dist are now scaled by 10^m, we need to do the // same with ulp in order to keep the units in sync. // // 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e // const std::uint64_t ten_m = one.f; grisu2_round(buffer, length, dist, delta, p2, ten_m); // By construction this algorithm generates the shortest possible decimal // number (Loitsch, Theorem 6.2) which rounds back to w. // For an input number of precision p, at least // // N = 1 + ceil(p * log_10(2)) // // decimal digits are sufficient to identify all binary floating-point // numbers (Matula, "In-and-Out conversions"). // This implies that the algorithm does not produce more than N decimal // digits. // // N = 17 for p = 53 (IEEE double precision) // N = 9 for p = 24 (IEEE single precision) } /*! v = buf * 10^decimal_exponent len is the length of the buffer (number of decimal digits) The buffer must be large enough, i.e. >= max_digits10. */ JSON_HEDLEY_NON_NULL(1) inline void grisu2(char* buf, int& len, int& decimal_exponent, diyfp m_minus, diyfp v, diyfp m_plus) { JSON_ASSERT(m_plus.e == m_minus.e); JSON_ASSERT(m_plus.e == v.e); // --------(-----------------------+-----------------------)-------- (A) // m- v m+ // // --------------------(-----------+-----------------------)-------- (B) // m- v m+ // // First scale v (and m- and m+) such that the exponent is in the range // [alpha, gamma]. const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e); const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma] const diyfp w = diyfp::mul(v, c_minus_k); const diyfp w_minus = diyfp::mul(m_minus, c_minus_k); const diyfp w_plus = diyfp::mul(m_plus, c_minus_k); // ----(---+---)---------------(---+---)---------------(---+---)---- // w- w w+ // = c*m- = c*v = c*m+ // // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and // w+ are now off by a small amount. // In fact: // // w - v * 10^k < 1 ulp // // To account for this inaccuracy, add resp. subtract 1 ulp. // // --------+---[---------------(---+---)---------------]---+-------- // w- M- w M+ w+ // // Now any number in [M-, M+] (bounds included) will round to w when input, // regardless of how the input rounding algorithm breaks ties. // // And digit_gen generates the shortest possible such number in [M-, M+]. // Note that this does not mean that Grisu2 always generates the shortest // possible number in the interval (m-, m+). const diyfp M_minus(w_minus.f + 1, w_minus.e); const diyfp M_plus (w_plus.f - 1, w_plus.e ); decimal_exponent = -cached.k; // = -(-k) = k grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus); } /*! v = buf * 10^decimal_exponent len is the length of the buffer (number of decimal digits) The buffer must be large enough, i.e. >= max_digits10. */ template<typename FloatType> JSON_HEDLEY_NON_NULL(1) void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value) { static_assert(diyfp::kPrecision >= std::numeric_limits<FloatType>::digits + 3, "internal error: not enough precision"); JSON_ASSERT(std::isfinite(value)); JSON_ASSERT(value > 0); // If the neighbors (and boundaries) of 'value' are always computed for double-precision // numbers, all float's can be recovered using strtod (and strtof). However, the resulting // decimal representations are not exactly "short". // // The documentation for 'std::to_chars' (https://en.cppreference.com/w/cpp/utility/to_chars) // says "value is converted to a string as if by std::sprintf in the default ("C") locale" // and since sprintf promotes float's to double's, I think this is exactly what 'std::to_chars' // does. // On the other hand, the documentation for 'std::to_chars' requires that "parsing the // representation using the corresponding std::from_chars function recovers value exactly". That // indicates that single precision floating-point numbers should be recovered using // 'std::strtof'. // // NB: If the neighbors are computed for single-precision numbers, there is a single float // (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision // value is off by 1 ulp. #if 0 const boundaries w = compute_boundaries(static_cast<double>(value)); #else const boundaries w = compute_boundaries(value); #endif grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus); } /*! @brief appends a decimal representation of e to buf @return a pointer to the element following the exponent. @pre -1000 < e < 1000 */ JSON_HEDLEY_NON_NULL(1) JSON_HEDLEY_RETURNS_NON_NULL inline char* append_exponent(char* buf, int e) { JSON_ASSERT(e > -1000); JSON_ASSERT(e < 1000); if (e < 0) { e = -e; *buf++ = '-'; } else { *buf++ = '+'; } auto k = static_cast<std::uint32_t>(e); if (k < 10) { // Always print at least two digits in the exponent. // This is for compatibility with printf("%g"). *buf++ = '0'; *buf++ = static_cast<char>('0' + k); } else if (k < 100) { *buf++ = static_cast<char>('0' + k / 10); k %= 10; *buf++ = static_cast<char>('0' + k); } else { *buf++ = static_cast<char>('0' + k / 100); k %= 100; *buf++ = static_cast<char>('0' + k / 10); k %= 10; *buf++ = static_cast<char>('0' + k); } return buf; } /*! @brief prettify v = buf * 10^decimal_exponent If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point notation. Otherwise it will be printed in exponential notation. @pre min_exp < 0 @pre max_exp > 0 */ JSON_HEDLEY_NON_NULL(1) JSON_HEDLEY_RETURNS_NON_NULL inline char* format_buffer(char* buf, int len, int decimal_exponent, int min_exp, int max_exp) { JSON_ASSERT(min_exp < 0); JSON_ASSERT(max_exp > 0); const int k = len; const int n = len + decimal_exponent; // v = buf * 10^(n-k) // k is the length of the buffer (number of decimal digits) // n is the position of the decimal point relative to the start of the buffer. if (k <= n && n <= max_exp) { // digits[000] // len <= max_exp + 2 std::memset(buf + k, '0', static_cast<size_t>(n) - static_cast<size_t>(k)); // Make it look like a floating-point number (#362, #378) buf[n + 0] = '.'; buf[n + 1] = '0'; return buf + (static_cast<size_t>(n) + 2); } if (0 < n && n <= max_exp) { // dig.its // len <= max_digits10 + 1 JSON_ASSERT(k > n); std::memmove(buf + (static_cast<size_t>(n) + 1), buf + n, static_cast<size_t>(k) - static_cast<size_t>(n)); buf[n] = '.'; return buf + (static_cast<size_t>(k) + 1U); } if (min_exp < n && n <= 0) { // 0.[000]digits // len <= 2 + (-min_exp - 1) + max_digits10 std::memmove(buf + (2 + static_cast<size_t>(-n)), buf, static_cast<size_t>(k)); buf[0] = '0'; buf[1] = '.'; std::memset(buf + 2, '0', static_cast<size_t>(-n)); return buf + (2U + static_cast<size_t>(-n) + static_cast<size_t>(k)); } if (k == 1) { // dE+123 // len <= 1 + 5 buf += 1; } else { // d.igitsE+123 // len <= max_digits10 + 1 + 5 std::memmove(buf + 2, buf + 1, static_cast<size_t>(k) - 1); buf[1] = '.'; buf += 1 + static_cast<size_t>(k); } *buf++ = 'e'; return append_exponent(buf, n - 1); } } // namespace dtoa_impl /*! @brief generates a decimal representation of the floating-point number value in [first, last). The format of the resulting decimal representation is similar to printf's %g format. Returns an iterator pointing past-the-end of the decimal representation. @note The input number must be finite, i.e. NaN's and Inf's are not supported. @note The buffer must be large enough. @note The result is NOT null-terminated. */ template<typename FloatType> JSON_HEDLEY_NON_NULL(1, 2) JSON_HEDLEY_RETURNS_NON_NULL char* to_chars(char* first, const char* last, FloatType value) { static_cast<void>(last); // maybe unused - fix warning JSON_ASSERT(std::isfinite(value)); // Use signbit(value) instead of (value < 0) since signbit works for -0. if (std::signbit(value)) { value = -value; *first++ = '-'; } if (value == 0) // +-0 { *first++ = '0'; // Make it look like a floating-point number (#362, #378) *first++ = '.'; *first++ = '0'; return first; } JSON_ASSERT(last - first >= std::numeric_limits<FloatType>::max_digits10); // Compute v = buffer * 10^decimal_exponent. // The decimal digits are stored in the buffer, which needs to be interpreted // as an unsigned decimal integer. // len is the length of the buffer, i.e. the number of decimal digits. int len = 0; int decimal_exponent = 0; dtoa_impl::grisu2(first, len, decimal_exponent, value); JSON_ASSERT(len <= std::numeric_limits<FloatType>::max_digits10); // Format the buffer like printf("%.*g", prec, value) constexpr int kMinExp = -4; // Use digits10 here to increase compatibility with version 2. constexpr int kMaxExp = std::numeric_limits<FloatType>::digits10; JSON_ASSERT(last - first >= kMaxExp + 2); JSON_ASSERT(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits<FloatType>::max_digits10); JSON_ASSERT(last - first >= std::numeric_limits<FloatType>::max_digits10 + 6); return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp); } } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/exceptions.hpp> // #include <nlohmann/detail/macro_scope.hpp> // #include <nlohmann/detail/meta/cpp_future.hpp> // #include <nlohmann/detail/output/binary_writer.hpp> // #include <nlohmann/detail/output/output_adapters.hpp> // #include <nlohmann/detail/value_t.hpp> namespace nlohmann { namespace detail { /////////////////// // serialization // /////////////////// /// how to treat decoding errors enum class error_handler_t { strict, ///< throw a type_error exception in case of invalid UTF-8 replace, ///< replace invalid UTF-8 sequences with U+FFFD ignore ///< ignore invalid UTF-8 sequences }; template<typename BasicJsonType> class serializer { using string_t = typename BasicJsonType::string_t; using number_float_t = typename BasicJsonType::number_float_t; using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using binary_char_t = typename BasicJsonType::binary_t::value_type; static constexpr std::uint8_t UTF8_ACCEPT = 0; static constexpr std::uint8_t UTF8_REJECT = 1; public: /*! @param[in] s output stream to serialize to @param[in] ichar indentation character to use @param[in] error_handler_ how to react on decoding errors */ serializer(output_adapter_t<char> s, const char ichar, error_handler_t error_handler_ = error_handler_t::strict) : o(std::move(s)) , loc(std::localeconv()) , thousands_sep(loc->thousands_sep == nullptr ? '\0' : std::char_traits<char>::to_char_type(* (loc->thousands_sep))) , decimal_point(loc->decimal_point == nullptr ? '\0' : std::char_traits<char>::to_char_type(* (loc->decimal_point))) , indent_char(ichar) , indent_string(512, indent_char) , error_handler(error_handler_) {} // delete because of pointer members serializer(const serializer&) = delete; serializer& operator=(const serializer&) = delete; serializer(serializer&&) = delete; serializer& operator=(serializer&&) = delete; ~serializer() = default; /*! @brief internal implementation of the serialization function This function is called by the public member function dump and organizes the serialization internally. The indentation level is propagated as additional parameter. In case of arrays and objects, the function is called recursively. - strings and object keys are escaped using `escape_string()` - integer numbers are converted implicitly via `operator<<` - floating-point numbers are converted to a string using `"%g"` format - binary values are serialized as objects containing the subtype and the byte array @param[in] val value to serialize @param[in] pretty_print whether the output shall be pretty-printed @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters in the output are escaped with `\uXXXX` sequences, and the result consists of ASCII characters only. @param[in] indent_step the indent level @param[in] current_indent the current indent level (only used internally) */ void dump(const BasicJsonType& val, const bool pretty_print, const bool ensure_ascii, const unsigned int indent_step, const unsigned int current_indent = 0) { switch (val.m_type) { case value_t::object: { if (val.m_value.object->empty()) { o->write_characters("{}", 2); return; } if (pretty_print) { o->write_characters("{\n", 2); // variable to hold indentation for recursive calls const auto new_indent = current_indent + indent_step; if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent)) { indent_string.resize(indent_string.size() * 2, ' '); } // first n-1 elements auto i = val.m_value.object->cbegin(); for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i) { o->write_characters(indent_string.c_str(), new_indent); o->write_character('\"'); dump_escaped(i->first, ensure_ascii); o->write_characters("\": ", 3); dump(i->second, true, ensure_ascii, indent_step, new_indent); o->write_characters(",\n", 2); } // last element JSON_ASSERT(i != val.m_value.object->cend()); JSON_ASSERT(std::next(i) == val.m_value.object->cend()); o->write_characters(indent_string.c_str(), new_indent); o->write_character('\"'); dump_escaped(i->first, ensure_ascii); o->write_characters("\": ", 3); dump(i->second, true, ensure_ascii, indent_step, new_indent); o->write_character('\n'); o->write_characters(indent_string.c_str(), current_indent); o->write_character('}'); } else { o->write_character('{'); // first n-1 elements auto i = val.m_value.object->cbegin(); for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i) { o->write_character('\"'); dump_escaped(i->first, ensure_ascii); o->write_characters("\":", 2); dump(i->second, false, ensure_ascii, indent_step, current_indent); o->write_character(','); } // last element JSON_ASSERT(i != val.m_value.object->cend()); JSON_ASSERT(std::next(i) == val.m_value.object->cend()); o->write_character('\"'); dump_escaped(i->first, ensure_ascii); o->write_characters("\":", 2); dump(i->second, false, ensure_ascii, indent_step, current_indent); o->write_character('}'); } return; } case value_t::array: { if (val.m_value.array->empty()) { o->write_characters("[]", 2); return; } if (pretty_print) { o->write_characters("[\n", 2); // variable to hold indentation for recursive calls const auto new_indent = current_indent + indent_step; if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent)) { indent_string.resize(indent_string.size() * 2, ' '); } // first n-1 elements for (auto i = val.m_value.array->cbegin(); i != val.m_value.array->cend() - 1; ++i) { o->write_characters(indent_string.c_str(), new_indent); dump(*i, true, ensure_ascii, indent_step, new_indent); o->write_characters(",\n", 2); } // last element JSON_ASSERT(!val.m_value.array->empty()); o->write_characters(indent_string.c_str(), new_indent); dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent); o->write_character('\n'); o->write_characters(indent_string.c_str(), current_indent); o->write_character(']'); } else { o->write_character('['); // first n-1 elements for (auto i = val.m_value.array->cbegin(); i != val.m_value.array->cend() - 1; ++i) { dump(*i, false, ensure_ascii, indent_step, current_indent); o->write_character(','); } // last element JSON_ASSERT(!val.m_value.array->empty()); dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent); o->write_character(']'); } return; } case value_t::string: { o->write_character('\"'); dump_escaped(*val.m_value.string, ensure_ascii); o->write_character('\"'); return; } case value_t::binary: { if (pretty_print) { o->write_characters("{\n", 2); // variable to hold indentation for recursive calls const auto new_indent = current_indent + indent_step; if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent)) { indent_string.resize(indent_string.size() * 2, ' '); } o->write_characters(indent_string.c_str(), new_indent); o->write_characters("\"bytes\": [", 10); if (!val.m_value.binary->empty()) { for (auto i = val.m_value.binary->cbegin(); i != val.m_value.binary->cend() - 1; ++i) { dump_integer(*i); o->write_characters(", ", 2); } dump_integer(val.m_value.binary->back()); } o->write_characters("],\n", 3); o->write_characters(indent_string.c_str(), new_indent); o->write_characters("\"subtype\": ", 11); if (val.m_value.binary->has_subtype()) { dump_integer(val.m_value.binary->subtype()); } else { o->write_characters("null", 4); } o->write_character('\n'); o->write_characters(indent_string.c_str(), current_indent); o->write_character('}'); } else { o->write_characters("{\"bytes\":[", 10); if (!val.m_value.binary->empty()) { for (auto i = val.m_value.binary->cbegin(); i != val.m_value.binary->cend() - 1; ++i) { dump_integer(*i); o->write_character(','); } dump_integer(val.m_value.binary->back()); } o->write_characters("],\"subtype\":", 12); if (val.m_value.binary->has_subtype()) { dump_integer(val.m_value.binary->subtype()); o->write_character('}'); } else { o->write_characters("null}", 5); } } return; } case value_t::boolean: { if (val.m_value.boolean) { o->write_characters("true", 4); } else { o->write_characters("false", 5); } return; } case value_t::number_integer: { dump_integer(val.m_value.number_integer); return; } case value_t::number_unsigned: { dump_integer(val.m_value.number_unsigned); return; } case value_t::number_float: { dump_float(val.m_value.number_float); return; } case value_t::discarded: { o->write_characters("<discarded>", 11); return; } case value_t::null: { o->write_characters("null", 4); return; } default: // LCOV_EXCL_LINE JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE } } JSON_PRIVATE_UNLESS_TESTED: /*! @brief dump escaped string Escape a string by replacing certain special characters by a sequence of an escape character (backslash) and another character and other control characters by a sequence of "\u" followed by a four-digit hex representation. The escaped string is written to output stream @a o. @param[in] s the string to escape @param[in] ensure_ascii whether to escape non-ASCII characters with \uXXXX sequences @complexity Linear in the length of string @a s. */ void dump_escaped(const string_t& s, const bool ensure_ascii) { std::uint32_t codepoint{}; std::uint8_t state = UTF8_ACCEPT; std::size_t bytes = 0; // number of bytes written to string_buffer // number of bytes written at the point of the last valid byte std::size_t bytes_after_last_accept = 0; std::size_t undumped_chars = 0; for (std::size_t i = 0; i < s.size(); ++i) { const auto byte = static_cast<uint8_t>(s[i]); switch (decode(state, codepoint, byte)) { case UTF8_ACCEPT: // decode found a new code point { switch (codepoint) { case 0x08: // backspace { string_buffer[bytes++] = '\\'; string_buffer[bytes++] = 'b'; break; } case 0x09: // horizontal tab { string_buffer[bytes++] = '\\'; string_buffer[bytes++] = 't'; break; } case 0x0A: // newline { string_buffer[bytes++] = '\\'; string_buffer[bytes++] = 'n'; break; } case 0x0C: // formfeed { string_buffer[bytes++] = '\\'; string_buffer[bytes++] = 'f'; break; } case 0x0D: // carriage return { string_buffer[bytes++] = '\\'; string_buffer[bytes++] = 'r'; break; } case 0x22: // quotation mark { string_buffer[bytes++] = '\\'; string_buffer[bytes++] = '\"'; break; } case 0x5C: // reverse solidus { string_buffer[bytes++] = '\\'; string_buffer[bytes++] = '\\'; break; } default: { // escape control characters (0x00..0x1F) or, if // ensure_ascii parameter is used, non-ASCII characters if ((codepoint <= 0x1F) || (ensure_ascii && (codepoint >= 0x7F))) { if (codepoint <= 0xFFFF) { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg) (std::snprintf)(string_buffer.data() + bytes, 7, "\\u%04x", static_cast<std::uint16_t>(codepoint)); bytes += 6; } else { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg) (std::snprintf)(string_buffer.data() + bytes, 13, "\\u%04x\\u%04x", static_cast<std::uint16_t>(0xD7C0u + (codepoint >> 10u)), static_cast<std::uint16_t>(0xDC00u + (codepoint & 0x3FFu))); bytes += 12; } } else { // copy byte to buffer (all previous bytes // been copied have in default case above) string_buffer[bytes++] = s[i]; } break; } } // write buffer and reset index; there must be 13 bytes // left, as this is the maximal number of bytes to be // written ("\uxxxx\uxxxx\0") for one code point if (string_buffer.size() - bytes < 13) { o->write_characters(string_buffer.data(), bytes); bytes = 0; } // remember the byte position of this accept bytes_after_last_accept = bytes; undumped_chars = 0; break; } case UTF8_REJECT: // decode found invalid UTF-8 byte { switch (error_handler) { case error_handler_t::strict: { std::string sn(9, '\0'); // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg) (std::snprintf)(&sn[0], sn.size(), "%.2X", byte); JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + sn, BasicJsonType())); } case error_handler_t::ignore: case error_handler_t::replace: { // in case we saw this character the first time, we // would like to read it again, because the byte // may be OK for itself, but just not OK for the // previous sequence if (undumped_chars > 0) { --i; } // reset length buffer to the last accepted index; // thus removing/ignoring the invalid characters bytes = bytes_after_last_accept; if (error_handler == error_handler_t::replace) { // add a replacement character if (ensure_ascii) { string_buffer[bytes++] = '\\'; string_buffer[bytes++] = 'u'; string_buffer[bytes++] = 'f'; string_buffer[bytes++] = 'f'; string_buffer[bytes++] = 'f'; string_buffer[bytes++] = 'd'; } else { string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xEF'); string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBF'); string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBD'); } // write buffer and reset index; there must be 13 bytes // left, as this is the maximal number of bytes to be // written ("\uxxxx\uxxxx\0") for one code point if (string_buffer.size() - bytes < 13) { o->write_characters(string_buffer.data(), bytes); bytes = 0; } bytes_after_last_accept = bytes; } undumped_chars = 0; // continue processing the string state = UTF8_ACCEPT; break; } default: // LCOV_EXCL_LINE JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE } break; } default: // decode found yet incomplete multi-byte code point { if (!ensure_ascii) { // code point will not be escaped - copy byte to buffer string_buffer[bytes++] = s[i]; } ++undumped_chars; break; } } } // we finished processing the string if (JSON_HEDLEY_LIKELY(state == UTF8_ACCEPT)) { // write buffer if (bytes > 0) { o->write_characters(string_buffer.data(), bytes); } } else { // we finish reading, but do not accept: string was incomplete switch (error_handler) { case error_handler_t::strict: { std::string sn(9, '\0'); // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg) (std::snprintf)(&sn[0], sn.size(), "%.2X", static_cast<std::uint8_t>(s.back())); JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + sn, BasicJsonType())); } case error_handler_t::ignore: { // write all accepted bytes o->write_characters(string_buffer.data(), bytes_after_last_accept); break; } case error_handler_t::replace: { // write all accepted bytes o->write_characters(string_buffer.data(), bytes_after_last_accept); // add a replacement character if (ensure_ascii) { o->write_characters("\\ufffd", 6); } else { o->write_characters("\xEF\xBF\xBD", 3); } break; } default: // LCOV_EXCL_LINE JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE } } } private: /*! @brief count digits Count the number of decimal (base 10) digits for an input unsigned integer. @param[in] x unsigned integer number to count its digits @return number of decimal digits */ inline unsigned int count_digits(number_unsigned_t x) noexcept { unsigned int n_digits = 1; for (;;) { if (x < 10) { return n_digits; } if (x < 100) { return n_digits + 1; } if (x < 1000) { return n_digits + 2; } if (x < 10000) { return n_digits + 3; } x = x / 10000u; n_digits += 4; } } /*! @brief dump an integer Dump a given integer to output stream @a o. Works internally with @a number_buffer. @param[in] x integer number (signed or unsigned) to dump @tparam NumberType either @a number_integer_t or @a number_unsigned_t */ template < typename NumberType, detail::enable_if_t < std::is_same<NumberType, number_unsigned_t>::value || std::is_same<NumberType, number_integer_t>::value || std::is_same<NumberType, binary_char_t>::value, int > = 0 > void dump_integer(NumberType x) { static constexpr std::array<std::array<char, 2>, 100> digits_to_99 { { {{'0', '0'}}, {{'0', '1'}}, {{'0', '2'}}, {{'0', '3'}}, {{'0', '4'}}, {{'0', '5'}}, {{'0', '6'}}, {{'0', '7'}}, {{'0', '8'}}, {{'0', '9'}}, {{'1', '0'}}, {{'1', '1'}}, {{'1', '2'}}, {{'1', '3'}}, {{'1', '4'}}, {{'1', '5'}}, {{'1', '6'}}, {{'1', '7'}}, {{'1', '8'}}, {{'1', '9'}}, {{'2', '0'}}, {{'2', '1'}}, {{'2', '2'}}, {{'2', '3'}}, {{'2', '4'}}, {{'2', '5'}}, {{'2', '6'}}, {{'2', '7'}}, {{'2', '8'}}, {{'2', '9'}}, {{'3', '0'}}, {{'3', '1'}}, {{'3', '2'}}, {{'3', '3'}}, {{'3', '4'}}, {{'3', '5'}}, {{'3', '6'}}, {{'3', '7'}}, {{'3', '8'}}, {{'3', '9'}}, {{'4', '0'}}, {{'4', '1'}}, {{'4', '2'}}, {{'4', '3'}}, {{'4', '4'}}, {{'4', '5'}}, {{'4', '6'}}, {{'4', '7'}}, {{'4', '8'}}, {{'4', '9'}}, {{'5', '0'}}, {{'5', '1'}}, {{'5', '2'}}, {{'5', '3'}}, {{'5', '4'}}, {{'5', '5'}}, {{'5', '6'}}, {{'5', '7'}}, {{'5', '8'}}, {{'5', '9'}}, {{'6', '0'}}, {{'6', '1'}}, {{'6', '2'}}, {{'6', '3'}}, {{'6', '4'}}, {{'6', '5'}}, {{'6', '6'}}, {{'6', '7'}}, {{'6', '8'}}, {{'6', '9'}}, {{'7', '0'}}, {{'7', '1'}}, {{'7', '2'}}, {{'7', '3'}}, {{'7', '4'}}, {{'7', '5'}}, {{'7', '6'}}, {{'7', '7'}}, {{'7', '8'}}, {{'7', '9'}}, {{'8', '0'}}, {{'8', '1'}}, {{'8', '2'}}, {{'8', '3'}}, {{'8', '4'}}, {{'8', '5'}}, {{'8', '6'}}, {{'8', '7'}}, {{'8', '8'}}, {{'8', '9'}}, {{'9', '0'}}, {{'9', '1'}}, {{'9', '2'}}, {{'9', '3'}}, {{'9', '4'}}, {{'9', '5'}}, {{'9', '6'}}, {{'9', '7'}}, {{'9', '8'}}, {{'9', '9'}}, } }; // special case for "0" if (x == 0) { o->write_character('0'); return; } // use a pointer to fill the buffer auto buffer_ptr = number_buffer.begin(); // NOLINT(llvm-qualified-auto,readability-qualified-auto,cppcoreguidelines-pro-type-vararg,hicpp-vararg) const bool is_negative = std::is_same<NumberType, number_integer_t>::value && !(x >= 0); // see issue #755 number_unsigned_t abs_value; unsigned int n_chars{}; if (is_negative) { *buffer_ptr = '-'; abs_value = remove_sign(static_cast<number_integer_t>(x)); // account one more byte for the minus sign n_chars = 1 + count_digits(abs_value); } else { abs_value = static_cast<number_unsigned_t>(x); n_chars = count_digits(abs_value); } // spare 1 byte for '\0' JSON_ASSERT(n_chars < number_buffer.size() - 1); // jump to the end to generate the string from backward // so we later avoid reversing the result buffer_ptr += n_chars; // Fast int2ascii implementation inspired by "Fastware" talk by Andrei Alexandrescu // See: https://www.youtube.com/watch?v=o4-CwDo2zpg while (abs_value >= 100) { const auto digits_index = static_cast<unsigned>((abs_value % 100)); abs_value /= 100; *(--buffer_ptr) = digits_to_99[digits_index][1]; *(--buffer_ptr) = digits_to_99[digits_index][0]; } if (abs_value >= 10) { const auto digits_index = static_cast<unsigned>(abs_value); *(--buffer_ptr) = digits_to_99[digits_index][1]; *(--buffer_ptr) = digits_to_99[digits_index][0]; } else { *(--buffer_ptr) = static_cast<char>('0' + abs_value); } o->write_characters(number_buffer.data(), n_chars); } /*! @brief dump a floating-point number Dump a given floating-point number to output stream @a o. Works internally with @a number_buffer. @param[in] x floating-point number to dump */ void dump_float(number_float_t x) { // NaN / inf if (!std::isfinite(x)) { o->write_characters("null", 4); return; } // If number_float_t is an IEEE-754 single or double precision number, // use the Grisu2 algorithm to produce short numbers which are // guaranteed to round-trip, using strtof and strtod, resp. // // NB: The test below works if <long double> == <double>. static constexpr bool is_ieee_single_or_double = (std::numeric_limits<number_float_t>::is_iec559 && std::numeric_limits<number_float_t>::digits == 24 && std::numeric_limits<number_float_t>::max_exponent == 128) || (std::numeric_limits<number_float_t>::is_iec559 && std::numeric_limits<number_float_t>::digits == 53 && std::numeric_limits<number_float_t>::max_exponent == 1024); dump_float(x, std::integral_constant<bool, is_ieee_single_or_double>()); } void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/) { auto* begin = number_buffer.data(); auto* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x); o->write_characters(begin, static_cast<size_t>(end - begin)); } void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/) { // get number of digits for a float -> text -> float round-trip static constexpr auto d = std::numeric_limits<number_float_t>::max_digits10; // the actual conversion // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg) std::ptrdiff_t len = (std::snprintf)(number_buffer.data(), number_buffer.size(), "%.*g", d, x); // negative value indicates an error JSON_ASSERT(len > 0); // check if buffer was large enough JSON_ASSERT(static_cast<std::size_t>(len) < number_buffer.size()); // erase thousands separator if (thousands_sep != '\0') { auto* const end = std::remove(number_buffer.begin(), number_buffer.begin() + len, thousands_sep); std::fill(end, number_buffer.end(), '\0'); JSON_ASSERT((end - number_buffer.begin()) <= len); len = (end - number_buffer.begin()); } // convert decimal point to '.' if (decimal_point != '\0' && decimal_point != '.') { auto* const dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point); if (dec_pos != number_buffer.end()) { *dec_pos = '.'; } } o->write_characters(number_buffer.data(), static_cast<std::size_t>(len)); // determine if need to append ".0" const bool value_is_int_like = std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1, [](char c) { return c == '.' || c == 'e'; }); if (value_is_int_like) { o->write_characters(".0", 2); } } /*! @brief check whether a string is UTF-8 encoded The function checks each byte of a string whether it is UTF-8 encoded. The result of the check is stored in the @a state parameter. The function must be called initially with state 0 (accept). State 1 means the string must be rejected, because the current byte is not allowed. If the string is completely processed, but the state is non-zero, the string ended prematurely; that is, the last byte indicated more bytes should have followed. @param[in,out] state the state of the decoding @param[in,out] codep codepoint (valid only if resulting state is UTF8_ACCEPT) @param[in] byte next byte to decode @return new state @note The function has been edited: a std::array is used. @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de> @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ */ static std::uint8_t decode(std::uint8_t& state, std::uint32_t& codep, const std::uint8_t byte) noexcept { static const std::array<std::uint8_t, 400> utf8d = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 00..1F 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20..3F 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 40..5F 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 60..7F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, // 80..9F 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, // A0..BF 8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // C0..DF 0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF 0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, // s1..s2 1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, // s3..s4 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, // s5..s6 1, 3, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // s7..s8 } }; JSON_ASSERT(byte < utf8d.size()); const std::uint8_t type = utf8d[byte]; codep = (state != UTF8_ACCEPT) ? (byte & 0x3fu) | (codep << 6u) : (0xFFu >> type) & (byte); std::size_t index = 256u + static_cast<size_t>(state) * 16u + static_cast<size_t>(type); JSON_ASSERT(index < 400); state = utf8d[index]; return state; } /* * Overload to make the compiler happy while it is instantiating * dump_integer for number_unsigned_t. * Must never be called. */ number_unsigned_t remove_sign(number_unsigned_t x) { JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE return x; // LCOV_EXCL_LINE } /* * Helper function for dump_integer * * This function takes a negative signed integer and returns its absolute * value as unsigned integer. The plus/minus shuffling is necessary as we can * not directly remove the sign of an arbitrary signed integer as the * absolute values of INT_MIN and INT_MAX are usually not the same. See * #1708 for details. */ inline number_unsigned_t remove_sign(number_integer_t x) noexcept { JSON_ASSERT(x < 0 && x < (std::numeric_limits<number_integer_t>::max)()); // NOLINT(misc-redundant-expression) return static_cast<number_unsigned_t>(-(x + 1)) + 1; } private: /// the output of the serializer output_adapter_t<char> o = nullptr; /// a (hopefully) large enough character buffer std::array<char, 64> number_buffer{{}}; /// the locale const std::lconv* loc = nullptr; /// the locale's thousand separator character const char thousands_sep = '\0'; /// the locale's decimal point character const char decimal_point = '\0'; /// string buffer std::array<char, 512> string_buffer{{}}; /// the indentation character const char indent_char; /// the indentation string string_t indent_string; /// error_handler how to react on decoding errors const error_handler_t error_handler; }; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/value_t.hpp> // #include <nlohmann/json_fwd.hpp> // #include <nlohmann/ordered_map.hpp> #include <functional> // less #include <initializer_list> // initializer_list #include <iterator> // input_iterator_tag, iterator_traits #include <memory> // allocator #include <stdexcept> // for out_of_range #include <type_traits> // enable_if, is_convertible #include <utility> // pair #include <vector> // vector // #include <nlohmann/detail/macro_scope.hpp> namespace nlohmann { /// ordered_map: a minimal map-like container that preserves insertion order /// for use within nlohmann::basic_json<ordered_map> template <class Key, class T, class IgnoredLess = std::less<Key>, class Allocator = std::allocator<std::pair<const Key, T>>> struct ordered_map : std::vector<std::pair<const Key, T>, Allocator> { using key_type = Key; using mapped_type = T; using Container = std::vector<std::pair<const Key, T>, Allocator>; using typename Container::iterator; using typename Container::const_iterator; using typename Container::size_type; using typename Container::value_type; // Explicit constructors instead of `using Container::Container` // otherwise older compilers choke on it (GCC <= 5.5, xcode <= 9.4) ordered_map(const Allocator& alloc = Allocator()) : Container{alloc} {} template <class It> ordered_map(It first, It last, const Allocator& alloc = Allocator()) : Container{first, last, alloc} {} ordered_map(std::initializer_list<T> init, const Allocator& alloc = Allocator() ) : Container{init, alloc} {} std::pair<iterator, bool> emplace(const key_type& key, T&& t) { for (auto it = this->begin(); it != this->end(); ++it) { if (it->first == key) { return {it, false}; } } Container::emplace_back(key, t); return {--this->end(), true}; } T& operator[](const Key& key) { return emplace(key, T{}).first->second; } const T& operator[](const Key& key) const { return at(key); } T& at(const Key& key) { for (auto it = this->begin(); it != this->end(); ++it) { if (it->first == key) { return it->second; } } JSON_THROW(std::out_of_range("key not found")); } const T& at(const Key& key) const { for (auto it = this->begin(); it != this->end(); ++it) { if (it->first == key) { return it->second; } } JSON_THROW(std::out_of_range("key not found")); } size_type erase(const Key& key) { for (auto it = this->begin(); it != this->end(); ++it) { if (it->first == key) { // Since we cannot move const Keys, re-construct them in place for (auto next = it; ++next != this->end(); ++it) { it->~value_type(); // Destroy but keep allocation new (&*it) value_type{std::move(*next)}; } Container::pop_back(); return 1; } } return 0; } iterator erase(iterator pos) { auto it = pos; // Since we cannot move const Keys, re-construct them in place for (auto next = it; ++next != this->end(); ++it) { it->~value_type(); // Destroy but keep allocation new (&*it) value_type{std::move(*next)}; } Container::pop_back(); return pos; } size_type count(const Key& key) const { for (auto it = this->begin(); it != this->end(); ++it) { if (it->first == key) { return 1; } } return 0; } iterator find(const Key& key) { for (auto it = this->begin(); it != this->end(); ++it) { if (it->first == key) { return it; } } return Container::end(); } const_iterator find(const Key& key) const { for (auto it = this->begin(); it != this->end(); ++it) { if (it->first == key) { return it; } } return Container::end(); } std::pair<iterator, bool> insert( value_type&& value ) { return emplace(value.first, std::move(value.second)); } std::pair<iterator, bool> insert( const value_type& value ) { for (auto it = this->begin(); it != this->end(); ++it) { if (it->first == value.first) { return {it, false}; } } Container::push_back(value); return {--this->end(), true}; } template<typename InputIt> using require_input_iter = typename std::enable_if<std::is_convertible<typename std::iterator_traits<InputIt>::iterator_category, std::input_iterator_tag>::value>::type; template<typename InputIt, typename = require_input_iter<InputIt>> void insert(InputIt first, InputIt last) { for (auto it = first; it != last; ++it) { insert(*it); } } }; } // namespace nlohmann #if defined(JSON_HAS_CPP_17) #include <string_view> #endif /*! @brief namespace for Niels Lohmann @see https://github.com/nlohmann @since version 1.0.0 */ namespace nlohmann { /*! @brief a class to store JSON values @tparam ObjectType type for JSON objects (`std::map` by default; will be used in @ref object_t) @tparam ArrayType type for JSON arrays (`std::vector` by default; will be used in @ref array_t) @tparam StringType type for JSON strings and object keys (`std::string` by default; will be used in @ref string_t) @tparam BooleanType type for JSON booleans (`bool` by default; will be used in @ref boolean_t) @tparam NumberIntegerType type for JSON integer numbers (`int64_t` by default; will be used in @ref number_integer_t) @tparam NumberUnsignedType type for JSON unsigned integer numbers (@c `uint64_t` by default; will be used in @ref number_unsigned_t) @tparam NumberFloatType type for JSON floating-point numbers (`double` by default; will be used in @ref number_float_t) @tparam BinaryType type for packed binary data for compatibility with binary serialization formats (`std::vector<std::uint8_t>` by default; will be used in @ref binary_t) @tparam AllocatorType type of the allocator to use (`std::allocator` by default) @tparam JSONSerializer the serializer to resolve internal calls to `to_json()` and `from_json()` (@ref adl_serializer by default) @requirement The class satisfies the following concept requirements: - Basic - [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible): JSON values can be default constructed. The result will be a JSON null value. - [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible): A JSON value can be constructed from an rvalue argument. - [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible): A JSON value can be copy-constructed from an lvalue expression. - [MoveAssignable](https://en.cppreference.com/w/cpp/named_req/MoveAssignable): A JSON value van be assigned from an rvalue argument. - [CopyAssignable](https://en.cppreference.com/w/cpp/named_req/CopyAssignable): A JSON value can be copy-assigned from an lvalue expression. - [Destructible](https://en.cppreference.com/w/cpp/named_req/Destructible): JSON values can be destructed. - Layout - [StandardLayoutType](https://en.cppreference.com/w/cpp/named_req/StandardLayoutType): JSON values have [standard layout](https://en.cppreference.com/w/cpp/language/data_members#Standard_layout): All non-static data members are private and standard layout types, the class has no virtual functions or (virtual) base classes. - Library-wide - [EqualityComparable](https://en.cppreference.com/w/cpp/named_req/EqualityComparable): JSON values can be compared with `==`, see @ref operator==(const_reference,const_reference). - [LessThanComparable](https://en.cppreference.com/w/cpp/named_req/LessThanComparable): JSON values can be compared with `<`, see @ref operator<(const_reference,const_reference). - [Swappable](https://en.cppreference.com/w/cpp/named_req/Swappable): Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of other compatible types, using unqualified function call @ref swap(). - [NullablePointer](https://en.cppreference.com/w/cpp/named_req/NullablePointer): JSON values can be compared against `std::nullptr_t` objects which are used to model the `null` value. - Container - [Container](https://en.cppreference.com/w/cpp/named_req/Container): JSON values can be used like STL containers and provide iterator access. - [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer); JSON values can be used like STL containers and provide reverse iterator access. @invariant The member variables @a m_value and @a m_type have the following relationship: - If `m_type == value_t::object`, then `m_value.object != nullptr`. - If `m_type == value_t::array`, then `m_value.array != nullptr`. - If `m_type == value_t::string`, then `m_value.string != nullptr`. The invariants are checked by member function assert_invariant(). @internal @note ObjectType trick from https://stackoverflow.com/a/9860911 @endinternal @see [RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format](https://tools.ietf.org/html/rfc8259) @since version 1.0.0 @nosubgrouping */ NLOHMANN_BASIC_JSON_TPL_DECLARATION class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-special-member-functions) { private: template<detail::value_t> friend struct detail::external_constructor; friend ::nlohmann::json_pointer<basic_json>; template<typename BasicJsonType, typename InputType> friend class ::nlohmann::detail::parser; friend ::nlohmann::detail::serializer<basic_json>; template<typename BasicJsonType> friend class ::nlohmann::detail::iter_impl; template<typename BasicJsonType, typename CharType> friend class ::nlohmann::detail::binary_writer; template<typename BasicJsonType, typename InputType, typename SAX> friend class ::nlohmann::detail::binary_reader; template<typename BasicJsonType> friend class ::nlohmann::detail::json_sax_dom_parser; template<typename BasicJsonType> friend class ::nlohmann::detail::json_sax_dom_callback_parser; friend class ::nlohmann::detail::exception; /// workaround type for MSVC using basic_json_t = NLOHMANN_BASIC_JSON_TPL; JSON_PRIVATE_UNLESS_TESTED: // convenience aliases for types residing in namespace detail; using lexer = ::nlohmann::detail::lexer_base<basic_json>; template<typename InputAdapterType> static ::nlohmann::detail::parser<basic_json, InputAdapterType> parser( InputAdapterType adapter, detail::parser_callback_t<basic_json>cb = nullptr, const bool allow_exceptions = true, const bool ignore_comments = false ) { return ::nlohmann::detail::parser<basic_json, InputAdapterType>(std::move(adapter), std::move(cb), allow_exceptions, ignore_comments); } private: using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t; template<typename BasicJsonType> using internal_iterator = ::nlohmann::detail::internal_iterator<BasicJsonType>; template<typename BasicJsonType> using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>; template<typename Iterator> using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>; template<typename Base> using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>; template<typename CharType> using output_adapter_t = ::nlohmann::detail::output_adapter_t<CharType>; template<typename InputType> using binary_reader = ::nlohmann::detail::binary_reader<basic_json, InputType>; template<typename CharType> using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>; JSON_PRIVATE_UNLESS_TESTED: using serializer = ::nlohmann::detail::serializer<basic_json>; public: using value_t = detail::value_t; /// JSON Pointer, see @ref nlohmann::json_pointer using json_pointer = ::nlohmann::json_pointer<basic_json>; template<typename T, typename SFINAE> using json_serializer = JSONSerializer<T, SFINAE>; /// how to treat decoding errors using error_handler_t = detail::error_handler_t; /// how to treat CBOR tags using cbor_tag_handler_t = detail::cbor_tag_handler_t; /// helper type for initializer lists of basic_json values using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>; using input_format_t = detail::input_format_t; /// SAX interface type, see @ref nlohmann::json_sax using json_sax_t = json_sax<basic_json>; //////////////// // exceptions // //////////////// /// @name exceptions /// Classes to implement user-defined exceptions. /// @{ /// @copydoc detail::exception using exception = detail::exception; /// @copydoc detail::parse_error using parse_error = detail::parse_error; /// @copydoc detail::invalid_iterator using invalid_iterator = detail::invalid_iterator; /// @copydoc detail::type_error using type_error = detail::type_error; /// @copydoc detail::out_of_range using out_of_range = detail::out_of_range; /// @copydoc detail::other_error using other_error = detail::other_error; /// @} ///////////////////// // container types // ///////////////////// /// @name container types /// The canonic container types to use @ref basic_json like any other STL /// container. /// @{ /// the type of elements in a basic_json container using value_type = basic_json; /// the type of an element reference using reference = value_type&; /// the type of an element const reference using const_reference = const value_type&; /// a type to represent differences between iterators using difference_type = std::ptrdiff_t; /// a type to represent container sizes using size_type = std::size_t; /// the allocator type using allocator_type = AllocatorType<basic_json>; /// the type of an element pointer using pointer = typename std::allocator_traits<allocator_type>::pointer; /// the type of an element const pointer using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer; /// an iterator for a basic_json container using iterator = iter_impl<basic_json>; /// a const iterator for a basic_json container using const_iterator = iter_impl<const basic_json>; /// a reverse iterator for a basic_json container using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>; /// a const reverse iterator for a basic_json container using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>; /// @} /*! @brief returns the allocator associated with the container */ static allocator_type get_allocator() { return allocator_type(); } /*! @brief returns version information on the library This function returns a JSON object with information about the library, including the version number and information on the platform and compiler. @return JSON object holding version information key | description ----------- | --------------- `compiler` | Information on the used compiler. It is an object with the following keys: `c++` (the used C++ standard), `family` (the compiler family; possible values are `clang`, `icc`, `gcc`, `ilecpp`, `msvc`, `pgcpp`, `sunpro`, and `unknown`), and `version` (the compiler version). `copyright` | The copyright line for the library as string. `name` | The name of the library as string. `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`. `url` | The URL of the project as string. `version` | The version of the library. It is an object with the following keys: `major`, `minor`, and `patch` as defined by [Semantic Versioning](http://semver.org), and `string` (the version string). @liveexample{The following code shows an example output of the `meta()` function.,meta} @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @complexity Constant. @since 2.1.0 */ JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json meta() { basic_json result; result["copyright"] = "(C) 2013-2021 Niels Lohmann"; result["name"] = "JSON for Modern C++"; result["url"] = "https://github.com/nlohmann/json"; result["version"]["string"] = std::to_string(NLOHMANN_JSON_VERSION_MAJOR) + "." + std::to_string(NLOHMANN_JSON_VERSION_MINOR) + "." + std::to_string(NLOHMANN_JSON_VERSION_PATCH); result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR; result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR; result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH; #ifdef _WIN32 result["platform"] = "win32"; #elif defined __linux__ result["platform"] = "linux"; #elif defined __APPLE__ result["platform"] = "apple"; #elif defined __unix__ result["platform"] = "unix"; #else result["platform"] = "unknown"; #endif #if defined(__ICC) || defined(__INTEL_COMPILER) result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}}; #elif defined(__clang__) result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}}; #elif defined(__GNUC__) || defined(__GNUG__) result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}}; #elif defined(__HP_cc) || defined(__HP_aCC) result["compiler"] = "hp" #elif defined(__IBMCPP__) result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}}; #elif defined(_MSC_VER) result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}}; #elif defined(__PGI) result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}}; #elif defined(__SUNPRO_CC) result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}}; #else result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}}; #endif #ifdef __cplusplus result["compiler"]["c++"] = std::to_string(__cplusplus); #else result["compiler"]["c++"] = "unknown"; #endif return result; } /////////////////////////// // JSON value data types // /////////////////////////// /// @name JSON value data types /// The data types to store a JSON value. These types are derived from /// the template arguments passed to class @ref basic_json. /// @{ #if defined(JSON_HAS_CPP_14) // Use transparent comparator if possible, combined with perfect forwarding // on find() and count() calls prevents unnecessary string construction. using object_comparator_t = std::less<>; #else using object_comparator_t = std::less<StringType>; #endif /*! @brief a type for an object [RFC 8259](https://tools.ietf.org/html/rfc8259) describes JSON objects as follows: > An object is an unordered collection of zero or more name/value pairs, > where a name is a string and a value is a string, number, boolean, null, > object, or array. To store objects in C++, a type is defined by the template parameters described below. @tparam ObjectType the container to store objects (e.g., `std::map` or `std::unordered_map`) @tparam StringType the type of the keys or names (e.g., `std::string`). The comparison function `std::less<StringType>` is used to order elements inside the container. @tparam AllocatorType the allocator to use for objects (e.g., `std::allocator`) #### Default type With the default values for @a ObjectType (`std::map`), @a StringType (`std::string`), and @a AllocatorType (`std::allocator`), the default value for @a object_t is: @code {.cpp} std::map< std::string, // key_type basic_json, // value_type std::less<std::string>, // key_compare std::allocator<std::pair<const std::string, basic_json>> // allocator_type > @endcode #### Behavior The choice of @a object_t influences the behavior of the JSON class. With the default type, objects have the following behavior: - When all names are unique, objects will be interoperable in the sense that all software implementations receiving that object will agree on the name-value mappings. - When the names within an object are not unique, it is unspecified which one of the values for a given key will be chosen. For instance, `{"key": 2, "key": 1}` could be equal to either `{"key": 1}` or `{"key": 2}`. - Internally, name/value pairs are stored in lexicographical order of the names. Objects will also be serialized (see @ref dump) in this order. For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored and serialized as `{"a": 2, "b": 1}`. - When comparing objects, the order of the name/value pairs is irrelevant. This makes objects interoperable in the sense that they will not be affected by these differences. For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be treated as equal. #### Limits [RFC 8259](https://tools.ietf.org/html/rfc8259) specifies: > An implementation may set limits on the maximum depth of nesting. In this class, the object's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the @ref max_size function of a JSON object. #### Storage Objects are stored as pointers in a @ref basic_json type. That is, for any access to object values, a pointer of type `object_t*` must be dereferenced. @sa see @ref array_t -- type for an array value @since version 1.0.0 @note The order name/value pairs are added to the object is *not* preserved by the library. Therefore, iterating an object may return name/value pairs in a different order than they were originally stored. In fact, keys will be traversed in alphabetical order as `std::map` with `std::less` is used by default. Please note this behavior conforms to [RFC 8259](https://tools.ietf.org/html/rfc8259), because any order implements the specified "unordered" nature of JSON objects. */ using object_t = ObjectType<StringType, basic_json, object_comparator_t, AllocatorType<std::pair<const StringType, basic_json>>>; /*! @brief a type for an array [RFC 8259](https://tools.ietf.org/html/rfc8259) describes JSON arrays as follows: > An array is an ordered sequence of zero or more values. To store objects in C++, a type is defined by the template parameters explained below. @tparam ArrayType container type to store arrays (e.g., `std::vector` or `std::list`) @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`) #### Default type With the default values for @a ArrayType (`std::vector`) and @a AllocatorType (`std::allocator`), the default value for @a array_t is: @code {.cpp} std::vector< basic_json, // value_type std::allocator<basic_json> // allocator_type > @endcode #### Limits [RFC 8259](https://tools.ietf.org/html/rfc8259) specifies: > An implementation may set limits on the maximum depth of nesting. In this class, the array's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the @ref max_size function of a JSON array. #### Storage Arrays are stored as pointers in a @ref basic_json type. That is, for any access to array values, a pointer of type `array_t*` must be dereferenced. @sa see @ref object_t -- type for an object value @since version 1.0.0 */ using array_t = ArrayType<basic_json, AllocatorType<basic_json>>; /*! @brief a type for a string [RFC 8259](https://tools.ietf.org/html/rfc8259) describes JSON strings as follows: > A string is a sequence of zero or more Unicode characters. To store objects in C++, a type is defined by the template parameter described below. Unicode values are split by the JSON class into byte-sized characters during deserialization. @tparam StringType the container to store strings (e.g., `std::string`). Note this container is used for keys/names in objects, see @ref object_t. #### Default type With the default values for @a StringType (`std::string`), the default value for @a string_t is: @code {.cpp} std::string @endcode #### Encoding Strings are stored in UTF-8 encoding. Therefore, functions like `std::string::size()` or `std::string::length()` return the number of bytes in the string rather than the number of characters or glyphs. #### String comparison [RFC 8259](https://tools.ietf.org/html/rfc8259) states: > Software implementations are typically required to test names of object > members for equality. Implementations that transform the textual > representation into sequences of Unicode code units and then perform the > comparison numerically, code unit by code unit, are interoperable in the > sense that implementations will agree in all cases on equality or > inequality of two strings. For example, implementations that compare > strings with escaped characters unconverted may incorrectly find that > `"a\\b"` and `"a\u005Cb"` are not equal. This implementation is interoperable as it does compare strings code unit by code unit. #### Storage String values are stored as pointers in a @ref basic_json type. That is, for any access to string values, a pointer of type `string_t*` must be dereferenced. @since version 1.0.0 */ using string_t = StringType; /*! @brief a type for a boolean [RFC 8259](https://tools.ietf.org/html/rfc8259) implicitly describes a boolean as a type which differentiates the two literals `true` and `false`. To store objects in C++, a type is defined by the template parameter @a BooleanType which chooses the type to use. #### Default type With the default values for @a BooleanType (`bool`), the default value for @a boolean_t is: @code {.cpp} bool @endcode #### Storage Boolean values are stored directly inside a @ref basic_json type. @since version 1.0.0 */ using boolean_t = BooleanType; /*! @brief a type for a number (integer) [RFC 8259](https://tools.ietf.org/html/rfc8259) describes numbers as follows: > The representation of numbers is similar to that used in most > programming languages. A number is represented in base 10 using decimal > digits. It contains an integer component that may be prefixed with an > optional minus sign, which may be followed by a fraction part and/or an > exponent part. Leading zeros are not allowed. (...) Numeric values that > cannot be represented in the grammar below (such as Infinity and NaN) > are not permitted. This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, @ref number_integer_t, @ref number_unsigned_t and @ref number_float_t are used. To store integer numbers in C++, a type is defined by the template parameter @a NumberIntegerType which chooses the type to use. #### Default type With the default values for @a NumberIntegerType (`int64_t`), the default value for @a number_integer_t is: @code {.cpp} int64_t @endcode #### Default behavior - The restrictions about leading zeros is not enforced in C++. Instead, leading zeros in integer literals lead to an interpretation as octal number. Internally, the value will be stored as decimal number. For instance, the C++ integer literal `010` will be serialized to `8`. During deserialization, leading zeros yield an error. - Not-a-number (NaN) values will be serialized to `null`. #### Limits [RFC 8259](https://tools.ietf.org/html/rfc8259) specifies: > An implementation may set limits on the range and precision of numbers. When the default type is used, the maximal integer number that can be stored is `9223372036854775807` (INT64_MAX) and the minimal integer number that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as @ref number_unsigned_t or @ref number_float_t. [RFC 8259](https://tools.ietf.org/html/rfc8259) further states: > Note that when such software is used, numbers that are integers and are > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense > that implementations will agree exactly on their numeric values. As this range is a subrange of the exactly supported range [INT64_MIN, INT64_MAX], this class's integer type is interoperable. #### Storage Integer number values are stored directly inside a @ref basic_json type. @sa see @ref number_float_t -- type for number values (floating-point) @sa see @ref number_unsigned_t -- type for number values (unsigned integer) @since version 1.0.0 */ using number_integer_t = NumberIntegerType; /*! @brief a type for a number (unsigned) [RFC 8259](https://tools.ietf.org/html/rfc8259) describes numbers as follows: > The representation of numbers is similar to that used in most > programming languages. A number is represented in base 10 using decimal > digits. It contains an integer component that may be prefixed with an > optional minus sign, which may be followed by a fraction part and/or an > exponent part. Leading zeros are not allowed. (...) Numeric values that > cannot be represented in the grammar below (such as Infinity and NaN) > are not permitted. This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, @ref number_integer_t, @ref number_unsigned_t and @ref number_float_t are used. To store unsigned integer numbers in C++, a type is defined by the template parameter @a NumberUnsignedType which chooses the type to use. #### Default type With the default values for @a NumberUnsignedType (`uint64_t`), the default value for @a number_unsigned_t is: @code {.cpp} uint64_t @endcode #### Default behavior - The restrictions about leading zeros is not enforced in C++. Instead, leading zeros in integer literals lead to an interpretation as octal number. Internally, the value will be stored as decimal number. For instance, the C++ integer literal `010` will be serialized to `8`. During deserialization, leading zeros yield an error. - Not-a-number (NaN) values will be serialized to `null`. #### Limits [RFC 8259](https://tools.ietf.org/html/rfc8259) specifies: > An implementation may set limits on the range and precision of numbers. When the default type is used, the maximal integer number that can be stored is `18446744073709551615` (UINT64_MAX) and the minimal integer number that can be stored is `0`. Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as @ref number_integer_t or @ref number_float_t. [RFC 8259](https://tools.ietf.org/html/rfc8259) further states: > Note that when such software is used, numbers that are integers and are > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense > that implementations will agree exactly on their numeric values. As this range is a subrange (when considered in conjunction with the number_integer_t type) of the exactly supported range [0, UINT64_MAX], this class's integer type is interoperable. #### Storage Integer number values are stored directly inside a @ref basic_json type. @sa see @ref number_float_t -- type for number values (floating-point) @sa see @ref number_integer_t -- type for number values (integer) @since version 2.0.0 */ using number_unsigned_t = NumberUnsignedType; /*! @brief a type for a number (floating-point) [RFC 8259](https://tools.ietf.org/html/rfc8259) describes numbers as follows: > The representation of numbers is similar to that used in most > programming languages. A number is represented in base 10 using decimal > digits. It contains an integer component that may be prefixed with an > optional minus sign, which may be followed by a fraction part and/or an > exponent part. Leading zeros are not allowed. (...) Numeric values that > cannot be represented in the grammar below (such as Infinity and NaN) > are not permitted. This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, @ref number_integer_t, @ref number_unsigned_t and @ref number_float_t are used. To store floating-point numbers in C++, a type is defined by the template parameter @a NumberFloatType which chooses the type to use. #### Default type With the default values for @a NumberFloatType (`double`), the default value for @a number_float_t is: @code {.cpp} double @endcode #### Default behavior - The restrictions about leading zeros is not enforced in C++. Instead, leading zeros in floating-point literals will be ignored. Internally, the value will be stored as decimal number. For instance, the C++ floating-point literal `01.2` will be serialized to `1.2`. During deserialization, leading zeros yield an error. - Not-a-number (NaN) values will be serialized to `null`. #### Limits [RFC 8259](https://tools.ietf.org/html/rfc8259) states: > This specification allows implementations to set limits on the range and > precision of numbers accepted. Since software that implements IEEE > 754-2008 binary64 (double precision) numbers is generally available and > widely used, good interoperability can be achieved by implementations > that expect no more precision or range than these provide, in the sense > that implementations will approximate JSON numbers within the expected > precision. This implementation does exactly follow this approach, as it uses double precision floating-point numbers. Note values smaller than `-1.79769313486232e+308` and values greater than `1.79769313486232e+308` will be stored as NaN internally and be serialized to `null`. #### Storage Floating-point number values are stored directly inside a @ref basic_json type. @sa see @ref number_integer_t -- type for number values (integer) @sa see @ref number_unsigned_t -- type for number values (unsigned integer) @since version 1.0.0 */ using number_float_t = NumberFloatType; /*! @brief a type for a packed binary type This type is a type designed to carry binary data that appears in various serialized formats, such as CBOR's Major Type 2, MessagePack's bin, and BSON's generic binary subtype. This type is NOT a part of standard JSON and exists solely for compatibility with these binary types. As such, it is simply defined as an ordered sequence of zero or more byte values. Additionally, as an implementation detail, the subtype of the binary data is carried around as a `std::uint8_t`, which is compatible with both of the binary data formats that use binary subtyping, (though the specific numbering is incompatible with each other, and it is up to the user to translate between them). [CBOR's RFC 7049](https://tools.ietf.org/html/rfc7049) describes this type as: > Major type 2: a byte string. The string's length in bytes is represented > following the rules for positive integers (major type 0). [MessagePack's documentation on the bin type family](https://github.com/msgpack/msgpack/blob/master/spec.md#bin-format-family) describes this type as: > Bin format family stores an byte array in 2, 3, or 5 bytes of extra bytes > in addition to the size of the byte array. [BSON's specifications](http://bsonspec.org/spec.html) describe several binary types; however, this type is intended to represent the generic binary type which has the description: > Generic binary subtype - This is the most commonly used binary subtype and > should be the 'default' for drivers and tools. None of these impose any limitations on the internal representation other than the basic unit of storage be some type of array whose parts are decomposable into bytes. The default representation of this binary format is a `std::vector<std::uint8_t>`, which is a very common way to represent a byte array in modern C++. #### Default type The default values for @a BinaryType is `std::vector<std::uint8_t>` #### Storage Binary Arrays are stored as pointers in a @ref basic_json type. That is, for any access to array values, a pointer of the type `binary_t*` must be dereferenced. #### Notes on subtypes - CBOR - Binary values are represented as byte strings. No subtypes are supported and will be ignored when CBOR is written. - MessagePack - If a subtype is given and the binary array contains exactly 1, 2, 4, 8, or 16 elements, the fixext family (fixext1, fixext2, fixext4, fixext8) is used. For other sizes, the ext family (ext8, ext16, ext32) is used. The subtype is then added as singed 8-bit integer. - If no subtype is given, the bin family (bin8, bin16, bin32) is used. - BSON - If a subtype is given, it is used and added as unsigned 8-bit integer. - If no subtype is given, the generic binary subtype 0x00 is used. @sa see @ref binary -- create a binary array @since version 3.8.0 */ using binary_t = nlohmann::byte_container_with_subtype<BinaryType>; /// @} private: /// helper for exception-safe object creation template<typename T, typename... Args> JSON_HEDLEY_RETURNS_NON_NULL static T* create(Args&& ... args) { AllocatorType<T> alloc; using AllocatorTraits = std::allocator_traits<AllocatorType<T>>; auto deleter = [&](T * obj) { AllocatorTraits::deallocate(alloc, obj, 1); }; std::unique_ptr<T, decltype(deleter)> obj(AllocatorTraits::allocate(alloc, 1), deleter); AllocatorTraits::construct(alloc, obj.get(), std::forward<Args>(args)...); JSON_ASSERT(obj != nullptr); return obj.release(); } //////////////////////// // JSON value storage // //////////////////////// JSON_PRIVATE_UNLESS_TESTED: /*! @brief a JSON value The actual storage for a JSON value of the @ref basic_json class. This union combines the different storage types for the JSON value types defined in @ref value_t. JSON type | value_t type | used type --------- | --------------- | ------------------------ object | object | pointer to @ref object_t array | array | pointer to @ref array_t string | string | pointer to @ref string_t boolean | boolean | @ref boolean_t number | number_integer | @ref number_integer_t number | number_unsigned | @ref number_unsigned_t number | number_float | @ref number_float_t binary | binary | pointer to @ref binary_t null | null | *no value is stored* @note Variable-length types (objects, arrays, and strings) are stored as pointers. The size of the union should not exceed 64 bits if the default value types are used. @since version 1.0.0 */ union json_value { /// object (stored with pointer to save storage) object_t* object; /// array (stored with pointer to save storage) array_t* array; /// string (stored with pointer to save storage) string_t* string; /// binary (stored with pointer to save storage) binary_t* binary; /// boolean boolean_t boolean; /// number (integer) number_integer_t number_integer; /// number (unsigned integer) number_unsigned_t number_unsigned; /// number (floating-point) number_float_t number_float; /// default constructor (for null values) json_value() = default; /// constructor for booleans json_value(boolean_t v) noexcept : boolean(v) {} /// constructor for numbers (integer) json_value(number_integer_t v) noexcept : number_integer(v) {} /// constructor for numbers (unsigned) json_value(number_unsigned_t v) noexcept : number_unsigned(v) {} /// constructor for numbers (floating-point) json_value(number_float_t v) noexcept : number_float(v) {} /// constructor for empty values of a given type json_value(value_t t) { switch (t) { case value_t::object: { object = create<object_t>(); break; } case value_t::array: { array = create<array_t>(); break; } case value_t::string: { string = create<string_t>(""); break; } case value_t::binary: { binary = create<binary_t>(); break; } case value_t::boolean: { boolean = boolean_t(false); break; } case value_t::number_integer: { number_integer = number_integer_t(0); break; } case value_t::number_unsigned: { number_unsigned = number_unsigned_t(0); break; } case value_t::number_float: { number_float = number_float_t(0.0); break; } case value_t::null: { object = nullptr; // silence warning, see #821 break; } default: { object = nullptr; // silence warning, see #821 if (JSON_HEDLEY_UNLIKELY(t == value_t::null)) { JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.9.1", basic_json())); // LCOV_EXCL_LINE } break; } } } /// constructor for strings json_value(const string_t& value) { string = create<string_t>(value); } /// constructor for rvalue strings json_value(string_t&& value) { string = create<string_t>(std::move(value)); } /// constructor for objects json_value(const object_t& value) { object = create<object_t>(value); } /// constructor for rvalue objects json_value(object_t&& value) { object = create<object_t>(std::move(value)); } /// constructor for arrays json_value(const array_t& value) { array = create<array_t>(value); } /// constructor for rvalue arrays json_value(array_t&& value) { array = create<array_t>(std::move(value)); } /// constructor for binary arrays json_value(const typename binary_t::container_type& value) { binary = create<binary_t>(value); } /// constructor for rvalue binary arrays json_value(typename binary_t::container_type&& value) { binary = create<binary_t>(std::move(value)); } /// constructor for binary arrays (internal type) json_value(const binary_t& value) { binary = create<binary_t>(value); } /// constructor for rvalue binary arrays (internal type) json_value(binary_t&& value) { binary = create<binary_t>(std::move(value)); } void destroy(value_t t) { if (t == value_t::array || t == value_t::object) { // flatten the current json_value to a heap-allocated stack std::vector<basic_json> stack; // move the top-level items to stack if (t == value_t::array) { stack.reserve(array->size()); std::move(array->begin(), array->end(), std::back_inserter(stack)); } else { stack.reserve(object->size()); for (auto&& it : *object) { stack.push_back(std::move(it.second)); } } while (!stack.empty()) { // move the last item to local variable to be processed basic_json current_item(std::move(stack.back())); stack.pop_back(); // if current_item is array/object, move // its children to the stack to be processed later if (current_item.is_array()) { std::move(current_item.m_value.array->begin(), current_item.m_value.array->end(), std::back_inserter(stack)); current_item.m_value.array->clear(); } else if (current_item.is_object()) { for (auto&& it : *current_item.m_value.object) { stack.push_back(std::move(it.second)); } current_item.m_value.object->clear(); } // it's now safe that current_item get destructed // since it doesn't have any children } } switch (t) { case value_t::object: { AllocatorType<object_t> alloc; std::allocator_traits<decltype(alloc)>::destroy(alloc, object); std::allocator_traits<decltype(alloc)>::deallocate(alloc, object, 1); break; } case value_t::array: { AllocatorType<array_t> alloc; std::allocator_traits<decltype(alloc)>::destroy(alloc, array); std::allocator_traits<decltype(alloc)>::deallocate(alloc, array, 1); break; } case value_t::string: { AllocatorType<string_t> alloc; std::allocator_traits<decltype(alloc)>::destroy(alloc, string); std::allocator_traits<decltype(alloc)>::deallocate(alloc, string, 1); break; } case value_t::binary: { AllocatorType<binary_t> alloc; std::allocator_traits<decltype(alloc)>::destroy(alloc, binary); std::allocator_traits<decltype(alloc)>::deallocate(alloc, binary, 1); break; } default: { break; } } } }; private: /*! @brief checks the class invariants This function asserts the class invariants. It needs to be called at the end of every constructor to make sure that created objects respect the invariant. Furthermore, it has to be called each time the type of a JSON value is changed, because the invariant expresses a relationship between @a m_type and @a m_value. Furthermore, the parent relation is checked for arrays and objects: If @a check_parents true and the value is an array or object, then the container's elements must have the current value as parent. @param[in] check_parents whether the parent relation should be checked. The value is true by default and should only be set to false during destruction of objects when the invariant does not need to hold. */ void assert_invariant(bool check_parents = true) const noexcept { JSON_ASSERT(m_type != value_t::object || m_value.object != nullptr); JSON_ASSERT(m_type != value_t::array || m_value.array != nullptr); JSON_ASSERT(m_type != value_t::string || m_value.string != nullptr); JSON_ASSERT(m_type != value_t::binary || m_value.binary != nullptr); #if JSON_DIAGNOSTICS JSON_TRY { // cppcheck-suppress assertWithSideEffect JSON_ASSERT(!check_parents || !is_structured() || std::all_of(begin(), end(), [this](const basic_json & j) { return j.m_parent == this; })); } JSON_CATCH(...) {} // LCOV_EXCL_LINE #endif static_cast<void>(check_parents); } void set_parents() { #if JSON_DIAGNOSTICS switch (m_type) { case value_t::array: { for (auto& element : *m_value.array) { element.m_parent = this; } break; } case value_t::object: { for (auto& element : *m_value.object) { element.second.m_parent = this; } break; } default: break; } #endif } iterator set_parents(iterator it, typename iterator::difference_type count) { #if JSON_DIAGNOSTICS for (typename iterator::difference_type i = 0; i < count; ++i) { (it + i)->m_parent = this; } #else static_cast<void>(count); #endif return it; } reference set_parent(reference j, std::size_t old_capacity = std::size_t(-1)) { #if JSON_DIAGNOSTICS if (old_capacity != std::size_t(-1)) { // see https://github.com/nlohmann/json/issues/2838 JSON_ASSERT(type() == value_t::array); if (JSON_HEDLEY_UNLIKELY(m_value.array->capacity() != old_capacity)) { // capacity has changed: update all parents set_parents(); return j; } } j.m_parent = this; #else static_cast<void>(j); static_cast<void>(old_capacity); #endif return j; } public: ////////////////////////// // JSON parser callback // ////////////////////////// /*! @brief parser event types The parser callback distinguishes the following events: - `object_start`: the parser read `{` and started to process a JSON object - `key`: the parser read a key of a value in an object - `object_end`: the parser read `}` and finished processing a JSON object - `array_start`: the parser read `[` and started to process a JSON array - `array_end`: the parser read `]` and finished processing a JSON array - `value`: the parser finished reading a JSON value @image html callback_events.png "Example when certain parse events are triggered" @sa see @ref parser_callback_t for more information and examples */ using parse_event_t = detail::parse_event_t; /*! @brief per-element parser callback type With a parser callback function, the result of parsing a JSON text can be influenced. When passed to @ref parse, it is called on certain events (passed as @ref parse_event_t via parameter @a event) with a set recursion depth @a depth and context JSON value @a parsed. The return value of the callback function is a boolean indicating whether the element that emitted the callback shall be kept or not. We distinguish six scenarios (determined by the event type) in which the callback function can be called. The following table describes the values of the parameters @a depth, @a event, and @a parsed. parameter @a event | description | parameter @a depth | parameter @a parsed ------------------ | ----------- | ------------------ | ------------------- parse_event_t::object_start | the parser read `{` and started to process a JSON object | depth of the parent of the JSON object | a JSON value with type discarded parse_event_t::key | the parser read a key of a value in an object | depth of the currently parsed JSON object | a JSON string containing the key parse_event_t::object_end | the parser read `}` and finished processing a JSON object | depth of the parent of the JSON object | the parsed JSON object parse_event_t::array_start | the parser read `[` and started to process a JSON array | depth of the parent of the JSON array | a JSON value with type discarded parse_event_t::array_end | the parser read `]` and finished processing a JSON array | depth of the parent of the JSON array | the parsed JSON array parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value @image html callback_events.png "Example when certain parse events are triggered" Discarding a value (i.e., returning `false`) has different effects depending on the context in which function was called: - Discarded values in structured types are skipped. That is, the parser will behave as if the discarded value was never read. - In case a value outside a structured type is skipped, it is replaced with `null`. This case happens if the top-level element is skipped. @param[in] depth the depth of the recursion during parsing @param[in] event an event of type parse_event_t indicating the context in the callback function has been called @param[in,out] parsed the current intermediate parse result; note that writing to this value has no effect for parse_event_t::key events @return Whether the JSON value which called the function during parsing should be kept (`true`) or not (`false`). In the latter case, it is either skipped completely or replaced by an empty discarded object. @sa see @ref parse for examples @since version 1.0.0 */ using parser_callback_t = detail::parser_callback_t<basic_json>; ////////////////// // constructors // ////////////////// /// @name constructors and destructors /// Constructors of class @ref basic_json, copy/move constructor, copy /// assignment, static functions creating objects, and the destructor. /// @{ /*! @brief create an empty value with a given type Create an empty JSON value with a given type. The value will be default initialized with an empty value which depends on the type: Value type | initial value ----------- | ------------- null | `null` boolean | `false` string | `""` number | `0` object | `{}` array | `[]` binary | empty array @param[in] v the type of the value to create @complexity Constant. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @liveexample{The following code shows the constructor for different @ref value_t values,basic_json__value_t} @sa see @ref clear() -- restores the postcondition of this constructor @since version 1.0.0 */ basic_json(const value_t v) : m_type(v), m_value(v) { assert_invariant(); } /*! @brief create a null object Create a `null` JSON value. It either takes a null pointer as parameter (explicitly creating `null`) or no parameter (implicitly creating `null`). The passed null pointer itself is not read -- it is only used to choose the right constructor. @complexity Constant. @exceptionsafety No-throw guarantee: this constructor never throws exceptions. @liveexample{The following code shows the constructor with and without a null pointer parameter.,basic_json__nullptr_t} @since version 1.0.0 */ basic_json(std::nullptr_t = nullptr) noexcept : basic_json(value_t::null) { assert_invariant(); } /*! @brief create a JSON value This is a "catch all" constructor for all compatible JSON types; that is, types for which a `to_json()` method exists. The constructor forwards the parameter @a val to that method (to `json_serializer<U>::to_json` method with `U = uncvref_t<CompatibleType>`, to be exact). Template type @a CompatibleType includes, but is not limited to, the following types: - **arrays**: @ref array_t and all kinds of compatible containers such as `std::vector`, `std::deque`, `std::list`, `std::forward_list`, `std::array`, `std::valarray`, `std::set`, `std::unordered_set`, `std::multiset`, and `std::unordered_multiset` with a `value_type` from which a @ref basic_json value can be constructed. - **objects**: @ref object_t and all kinds of compatible associative containers such as `std::map`, `std::unordered_map`, `std::multimap`, and `std::unordered_multimap` with a `key_type` compatible to @ref string_t and a `value_type` from which a @ref basic_json value can be constructed. - **strings**: @ref string_t, string literals, and all compatible string containers can be used. - **numbers**: @ref number_integer_t, @ref number_unsigned_t, @ref number_float_t, and all convertible number types such as `int`, `size_t`, `int64_t`, `float` or `double` can be used. - **boolean**: @ref boolean_t / `bool` can be used. - **binary**: @ref binary_t / `std::vector<uint8_t>` may be used, unfortunately because string literals cannot be distinguished from binary character arrays by the C++ type system, all types compatible with `const char*` will be directed to the string constructor instead. This is both for backwards compatibility, and due to the fact that a binary type is not a standard JSON type. See the examples below. @tparam CompatibleType a type such that: - @a CompatibleType is not derived from `std::istream`, - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move constructors), - @a CompatibleType is not a different @ref basic_json type (i.e. with different template arguments) - @a CompatibleType is not a @ref basic_json nested type (e.g., @ref json_pointer, @ref iterator, etc ...) - `json_serializer<U>` has a `to_json(basic_json_t&, CompatibleType&&)` method @tparam U = `uncvref_t<CompatibleType>` @param[in] val the value to be forwarded to the respective constructor @complexity Usually linear in the size of the passed @a val, also depending on the implementation of the called `to_json()` method. @exceptionsafety Depends on the called constructor. For types directly supported by the library (i.e., all types for which no `to_json()` function was provided), strong guarantee holds: if an exception is thrown, there are no changes to any JSON value. @liveexample{The following code shows the constructor with several compatible types.,basic_json__CompatibleType} @since version 2.1.0 */ template < typename CompatibleType, typename U = detail::uncvref_t<CompatibleType>, detail::enable_if_t < !detail::is_basic_json<U>::value && detail::is_compatible_type<basic_json_t, U>::value, int > = 0 > basic_json(CompatibleType && val) noexcept(noexcept( // NOLINT(bugprone-forwarding-reference-overload,bugprone-exception-escape) JSONSerializer<U>::to_json(std::declval<basic_json_t&>(), std::forward<CompatibleType>(val)))) { JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val)); set_parents(); assert_invariant(); } /*! @brief create a JSON value from an existing one This is a constructor for existing @ref basic_json types. It does not hijack copy/move constructors, since the parameter has different template arguments than the current ones. The constructor tries to convert the internal @ref m_value of the parameter. @tparam BasicJsonType a type such that: - @a BasicJsonType is a @ref basic_json type. - @a BasicJsonType has different template arguments than @ref basic_json_t. @param[in] val the @ref basic_json value to be converted. @complexity Usually linear in the size of the passed @a val, also depending on the implementation of the called `to_json()` method. @exceptionsafety Depends on the called constructor. For types directly supported by the library (i.e., all types for which no `to_json()` function was provided), strong guarantee holds: if an exception is thrown, there are no changes to any JSON value. @since version 3.2.0 */ template < typename BasicJsonType, detail::enable_if_t < detail::is_basic_json<BasicJsonType>::value&& !std::is_same<basic_json, BasicJsonType>::value, int > = 0 > basic_json(const BasicJsonType& val) { using other_boolean_t = typename BasicJsonType::boolean_t; using other_number_float_t = typename BasicJsonType::number_float_t; using other_number_integer_t = typename BasicJsonType::number_integer_t; using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t; using other_string_t = typename BasicJsonType::string_t; using other_object_t = typename BasicJsonType::object_t; using other_array_t = typename BasicJsonType::array_t; using other_binary_t = typename BasicJsonType::binary_t; switch (val.type()) { case value_t::boolean: JSONSerializer<other_boolean_t>::to_json(*this, val.template get<other_boolean_t>()); break; case value_t::number_float: JSONSerializer<other_number_float_t>::to_json(*this, val.template get<other_number_float_t>()); break; case value_t::number_integer: JSONSerializer<other_number_integer_t>::to_json(*this, val.template get<other_number_integer_t>()); break; case value_t::number_unsigned: JSONSerializer<other_number_unsigned_t>::to_json(*this, val.template get<other_number_unsigned_t>()); break; case value_t::string: JSONSerializer<other_string_t>::to_json(*this, val.template get_ref<const other_string_t&>()); break; case value_t::object: JSONSerializer<other_object_t>::to_json(*this, val.template get_ref<const other_object_t&>()); break; case value_t::array: JSONSerializer<other_array_t>::to_json(*this, val.template get_ref<const other_array_t&>()); break; case value_t::binary: JSONSerializer<other_binary_t>::to_json(*this, val.template get_ref<const other_binary_t&>()); break; case value_t::null: *this = nullptr; break; case value_t::discarded: m_type = value_t::discarded; break; default: // LCOV_EXCL_LINE JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE } set_parents(); assert_invariant(); } /*! @brief create a container (array or object) from an initializer list Creates a JSON value of type array or object from the passed initializer list @a init. In case @a type_deduction is `true` (default), the type of the JSON value to be created is deducted from the initializer list @a init according to the following rules: 1. If the list is empty, an empty JSON object value `{}` is created. 2. If the list consists of pairs whose first element is a string, a JSON object value is created where the first elements of the pairs are treated as keys and the second elements are as values. 3. In all other cases, an array is created. The rules aim to create the best fit between a C++ initializer list and JSON values. The rationale is as follows: 1. The empty initializer list is written as `{}` which is exactly an empty JSON object. 2. C++ has no way of describing mapped types other than to list a list of pairs. As JSON requires that keys must be of type string, rule 2 is the weakest constraint one can pose on initializer lists to interpret them as an object. 3. In all other cases, the initializer list could not be interpreted as JSON object type, so interpreting it as JSON array type is safe. With the rules described above, the following JSON values cannot be expressed by an initializer list: - the empty array (`[]`): use @ref array(initializer_list_t) with an empty initializer list in this case - arrays whose elements satisfy rule 2: use @ref array(initializer_list_t) with the same initializer list in this case @note When used without parentheses around an empty initializer list, @ref basic_json() is called instead of this function, yielding the JSON null value. @param[in] init initializer list with JSON values @param[in] type_deduction internal parameter; when set to `true`, the type of the JSON value is deducted from the initializer list @a init; when set to `false`, the type provided via @a manual_type is forced. This mode is used by the functions @ref array(initializer_list_t) and @ref object(initializer_list_t). @param[in] manual_type internal parameter; when @a type_deduction is set to `false`, the created JSON value will use the provided type (only @ref value_t::array and @ref value_t::object are valid); when @a type_deduction is set to `true`, this parameter has no effect @throw type_error.301 if @a type_deduction is `false`, @a manual_type is `value_t::object`, but @a init contains an element which is not a pair whose first element is a string. In this case, the constructor could not create an object. If @a type_deduction would have be `true`, an array would have been created. See @ref object(initializer_list_t) for an example. @complexity Linear in the size of the initializer list @a init. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @liveexample{The example below shows how JSON values are created from initializer lists.,basic_json__list_init_t} @sa see @ref array(initializer_list_t) -- create a JSON array value from an initializer list @sa see @ref object(initializer_list_t) -- create a JSON object value from an initializer list @since version 1.0.0 */ basic_json(initializer_list_t init, bool type_deduction = true, value_t manual_type = value_t::array) { // check if each element is an array with two elements whose first // element is a string bool is_an_object = std::all_of(init.begin(), init.end(), [](const detail::json_ref<basic_json>& element_ref) { return element_ref->is_array() && element_ref->size() == 2 && (*element_ref)[0].is_string(); }); // adjust type if type deduction is not wanted if (!type_deduction) { // if array is wanted, do not create an object though possible if (manual_type == value_t::array) { is_an_object = false; } // if object is wanted but impossible, throw an exception if (JSON_HEDLEY_UNLIKELY(manual_type == value_t::object && !is_an_object)) { JSON_THROW(type_error::create(301, "cannot create object from initializer list", basic_json())); } } if (is_an_object) { // the initializer list is a list of pairs -> create object m_type = value_t::object; m_value = value_t::object; for (auto& element_ref : init) { auto element = element_ref.moved_or_copied(); m_value.object->emplace( std::move(*((*element.m_value.array)[0].m_value.string)), std::move((*element.m_value.array)[1])); } } else { // the initializer list describes an array -> create array m_type = value_t::array; m_value.array = create<array_t>(init.begin(), init.end()); } set_parents(); assert_invariant(); } /*! @brief explicitly create a binary array (without subtype) Creates a JSON binary array value from a given binary container. Binary values are part of various binary formats, such as CBOR, MessagePack, and BSON. This constructor is used to create a value for serialization to those formats. @note Note, this function exists because of the difficulty in correctly specifying the correct template overload in the standard value ctor, as both JSON arrays and JSON binary arrays are backed with some form of a `std::vector`. Because JSON binary arrays are a non-standard extension it was decided that it would be best to prevent automatic initialization of a binary array type, for backwards compatibility and so it does not happen on accident. @param[in] init container containing bytes to use as binary type @return JSON binary array value @complexity Linear in the size of @a init. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @since version 3.8.0 */ JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json binary(const typename binary_t::container_type& init) { auto res = basic_json(); res.m_type = value_t::binary; res.m_value = init; return res; } /*! @brief explicitly create a binary array (with subtype) Creates a JSON binary array value from a given binary container. Binary values are part of various binary formats, such as CBOR, MessagePack, and BSON. This constructor is used to create a value for serialization to those formats. @note Note, this function exists because of the difficulty in correctly specifying the correct template overload in the standard value ctor, as both JSON arrays and JSON binary arrays are backed with some form of a `std::vector`. Because JSON binary arrays are a non-standard extension it was decided that it would be best to prevent automatic initialization of a binary array type, for backwards compatibility and so it does not happen on accident. @param[in] init container containing bytes to use as binary type @param[in] subtype subtype to use in MessagePack and BSON @return JSON binary array value @complexity Linear in the size of @a init. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @since version 3.8.0 */ JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json binary(const typename binary_t::container_type& init, std::uint8_t subtype) { auto res = basic_json(); res.m_type = value_t::binary; res.m_value = binary_t(init, subtype); return res; } /// @copydoc binary(const typename binary_t::container_type&) JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json binary(typename binary_t::container_type&& init) { auto res = basic_json(); res.m_type = value_t::binary; res.m_value = std::move(init); return res; } /// @copydoc binary(const typename binary_t::container_type&, std::uint8_t) JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json binary(typename binary_t::container_type&& init, std::uint8_t subtype) { auto res = basic_json(); res.m_type = value_t::binary; res.m_value = binary_t(std::move(init), subtype); return res; } /*! @brief explicitly create an array from an initializer list Creates a JSON array value from a given initializer list. That is, given a list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the initializer list is empty, the empty array `[]` is created. @note This function is only needed to express two edge cases that cannot be realized with the initializer list constructor (@ref basic_json(initializer_list_t, bool, value_t)). These cases are: 1. creating an array whose elements are all pairs whose first element is a string -- in this case, the initializer list constructor would create an object, taking the first elements as keys 2. creating an empty array -- passing the empty initializer list to the initializer list constructor yields an empty object @param[in] init initializer list with JSON values to create an array from (optional) @return JSON array value @complexity Linear in the size of @a init. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @liveexample{The following code shows an example for the `array` function.,array} @sa see @ref basic_json(initializer_list_t, bool, value_t) -- create a JSON value from an initializer list @sa see @ref object(initializer_list_t) -- create a JSON object value from an initializer list @since version 1.0.0 */ JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json array(initializer_list_t init = {}) { return basic_json(init, false, value_t::array); } /*! @brief explicitly create an object from an initializer list Creates a JSON object value from a given initializer list. The initializer lists elements must be pairs, and their first elements must be strings. If the initializer list is empty, the empty object `{}` is created. @note This function is only added for symmetry reasons. In contrast to the related function @ref array(initializer_list_t), there are no cases which can only be expressed by this function. That is, any initializer list @a init can also be passed to the initializer list constructor @ref basic_json(initializer_list_t, bool, value_t). @param[in] init initializer list to create an object from (optional) @return JSON object value @throw type_error.301 if @a init is not a list of pairs whose first elements are strings. In this case, no object can be created. When such a value is passed to @ref basic_json(initializer_list_t, bool, value_t), an array would have been created from the passed initializer list @a init. See example below. @complexity Linear in the size of @a init. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @liveexample{The following code shows an example for the `object` function.,object} @sa see @ref basic_json(initializer_list_t, bool, value_t) -- create a JSON value from an initializer list @sa see @ref array(initializer_list_t) -- create a JSON array value from an initializer list @since version 1.0.0 */ JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json object(initializer_list_t init = {}) { return basic_json(init, false, value_t::object); } /*! @brief construct an array with count copies of given value Constructs a JSON array value by creating @a cnt copies of a passed value. In case @a cnt is `0`, an empty array is created. @param[in] cnt the number of JSON copies of @a val to create @param[in] val the JSON value to copy @post `std::distance(begin(),end()) == cnt` holds. @complexity Linear in @a cnt. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @liveexample{The following code shows examples for the @ref basic_json(size_type\, const basic_json&) constructor.,basic_json__size_type_basic_json} @since version 1.0.0 */ basic_json(size_type cnt, const basic_json& val) : m_type(value_t::array) { m_value.array = create<array_t>(cnt, val); set_parents(); assert_invariant(); } /*! @brief construct a JSON container given an iterator range Constructs the JSON value with the contents of the range `[first, last)`. The semantics depends on the different types a JSON value can have: - In case of a null type, invalid_iterator.206 is thrown. - In case of other primitive types (number, boolean, or string), @a first must be `begin()` and @a last must be `end()`. In this case, the value is copied. Otherwise, invalid_iterator.204 is thrown. - In case of structured types (array, object), the constructor behaves as similar versions for `std::vector` or `std::map`; that is, a JSON array or object is constructed from the values in the range. @tparam InputIT an input iterator type (@ref iterator or @ref const_iterator) @param[in] first begin of the range to copy from (included) @param[in] last end of the range to copy from (excluded) @pre Iterators @a first and @a last must be initialized. **This precondition is enforced with an assertion (see warning).** If assertions are switched off, a violation of this precondition yields undefined behavior. @pre Range `[first, last)` is valid. Usually, this precondition cannot be checked efficiently. Only certain edge cases are detected; see the description of the exceptions below. A violation of this precondition yields undefined behavior. @warning A precondition is enforced with a runtime assertion that will result in calling `std::abort` if this precondition is not met. Assertions can be disabled by defining `NDEBUG` at compile time. See https://en.cppreference.com/w/cpp/error/assert for more information. @throw invalid_iterator.201 if iterators @a first and @a last are not compatible (i.e., do not belong to the same JSON value). In this case, the range `[first, last)` is undefined. @throw invalid_iterator.204 if iterators @a first and @a last belong to a primitive type (number, boolean, or string), but @a first does not point to the first element any more. In this case, the range `[first, last)` is undefined. See example code below. @throw invalid_iterator.206 if iterators @a first and @a last belong to a null value. In this case, the range `[first, last)` is undefined. @complexity Linear in distance between @a first and @a last. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @liveexample{The example below shows several ways to create JSON values by specifying a subrange with iterators.,basic_json__InputIt_InputIt} @since version 1.0.0 */ template < class InputIT, typename std::enable_if < std::is_same<InputIT, typename basic_json_t::iterator>::value || std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int >::type = 0 > basic_json(InputIT first, InputIT last) { JSON_ASSERT(first.m_object != nullptr); JSON_ASSERT(last.m_object != nullptr); // make sure iterator fits the current value if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) { JSON_THROW(invalid_iterator::create(201, "iterators are not compatible", basic_json())); } // copy type from first iterator m_type = first.m_object->m_type; // check if iterator range is complete for primitive values switch (m_type) { case value_t::boolean: case value_t::number_float: case value_t::number_integer: case value_t::number_unsigned: case value_t::string: { if (JSON_HEDLEY_UNLIKELY(!first.m_it.primitive_iterator.is_begin() || !last.m_it.primitive_iterator.is_end())) { JSON_THROW(invalid_iterator::create(204, "iterators out of range", *first.m_object)); } break; } default: break; } switch (m_type) { case value_t::number_integer: { m_value.number_integer = first.m_object->m_value.number_integer; break; } case value_t::number_unsigned: { m_value.number_unsigned = first.m_object->m_value.number_unsigned; break; } case value_t::number_float: { m_value.number_float = first.m_object->m_value.number_float; break; } case value_t::boolean: { m_value.boolean = first.m_object->m_value.boolean; break; } case value_t::string: { m_value = *first.m_object->m_value.string; break; } case value_t::object: { m_value.object = create<object_t>(first.m_it.object_iterator, last.m_it.object_iterator); break; } case value_t::array: { m_value.array = create<array_t>(first.m_it.array_iterator, last.m_it.array_iterator); break; } case value_t::binary: { m_value = *first.m_object->m_value.binary; break; } default: JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " + std::string(first.m_object->type_name()), *first.m_object)); } set_parents(); assert_invariant(); } /////////////////////////////////////// // other constructors and destructor // /////////////////////////////////////// template<typename JsonRef, detail::enable_if_t<detail::conjunction<detail::is_json_ref<JsonRef>, std::is_same<typename JsonRef::value_type, basic_json>>::value, int> = 0 > basic_json(const JsonRef& ref) : basic_json(ref.moved_or_copied()) {} /*! @brief copy constructor Creates a copy of a given JSON value. @param[in] other the JSON value to copy @post `*this == other` @complexity Linear in the size of @a other. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @requirement This function helps `basic_json` satisfying the [Container](https://en.cppreference.com/w/cpp/named_req/Container) requirements: - The complexity is linear. - As postcondition, it holds: `other == basic_json(other)`. @liveexample{The following code shows an example for the copy constructor.,basic_json__basic_json} @since version 1.0.0 */ basic_json(const basic_json& other) : m_type(other.m_type) { // check of passed value is valid other.assert_invariant(); switch (m_type) { case value_t::object: { m_value = *other.m_value.object; break; } case value_t::array: { m_value = *other.m_value.array; break; } case value_t::string: { m_value = *other.m_value.string; break; } case value_t::boolean: { m_value = other.m_value.boolean; break; } case value_t::number_integer: { m_value = other.m_value.number_integer; break; } case value_t::number_unsigned: { m_value = other.m_value.number_unsigned; break; } case value_t::number_float: { m_value = other.m_value.number_float; break; } case value_t::binary: { m_value = *other.m_value.binary; break; } default: break; } set_parents(); assert_invariant(); } /*! @brief move constructor Move constructor. Constructs a JSON value with the contents of the given value @a other using move semantics. It "steals" the resources from @a other and leaves it as JSON null value. @param[in,out] other value to move to this object @post `*this` has the same value as @a other before the call. @post @a other is a JSON null value. @complexity Constant. @exceptionsafety No-throw guarantee: this constructor never throws exceptions. @requirement This function helps `basic_json` satisfying the [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible) requirements. @liveexample{The code below shows the move constructor explicitly called via std::move.,basic_json__moveconstructor} @since version 1.0.0 */ basic_json(basic_json&& other) noexcept : m_type(std::move(other.m_type)), m_value(std::move(other.m_value)) { // check that passed value is valid other.assert_invariant(false); // invalidate payload other.m_type = value_t::null; other.m_value = {}; set_parents(); assert_invariant(); } /*! @brief copy assignment Copy assignment operator. Copies a JSON value via the "copy and swap" strategy: It is expressed in terms of the copy constructor, destructor, and the `swap()` member function. @param[in] other value to copy from @complexity Linear. @requirement This function helps `basic_json` satisfying the [Container](https://en.cppreference.com/w/cpp/named_req/Container) requirements: - The complexity is linear. @liveexample{The code below shows and example for the copy assignment. It creates a copy of value `a` which is then swapped with `b`. Finally\, the copy of `a` (which is the null value after the swap) is destroyed.,basic_json__copyassignment} @since version 1.0.0 */ basic_json& operator=(basic_json other) noexcept ( std::is_nothrow_move_constructible<value_t>::value&& std::is_nothrow_move_assignable<value_t>::value&& std::is_nothrow_move_constructible<json_value>::value&& std::is_nothrow_move_assignable<json_value>::value ) { // check that passed value is valid other.assert_invariant(); using std::swap; swap(m_type, other.m_type); swap(m_value, other.m_value); set_parents(); assert_invariant(); return *this; } /*! @brief destructor Destroys the JSON value and frees all allocated memory. @complexity Linear. @requirement This function helps `basic_json` satisfying the [Container](https://en.cppreference.com/w/cpp/named_req/Container) requirements: - The complexity is linear. - All stored elements are destroyed and all memory is freed. @since version 1.0.0 */ ~basic_json() noexcept { assert_invariant(false); m_value.destroy(m_type); } /// @} public: /////////////////////// // object inspection // /////////////////////// /// @name object inspection /// Functions to inspect the type of a JSON value. /// @{ /*! @brief serialization Serialization function for JSON values. The function tries to mimic Python's `json.dumps()` function, and currently supports its @a indent and @a ensure_ascii parameters. @param[in] indent If indent is nonnegative, then array elements and object members will be pretty-printed with that indent level. An indent level of `0` will only insert newlines. `-1` (the default) selects the most compact representation. @param[in] indent_char The character to use for indentation if @a indent is greater than `0`. The default is ` ` (space). @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters in the output are escaped with `\uXXXX` sequences, and the result consists of ASCII characters only. @param[in] error_handler how to react on decoding errors; there are three possible values: `strict` (throws and exception in case a decoding error occurs; default), `replace` (replace invalid UTF-8 sequences with U+FFFD), and `ignore` (ignore invalid UTF-8 sequences during serialization; all bytes are copied to the output unchanged). @return string containing the serialization of the JSON value @throw type_error.316 if a string stored inside the JSON value is not UTF-8 encoded and @a error_handler is set to strict @note Binary values are serialized as object containing two keys: - "bytes": an array of bytes as integers - "subtype": the subtype as integer or "null" if the binary has no subtype @complexity Linear. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @liveexample{The following example shows the effect of different @a indent\, @a indent_char\, and @a ensure_ascii parameters to the result of the serialization.,dump} @see https://docs.python.org/2/library/json.html#json.dump @since version 1.0.0; indentation character @a indent_char, option @a ensure_ascii and exceptions added in version 3.0.0; error handlers added in version 3.4.0; serialization of binary values added in version 3.8.0. */ string_t dump(const int indent = -1, const char indent_char = ' ', const bool ensure_ascii = false, const error_handler_t error_handler = error_handler_t::strict) const { string_t result; serializer s(detail::output_adapter<char, string_t>(result), indent_char, error_handler); if (indent >= 0) { s.dump(*this, true, ensure_ascii, static_cast<unsigned int>(indent)); } else { s.dump(*this, false, ensure_ascii, 0); } return result; } /*! @brief return the type of the JSON value (explicit) Return the type of the JSON value as a value from the @ref value_t enumeration. @return the type of the JSON value Value type | return value ------------------------- | ------------------------- null | value_t::null boolean | value_t::boolean string | value_t::string number (integer) | value_t::number_integer number (unsigned integer) | value_t::number_unsigned number (floating-point) | value_t::number_float object | value_t::object array | value_t::array binary | value_t::binary discarded | value_t::discarded @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `type()` for all JSON types.,type} @sa see @ref operator value_t() -- return the type of the JSON value (implicit) @sa see @ref type_name() -- return the type as string @since version 1.0.0 */ constexpr value_t type() const noexcept { return m_type; } /*! @brief return whether type is primitive This function returns true if and only if the JSON type is primitive (string, number, boolean, or null). @return `true` if type is primitive (string, number, boolean, or null), `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_primitive()` for all JSON types.,is_primitive} @sa see @ref is_structured() -- returns whether JSON value is structured @sa see @ref is_null() -- returns whether JSON value is `null` @sa see @ref is_string() -- returns whether JSON value is a string @sa see @ref is_boolean() -- returns whether JSON value is a boolean @sa see @ref is_number() -- returns whether JSON value is a number @sa see @ref is_binary() -- returns whether JSON value is a binary array @since version 1.0.0 */ constexpr bool is_primitive() const noexcept { return is_null() || is_string() || is_boolean() || is_number() || is_binary(); } /*! @brief return whether type is structured This function returns true if and only if the JSON type is structured (array or object). @return `true` if type is structured (array or object), `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_structured()` for all JSON types.,is_structured} @sa see @ref is_primitive() -- returns whether value is primitive @sa see @ref is_array() -- returns whether value is an array @sa see @ref is_object() -- returns whether value is an object @since version 1.0.0 */ constexpr bool is_structured() const noexcept { return is_array() || is_object(); } /*! @brief return whether value is null This function returns true if and only if the JSON value is null. @return `true` if type is null, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_null()` for all JSON types.,is_null} @since version 1.0.0 */ constexpr bool is_null() const noexcept { return m_type == value_t::null; } /*! @brief return whether value is a boolean This function returns true if and only if the JSON value is a boolean. @return `true` if type is boolean, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_boolean()` for all JSON types.,is_boolean} @since version 1.0.0 */ constexpr bool is_boolean() const noexcept { return m_type == value_t::boolean; } /*! @brief return whether value is a number This function returns true if and only if the JSON value is a number. This includes both integer (signed and unsigned) and floating-point values. @return `true` if type is number (regardless whether integer, unsigned integer or floating-type), `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_number()` for all JSON types.,is_number} @sa see @ref is_number_integer() -- check if value is an integer or unsigned integer number @sa see @ref is_number_unsigned() -- check if value is an unsigned integer number @sa see @ref is_number_float() -- check if value is a floating-point number @since version 1.0.0 */ constexpr bool is_number() const noexcept { return is_number_integer() || is_number_float(); } /*! @brief return whether value is an integer number This function returns true if and only if the JSON value is a signed or unsigned integer number. This excludes floating-point values. @return `true` if type is an integer or unsigned integer number, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_number_integer()` for all JSON types.,is_number_integer} @sa see @ref is_number() -- check if value is a number @sa see @ref is_number_unsigned() -- check if value is an unsigned integer number @sa see @ref is_number_float() -- check if value is a floating-point number @since version 1.0.0 */ constexpr bool is_number_integer() const noexcept { return m_type == value_t::number_integer || m_type == value_t::number_unsigned; } /*! @brief return whether value is an unsigned integer number This function returns true if and only if the JSON value is an unsigned integer number. This excludes floating-point and signed integer values. @return `true` if type is an unsigned integer number, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_number_unsigned()` for all JSON types.,is_number_unsigned} @sa see @ref is_number() -- check if value is a number @sa see @ref is_number_integer() -- check if value is an integer or unsigned integer number @sa see @ref is_number_float() -- check if value is a floating-point number @since version 2.0.0 */ constexpr bool is_number_unsigned() const noexcept { return m_type == value_t::number_unsigned; } /*! @brief return whether value is a floating-point number This function returns true if and only if the JSON value is a floating-point number. This excludes signed and unsigned integer values. @return `true` if type is a floating-point number, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_number_float()` for all JSON types.,is_number_float} @sa see @ref is_number() -- check if value is number @sa see @ref is_number_integer() -- check if value is an integer number @sa see @ref is_number_unsigned() -- check if value is an unsigned integer number @since version 1.0.0 */ constexpr bool is_number_float() const noexcept { return m_type == value_t::number_float; } /*! @brief return whether value is an object This function returns true if and only if the JSON value is an object. @return `true` if type is object, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_object()` for all JSON types.,is_object} @since version 1.0.0 */ constexpr bool is_object() const noexcept { return m_type == value_t::object; } /*! @brief return whether value is an array This function returns true if and only if the JSON value is an array. @return `true` if type is array, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_array()` for all JSON types.,is_array} @since version 1.0.0 */ constexpr bool is_array() const noexcept { return m_type == value_t::array; } /*! @brief return whether value is a string This function returns true if and only if the JSON value is a string. @return `true` if type is string, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_string()` for all JSON types.,is_string} @since version 1.0.0 */ constexpr bool is_string() const noexcept { return m_type == value_t::string; } /*! @brief return whether value is a binary array This function returns true if and only if the JSON value is a binary array. @return `true` if type is binary array, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_binary()` for all JSON types.,is_binary} @since version 3.8.0 */ constexpr bool is_binary() const noexcept { return m_type == value_t::binary; } /*! @brief return whether value is discarded This function returns true if and only if the JSON value was discarded during parsing with a callback function (see @ref parser_callback_t). @note This function will always be `false` for JSON values after parsing. That is, discarded values can only occur during parsing, but will be removed when inside a structured value or replaced by null in other cases. @return `true` if type is discarded, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_discarded()` for all JSON types.,is_discarded} @since version 1.0.0 */ constexpr bool is_discarded() const noexcept { return m_type == value_t::discarded; } /*! @brief return the type of the JSON value (implicit) Implicitly return the type of the JSON value as a value from the @ref value_t enumeration. @return the type of the JSON value @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies the @ref value_t operator for all JSON types.,operator__value_t} @sa see @ref type() -- return the type of the JSON value (explicit) @sa see @ref type_name() -- return the type as string @since version 1.0.0 */ constexpr operator value_t() const noexcept { return m_type; } /// @} private: ////////////////// // value access // ////////////////// /// get a boolean (explicit) boolean_t get_impl(boolean_t* /*unused*/) const { if (JSON_HEDLEY_LIKELY(is_boolean())) { return m_value.boolean; } JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name()), *this)); } /// get a pointer to the value (object) object_t* get_impl_ptr(object_t* /*unused*/) noexcept { return is_object() ? m_value.object : nullptr; } /// get a pointer to the value (object) constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept { return is_object() ? m_value.object : nullptr; } /// get a pointer to the value (array) array_t* get_impl_ptr(array_t* /*unused*/) noexcept { return is_array() ? m_value.array : nullptr; } /// get a pointer to the value (array) constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept { return is_array() ? m_value.array : nullptr; } /// get a pointer to the value (string) string_t* get_impl_ptr(string_t* /*unused*/) noexcept { return is_string() ? m_value.string : nullptr; } /// get a pointer to the value (string) constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept { return is_string() ? m_value.string : nullptr; } /// get a pointer to the value (boolean) boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept { return is_boolean() ? &m_value.boolean : nullptr; } /// get a pointer to the value (boolean) constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept { return is_boolean() ? &m_value.boolean : nullptr; } /// get a pointer to the value (integer number) number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept { return is_number_integer() ? &m_value.number_integer : nullptr; } /// get a pointer to the value (integer number) constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept { return is_number_integer() ? &m_value.number_integer : nullptr; } /// get a pointer to the value (unsigned number) number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept { return is_number_unsigned() ? &m_value.number_unsigned : nullptr; } /// get a pointer to the value (unsigned number) constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept { return is_number_unsigned() ? &m_value.number_unsigned : nullptr; } /// get a pointer to the value (floating-point number) number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept { return is_number_float() ? &m_value.number_float : nullptr; } /// get a pointer to the value (floating-point number) constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept { return is_number_float() ? &m_value.number_float : nullptr; } /// get a pointer to the value (binary) binary_t* get_impl_ptr(binary_t* /*unused*/) noexcept { return is_binary() ? m_value.binary : nullptr; } /// get a pointer to the value (binary) constexpr const binary_t* get_impl_ptr(const binary_t* /*unused*/) const noexcept { return is_binary() ? m_value.binary : nullptr; } /*! @brief helper function to implement get_ref() This function helps to implement get_ref() without code duplication for const and non-const overloads @tparam ThisType will be deduced as `basic_json` or `const basic_json` @throw type_error.303 if ReferenceType does not match underlying value type of the current JSON */ template<typename ReferenceType, typename ThisType> static ReferenceType get_ref_impl(ThisType& obj) { // delegate the call to get_ptr<>() auto* ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>(); if (JSON_HEDLEY_LIKELY(ptr != nullptr)) { return *ptr; } JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name()), obj)); } public: /// @name value access /// Direct access to the stored value of a JSON value. /// @{ /*! @brief get a pointer value (implicit) Implicit pointer access to the internally stored JSON value. No copies are made. @warning Writing data to the pointee of the result yields an undefined state. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, @ref number_unsigned_t, or @ref number_float_t. Enforced by a static assertion. @return pointer to the internally stored JSON value if the requested pointer type @a PointerType fits to the JSON value; `nullptr` otherwise @complexity Constant. @liveexample{The example below shows how pointers to internal values of a JSON value can be requested. Note that no type conversions are made and a `nullptr` is returned if the value and the requested pointer type does not match.,get_ptr} @since version 1.0.0 */ template<typename PointerType, typename std::enable_if< std::is_pointer<PointerType>::value, int>::type = 0> auto get_ptr() noexcept -> decltype(std::declval<basic_json_t&>().get_impl_ptr(std::declval<PointerType>())) { // delegate the call to get_impl_ptr<>() return get_impl_ptr(static_cast<PointerType>(nullptr)); } /*! @brief get a pointer value (implicit) @copydoc get_ptr() */ template < typename PointerType, typename std::enable_if < std::is_pointer<PointerType>::value&& std::is_const<typename std::remove_pointer<PointerType>::type>::value, int >::type = 0 > constexpr auto get_ptr() const noexcept -> decltype(std::declval<const basic_json_t&>().get_impl_ptr(std::declval<PointerType>())) { // delegate the call to get_impl_ptr<>() const return get_impl_ptr(static_cast<PointerType>(nullptr)); } private: /*! @brief get a value (explicit) Explicit type conversion between the JSON value and a compatible value which is [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible) and [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible). The value is converted by calling the @ref json_serializer<ValueType> `from_json()` method. The function is equivalent to executing @code {.cpp} ValueType ret; JSONSerializer<ValueType>::from_json(*this, ret); return ret; @endcode This overloads is chosen if: - @a ValueType is not @ref basic_json, - @ref json_serializer<ValueType> has a `from_json()` method of the form `void from_json(const basic_json&, ValueType&)`, and - @ref json_serializer<ValueType> does not have a `from_json()` method of the form `ValueType from_json(const basic_json&)` @tparam ValueType the returned value type @return copy of the JSON value, converted to @a ValueType @throw what @ref json_serializer<ValueType> `from_json()` method throws @liveexample{The example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers\, (2) A JSON array can be converted to a standard `std::vector<short>`\, (3) A JSON object can be converted to C++ associative containers such as `std::unordered_map<std::string\, json>`.,get__ValueType_const} @since version 2.1.0 */ template < typename ValueType, detail::enable_if_t < detail::is_default_constructible<ValueType>::value&& detail::has_from_json<basic_json_t, ValueType>::value, int > = 0 > ValueType get_impl(detail::priority_tag<0> /*unused*/) const noexcept(noexcept( JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>()))) { ValueType ret{}; JSONSerializer<ValueType>::from_json(*this, ret); return ret; } /*! @brief get a value (explicit); special case Explicit type conversion between the JSON value and a compatible value which is **not** [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible) and **not** [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible). The value is converted by calling the @ref json_serializer<ValueType> `from_json()` method. The function is equivalent to executing @code {.cpp} return JSONSerializer<ValueType>::from_json(*this); @endcode This overloads is chosen if: - @a ValueType is not @ref basic_json and - @ref json_serializer<ValueType> has a `from_json()` method of the form `ValueType from_json(const basic_json&)` @note If @ref json_serializer<ValueType> has both overloads of `from_json()`, this one is chosen. @tparam ValueType the returned value type @return copy of the JSON value, converted to @a ValueType @throw what @ref json_serializer<ValueType> `from_json()` method throws @since version 2.1.0 */ template < typename ValueType, detail::enable_if_t < detail::has_non_default_from_json<basic_json_t, ValueType>::value, int > = 0 > ValueType get_impl(detail::priority_tag<1> /*unused*/) const noexcept(noexcept( JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>()))) { return JSONSerializer<ValueType>::from_json(*this); } /*! @brief get special-case overload This overloads converts the current @ref basic_json in a different @ref basic_json type @tparam BasicJsonType == @ref basic_json @return a copy of *this, converted into @a BasicJsonType @complexity Depending on the implementation of the called `from_json()` method. @since version 3.2.0 */ template < typename BasicJsonType, detail::enable_if_t < detail::is_basic_json<BasicJsonType>::value, int > = 0 > BasicJsonType get_impl(detail::priority_tag<2> /*unused*/) const { return *this; } /*! @brief get special-case overload This overloads avoids a lot of template boilerplate, it can be seen as the identity method @tparam BasicJsonType == @ref basic_json @return a copy of *this @complexity Constant. @since version 2.1.0 */ template<typename BasicJsonType, detail::enable_if_t< std::is_same<BasicJsonType, basic_json_t>::value, int> = 0> basic_json get_impl(detail::priority_tag<3> /*unused*/) const { return *this; } /*! @brief get a pointer value (explicit) @copydoc get() */ template<typename PointerType, detail::enable_if_t< std::is_pointer<PointerType>::value, int> = 0> constexpr auto get_impl(detail::priority_tag<4> /*unused*/) const noexcept -> decltype(std::declval<const basic_json_t&>().template get_ptr<PointerType>()) { // delegate the call to get_ptr return get_ptr<PointerType>(); } public: /*! @brief get a (pointer) value (explicit) Performs explicit type conversion between the JSON value and a compatible value if required. - If the requested type is a pointer to the internally stored JSON value that pointer is returned. No copies are made. - If the requested type is the current @ref basic_json, or a different @ref basic_json convertible from the current @ref basic_json. - Otherwise the value is converted by calling the @ref json_serializer<ValueType> `from_json()` method. @tparam ValueTypeCV the provided value type @tparam ValueType the returned value type @return copy of the JSON value, converted to @tparam ValueType if necessary @throw what @ref json_serializer<ValueType> `from_json()` method throws if conversion is required @since version 2.1.0 */ template < typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>> #if defined(JSON_HAS_CPP_14) constexpr #endif auto get() const noexcept( noexcept(std::declval<const basic_json_t&>().template get_impl<ValueType>(detail::priority_tag<4> {}))) -> decltype(std::declval<const basic_json_t&>().template get_impl<ValueType>(detail::priority_tag<4> {})) { // we cannot static_assert on ValueTypeCV being non-const, because // there is support for get<const basic_json_t>(), which is why we // still need the uncvref static_assert(!std::is_reference<ValueTypeCV>::value, "get() cannot be used with reference types, you might want to use get_ref()"); return get_impl<ValueType>(detail::priority_tag<4> {}); } /*! @brief get a pointer value (explicit) Explicit pointer access to the internally stored JSON value. No copies are made. @warning The pointer becomes invalid if the underlying JSON object changes. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, @ref number_unsigned_t, or @ref number_float_t. @return pointer to the internally stored JSON value if the requested pointer type @a PointerType fits to the JSON value; `nullptr` otherwise @complexity Constant. @liveexample{The example below shows how pointers to internal values of a JSON value can be requested. Note that no type conversions are made and a `nullptr` is returned if the value and the requested pointer type does not match.,get__PointerType} @sa see @ref get_ptr() for explicit pointer-member access @since version 1.0.0 */ template<typename PointerType, typename std::enable_if< std::is_pointer<PointerType>::value, int>::type = 0> auto get() noexcept -> decltype(std::declval<basic_json_t&>().template get_ptr<PointerType>()) { // delegate the call to get_ptr return get_ptr<PointerType>(); } /*! @brief get a value (explicit) Explicit type conversion between the JSON value and a compatible value. The value is filled into the input parameter by calling the @ref json_serializer<ValueType> `from_json()` method. The function is equivalent to executing @code {.cpp} ValueType v; JSONSerializer<ValueType>::from_json(*this, v); @endcode This overloads is chosen if: - @a ValueType is not @ref basic_json, - @ref json_serializer<ValueType> has a `from_json()` method of the form `void from_json(const basic_json&, ValueType&)`, and @tparam ValueType the input parameter type. @return the input parameter, allowing chaining calls. @throw what @ref json_serializer<ValueType> `from_json()` method throws @liveexample{The example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers\, (2) A JSON array can be converted to a standard `std::vector<short>`\, (3) A JSON object can be converted to C++ associative containers such as `std::unordered_map<std::string\, json>`.,get_to} @since version 3.3.0 */ template < typename ValueType, detail::enable_if_t < !detail::is_basic_json<ValueType>::value&& detail::has_from_json<basic_json_t, ValueType>::value, int > = 0 > ValueType & get_to(ValueType& v) const noexcept(noexcept( JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), v))) { JSONSerializer<ValueType>::from_json(*this, v); return v; } // specialization to allow to call get_to with a basic_json value // see https://github.com/nlohmann/json/issues/2175 template<typename ValueType, detail::enable_if_t < detail::is_basic_json<ValueType>::value, int> = 0> ValueType & get_to(ValueType& v) const { v = *this; return v; } template < typename T, std::size_t N, typename Array = T (&)[N], // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) detail::enable_if_t < detail::has_from_json<basic_json_t, Array>::value, int > = 0 > Array get_to(T (&v)[N]) const // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) noexcept(noexcept(JSONSerializer<Array>::from_json( std::declval<const basic_json_t&>(), v))) { JSONSerializer<Array>::from_json(*this, v); return v; } /*! @brief get a reference value (implicit) Implicit reference access to the internally stored JSON value. No copies are made. @warning Writing data to the referee of the result yields an undefined state. @tparam ReferenceType reference type; must be a reference to @ref array_t, @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or @ref number_float_t. Enforced by static assertion. @return reference to the internally stored JSON value if the requested reference type @a ReferenceType fits to the JSON value; throws type_error.303 otherwise @throw type_error.303 in case passed type @a ReferenceType is incompatible with the stored JSON value; see example below @complexity Constant. @liveexample{The example shows several calls to `get_ref()`.,get_ref} @since version 1.1.0 */ template<typename ReferenceType, typename std::enable_if< std::is_reference<ReferenceType>::value, int>::type = 0> ReferenceType get_ref() { // delegate call to get_ref_impl return get_ref_impl<ReferenceType>(*this); } /*! @brief get a reference value (implicit) @copydoc get_ref() */ template < typename ReferenceType, typename std::enable_if < std::is_reference<ReferenceType>::value&& std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int >::type = 0 > ReferenceType get_ref() const { // delegate call to get_ref_impl return get_ref_impl<ReferenceType>(*this); } /*! @brief get a value (implicit) Implicit type conversion between the JSON value and a compatible value. The call is realized by calling @ref get() const. @tparam ValueType non-pointer type compatible to the JSON value, for instance `int` for JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for JSON arrays. The character type of @ref string_t as well as an initializer list of this type is excluded to avoid ambiguities as these types implicitly convert to `std::string`. @return copy of the JSON value, converted to type @a ValueType @throw type_error.302 in case passed type @a ValueType is incompatible to the JSON value type (e.g., the JSON value is of type boolean, but a string is requested); see example below @complexity Linear in the size of the JSON value. @liveexample{The example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers\, (2) A JSON array can be converted to a standard `std::vector<short>`\, (3) A JSON object can be converted to C++ associative containers such as `std::unordered_map<std::string\, json>`.,operator__ValueType} @since version 1.0.0 */ template < typename ValueType, typename std::enable_if < !std::is_pointer<ValueType>::value&& !std::is_same<ValueType, detail::json_ref<basic_json>>::value&& !std::is_same<ValueType, typename string_t::value_type>::value&& !detail::is_basic_json<ValueType>::value && !std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value #if defined(JSON_HAS_CPP_17) && (defined(__GNUC__) || (defined(_MSC_VER) && _MSC_VER >= 1910 && _MSC_VER <= 1914)) && !std::is_same<ValueType, typename std::string_view>::value #endif && detail::is_detected<detail::get_template_function, const basic_json_t&, ValueType>::value , int >::type = 0 > JSON_EXPLICIT operator ValueType() const { // delegate the call to get<>() const return get<ValueType>(); } /*! @return reference to the binary value @throw type_error.302 if the value is not binary @sa see @ref is_binary() to check if the value is binary @since version 3.8.0 */ binary_t& get_binary() { if (!is_binary()) { JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(type_name()), *this)); } return *get_ptr<binary_t*>(); } /// @copydoc get_binary() const binary_t& get_binary() const { if (!is_binary()) { JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(type_name()), *this)); } return *get_ptr<const binary_t*>(); } /// @} //////////////////// // element access // //////////////////// /// @name element access /// Access to the JSON value. /// @{ /*! @brief access specified array element with bounds checking Returns a reference to the element at specified location @a idx, with bounds checking. @param[in] idx index of the element to access @return reference to the element at index @a idx @throw type_error.304 if the JSON value is not an array; in this case, calling `at` with an index makes no sense. See example below. @throw out_of_range.401 if the index @a idx is out of range of the array; that is, `idx >= size()`. See example below. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @complexity Constant. @since version 1.0.0 @liveexample{The example below shows how array elements can be read and written using `at()`. It also demonstrates the different exceptions that can be thrown.,at__size_type} */ reference at(size_type idx) { // at only works for arrays if (JSON_HEDLEY_LIKELY(is_array())) { JSON_TRY { return set_parent(m_value.array->at(idx)); } JSON_CATCH (std::out_of_range&) { // create better exception explanation JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", *this)); } } else { JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this)); } } /*! @brief access specified array element with bounds checking Returns a const reference to the element at specified location @a idx, with bounds checking. @param[in] idx index of the element to access @return const reference to the element at index @a idx @throw type_error.304 if the JSON value is not an array; in this case, calling `at` with an index makes no sense. See example below. @throw out_of_range.401 if the index @a idx is out of range of the array; that is, `idx >= size()`. See example below. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @complexity Constant. @since version 1.0.0 @liveexample{The example below shows how array elements can be read using `at()`. It also demonstrates the different exceptions that can be thrown., at__size_type_const} */ const_reference at(size_type idx) const { // at only works for arrays if (JSON_HEDLEY_LIKELY(is_array())) { JSON_TRY { return m_value.array->at(idx); } JSON_CATCH (std::out_of_range&) { // create better exception explanation JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", *this)); } } else { JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this)); } } /*! @brief access specified object element with bounds checking Returns a reference to the element at with specified key @a key, with bounds checking. @param[in] key key of the element to access @return reference to the element at key @a key @throw type_error.304 if the JSON value is not an object; in this case, calling `at` with a key makes no sense. See example below. @throw out_of_range.403 if the key @a key is is not stored in the object; that is, `find(key) == end()`. See example below. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @complexity Logarithmic in the size of the container. @sa see @ref operator[](const typename object_t::key_type&) for unchecked access by reference @sa see @ref value() for access by value with a default value @since version 1.0.0 @liveexample{The example below shows how object elements can be read and written using `at()`. It also demonstrates the different exceptions that can be thrown.,at__object_t_key_type} */ reference at(const typename object_t::key_type& key) { // at only works for objects if (JSON_HEDLEY_LIKELY(is_object())) { JSON_TRY { return set_parent(m_value.object->at(key)); } JSON_CATCH (std::out_of_range&) { // create better exception explanation JSON_THROW(out_of_range::create(403, "key '" + key + "' not found", *this)); } } else { JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this)); } } /*! @brief access specified object element with bounds checking Returns a const reference to the element at with specified key @a key, with bounds checking. @param[in] key key of the element to access @return const reference to the element at key @a key @throw type_error.304 if the JSON value is not an object; in this case, calling `at` with a key makes no sense. See example below. @throw out_of_range.403 if the key @a key is is not stored in the object; that is, `find(key) == end()`. See example below. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @complexity Logarithmic in the size of the container. @sa see @ref operator[](const typename object_t::key_type&) for unchecked access by reference @sa see @ref value() for access by value with a default value @since version 1.0.0 @liveexample{The example below shows how object elements can be read using `at()`. It also demonstrates the different exceptions that can be thrown., at__object_t_key_type_const} */ const_reference at(const typename object_t::key_type& key) const { // at only works for objects if (JSON_HEDLEY_LIKELY(is_object())) { JSON_TRY { return m_value.object->at(key); } JSON_CATCH (std::out_of_range&) { // create better exception explanation JSON_THROW(out_of_range::create(403, "key '" + key + "' not found", *this)); } } else { JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this)); } } /*! @brief access specified array element Returns a reference to the element at specified location @a idx. @note If @a idx is beyond the range of the array (i.e., `idx >= size()`), then the array is silently filled up with `null` values to make `idx` a valid reference to the last stored element. @param[in] idx index of the element to access @return reference to the element at index @a idx @throw type_error.305 if the JSON value is not an array or null; in that cases, using the [] operator with an index makes no sense. @complexity Constant if @a idx is in the range of the array. Otherwise linear in `idx - size()`. @liveexample{The example below shows how array elements can be read and written using `[]` operator. Note the addition of `null` values.,operatorarray__size_type} @since version 1.0.0 */ reference operator[](size_type idx) { // implicitly convert null value to an empty array if (is_null()) { m_type = value_t::array; m_value.array = create<array_t>(); assert_invariant(); } // operator[] only works for arrays if (JSON_HEDLEY_LIKELY(is_array())) { // fill up array with null values if given idx is outside range if (idx >= m_value.array->size()) { #if JSON_DIAGNOSTICS // remember array size before resizing const auto previous_size = m_value.array->size(); #endif m_value.array->resize(idx + 1); #if JSON_DIAGNOSTICS // set parent for values added above set_parents(begin() + static_cast<typename iterator::difference_type>(previous_size), static_cast<typename iterator::difference_type>(idx + 1 - previous_size)); #endif } return m_value.array->operator[](idx); } JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name()), *this)); } /*! @brief access specified array element Returns a const reference to the element at specified location @a idx. @param[in] idx index of the element to access @return const reference to the element at index @a idx @throw type_error.305 if the JSON value is not an array; in that case, using the [] operator with an index makes no sense. @complexity Constant. @liveexample{The example below shows how array elements can be read using the `[]` operator.,operatorarray__size_type_const} @since version 1.0.0 */ const_reference operator[](size_type idx) const { // const operator[] only works for arrays if (JSON_HEDLEY_LIKELY(is_array())) { return m_value.array->operator[](idx); } JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name()), *this)); } /*! @brief access specified object element Returns a reference to the element at with specified key @a key. @note If @a key is not found in the object, then it is silently added to the object and filled with a `null` value to make `key` a valid reference. In case the value was `null` before, it is converted to an object. @param[in] key key of the element to access @return reference to the element at key @a key @throw type_error.305 if the JSON value is not an object or null; in that cases, using the [] operator with a key makes no sense. @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be read and written using the `[]` operator.,operatorarray__key_type} @sa see @ref at(const typename object_t::key_type&) for access by reference with range checking @sa see @ref value() for access by value with a default value @since version 1.0.0 */ reference operator[](const typename object_t::key_type& key) { // implicitly convert null value to an empty object if (is_null()) { m_type = value_t::object; m_value.object = create<object_t>(); assert_invariant(); } // operator[] only works for objects if (JSON_HEDLEY_LIKELY(is_object())) { return set_parent(m_value.object->operator[](key)); } JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this)); } /*! @brief read-only access specified object element Returns a const reference to the element at with specified key @a key. No bounds checking is performed. @warning If the element with key @a key does not exist, the behavior is undefined. @param[in] key key of the element to access @return const reference to the element at key @a key @pre The element with key @a key must exist. **This precondition is enforced with an assertion.** @throw type_error.305 if the JSON value is not an object; in that case, using the [] operator with a key makes no sense. @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be read using the `[]` operator.,operatorarray__key_type_const} @sa see @ref at(const typename object_t::key_type&) for access by reference with range checking @sa see @ref value() for access by value with a default value @since version 1.0.0 */ const_reference operator[](const typename object_t::key_type& key) const { // const operator[] only works for objects if (JSON_HEDLEY_LIKELY(is_object())) { JSON_ASSERT(m_value.object->find(key) != m_value.object->end()); return m_value.object->find(key)->second; } JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this)); } /*! @brief access specified object element Returns a reference to the element at with specified key @a key. @note If @a key is not found in the object, then it is silently added to the object and filled with a `null` value to make `key` a valid reference. In case the value was `null` before, it is converted to an object. @param[in] key key of the element to access @return reference to the element at key @a key @throw type_error.305 if the JSON value is not an object or null; in that cases, using the [] operator with a key makes no sense. @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be read and written using the `[]` operator.,operatorarray__key_type} @sa see @ref at(const typename object_t::key_type&) for access by reference with range checking @sa see @ref value() for access by value with a default value @since version 1.1.0 */ template<typename T> JSON_HEDLEY_NON_NULL(2) reference operator[](T* key) { // implicitly convert null to object if (is_null()) { m_type = value_t::object; m_value = value_t::object; assert_invariant(); } // at only works for objects if (JSON_HEDLEY_LIKELY(is_object())) { return set_parent(m_value.object->operator[](key)); } JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this)); } /*! @brief read-only access specified object element Returns a const reference to the element at with specified key @a key. No bounds checking is performed. @warning If the element with key @a key does not exist, the behavior is undefined. @param[in] key key of the element to access @return const reference to the element at key @a key @pre The element with key @a key must exist. **This precondition is enforced with an assertion.** @throw type_error.305 if the JSON value is not an object; in that case, using the [] operator with a key makes no sense. @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be read using the `[]` operator.,operatorarray__key_type_const} @sa see @ref at(const typename object_t::key_type&) for access by reference with range checking @sa see @ref value() for access by value with a default value @since version 1.1.0 */ template<typename T> JSON_HEDLEY_NON_NULL(2) const_reference operator[](T* key) const { // at only works for objects if (JSON_HEDLEY_LIKELY(is_object())) { JSON_ASSERT(m_value.object->find(key) != m_value.object->end()); return m_value.object->find(key)->second; } JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this)); } /*! @brief access specified object element with default value Returns either a copy of an object's element at the specified key @a key or a given default value if no element with key @a key exists. The function is basically equivalent to executing @code {.cpp} try { return at(key); } catch(out_of_range) { return default_value; } @endcode @note Unlike @ref at(const typename object_t::key_type&), this function does not throw if the given key @a key was not found. @note Unlike @ref operator[](const typename object_t::key_type& key), this function does not implicitly add an element to the position defined by @a key. This function is furthermore also applicable to const objects. @param[in] key key of the element to access @param[in] default_value the value to return if @a key is not found @tparam ValueType type compatible to JSON values, for instance `int` for JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for JSON arrays. Note the type of the expected value at @a key and the default value @a default_value must be compatible. @return copy of the element at key @a key or @a default_value if @a key is not found @throw type_error.302 if @a default_value does not match the type of the value at @a key @throw type_error.306 if the JSON value is not an object; in that case, using `value()` with a key makes no sense. @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be queried with a default value.,basic_json__value} @sa see @ref at(const typename object_t::key_type&) for access by reference with range checking @sa see @ref operator[](const typename object_t::key_type&) for unchecked access by reference @since version 1.0.0 */ // using std::is_convertible in a std::enable_if will fail when using explicit conversions template < class ValueType, typename std::enable_if < detail::is_getable<basic_json_t, ValueType>::value && !std::is_same<value_t, ValueType>::value, int >::type = 0 > ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const { // at only works for objects if (JSON_HEDLEY_LIKELY(is_object())) { // if key is found, return value and given default value otherwise const auto it = find(key); if (it != end()) { return it->template get<ValueType>(); } return default_value; } JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()), *this)); } /*! @brief overload for a default value of type const char* @copydoc basic_json::value(const typename object_t::key_type&, const ValueType&) const */ string_t value(const typename object_t::key_type& key, const char* default_value) const { return value(key, string_t(default_value)); } /*! @brief access specified object element via JSON Pointer with default value Returns either a copy of an object's element at the specified key @a key or a given default value if no element with key @a key exists. The function is basically equivalent to executing @code {.cpp} try { return at(ptr); } catch(out_of_range) { return default_value; } @endcode @note Unlike @ref at(const json_pointer&), this function does not throw if the given key @a key was not found. @param[in] ptr a JSON pointer to the element to access @param[in] default_value the value to return if @a ptr found no value @tparam ValueType type compatible to JSON values, for instance `int` for JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for JSON arrays. Note the type of the expected value at @a key and the default value @a default_value must be compatible. @return copy of the element at key @a key or @a default_value if @a key is not found @throw type_error.302 if @a default_value does not match the type of the value at @a ptr @throw type_error.306 if the JSON value is not an object; in that case, using `value()` with a key makes no sense. @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be queried with a default value.,basic_json__value_ptr} @sa see @ref operator[](const json_pointer&) for unchecked access by reference @since version 2.0.2 */ template<class ValueType, typename std::enable_if< detail::is_getable<basic_json_t, ValueType>::value, int>::type = 0> ValueType value(const json_pointer& ptr, const ValueType& default_value) const { // at only works for objects if (JSON_HEDLEY_LIKELY(is_object())) { // if pointer resolves a value, return it or use default value JSON_TRY { return ptr.get_checked(this).template get<ValueType>(); } JSON_INTERNAL_CATCH (out_of_range&) { return default_value; } } JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()), *this)); } /*! @brief overload for a default value of type const char* @copydoc basic_json::value(const json_pointer&, ValueType) const */ JSON_HEDLEY_NON_NULL(3) string_t value(const json_pointer& ptr, const char* default_value) const { return value(ptr, string_t(default_value)); } /*! @brief access the first element Returns a reference to the first element in the container. For a JSON container `c`, the expression `c.front()` is equivalent to `*c.begin()`. @return In case of a structured type (array or object), a reference to the first element is returned. In case of number, string, boolean, or binary values, a reference to the value is returned. @complexity Constant. @pre The JSON value must not be `null` (would throw `std::out_of_range`) or an empty array or object (undefined behavior, **guarded by assertions**). @post The JSON value remains unchanged. @throw invalid_iterator.214 when called on `null` value @liveexample{The following code shows an example for `front()`.,front} @sa see @ref back() -- access the last element @since version 1.0.0 */ reference front() { return *begin(); } /*! @copydoc basic_json::front() */ const_reference front() const { return *cbegin(); } /*! @brief access the last element Returns a reference to the last element in the container. For a JSON container `c`, the expression `c.back()` is equivalent to @code {.cpp} auto tmp = c.end(); --tmp; return *tmp; @endcode @return In case of a structured type (array or object), a reference to the last element is returned. In case of number, string, boolean, or binary values, a reference to the value is returned. @complexity Constant. @pre The JSON value must not be `null` (would throw `std::out_of_range`) or an empty array or object (undefined behavior, **guarded by assertions**). @post The JSON value remains unchanged. @throw invalid_iterator.214 when called on a `null` value. See example below. @liveexample{The following code shows an example for `back()`.,back} @sa see @ref front() -- access the first element @since version 1.0.0 */ reference back() { auto tmp = end(); --tmp; return *tmp; } /*! @copydoc basic_json::back() */ const_reference back() const { auto tmp = cend(); --tmp; return *tmp; } /*! @brief remove element given an iterator Removes the element specified by iterator @a pos. The iterator @a pos must be valid and dereferenceable. Thus the `end()` iterator (which is valid, but is not dereferenceable) cannot be used as a value for @a pos. If called on a primitive type other than `null`, the resulting JSON value will be `null`. @param[in] pos iterator to the element to remove @return Iterator following the last removed element. If the iterator @a pos refers to the last element, the `end()` iterator is returned. @tparam IteratorType an @ref iterator or @ref const_iterator @post Invalidates iterators and references at or after the point of the erase, including the `end()` iterator. @throw type_error.307 if called on a `null` value; example: `"cannot use erase() with null"` @throw invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: `"iterator does not fit current value"` @throw invalid_iterator.205 if called on a primitive type with invalid iterator (i.e., any iterator which is not `begin()`); example: `"iterator out of range"` @complexity The complexity depends on the type: - objects: amortized constant - arrays: linear in distance between @a pos and the end of the container - strings and binary: linear in the length of the member - other types: constant @liveexample{The example shows the result of `erase()` for different JSON types.,erase__IteratorType} @sa see @ref erase(IteratorType, IteratorType) -- removes the elements in the given range @sa see @ref erase(const typename object_t::key_type&) -- removes the element from an object at the given key @sa see @ref erase(const size_type) -- removes the element from an array at the given index @since version 1.0.0 */ template < class IteratorType, typename std::enable_if < std::is_same<IteratorType, typename basic_json_t::iterator>::value || std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int >::type = 0 > IteratorType erase(IteratorType pos) { // make sure iterator fits the current value if (JSON_HEDLEY_UNLIKELY(this != pos.m_object)) { JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this)); } IteratorType result = end(); switch (m_type) { case value_t::boolean: case value_t::number_float: case value_t::number_integer: case value_t::number_unsigned: case value_t::string: case value_t::binary: { if (JSON_HEDLEY_UNLIKELY(!pos.m_it.primitive_iterator.is_begin())) { JSON_THROW(invalid_iterator::create(205, "iterator out of range", *this)); } if (is_string()) { AllocatorType<string_t> alloc; std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string); std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1); m_value.string = nullptr; } else if (is_binary()) { AllocatorType<binary_t> alloc; std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.binary); std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.binary, 1); m_value.binary = nullptr; } m_type = value_t::null; assert_invariant(); break; } case value_t::object: { result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator); break; } case value_t::array: { result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator); break; } default: JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this)); } return result; } /*! @brief remove elements given an iterator range Removes the element specified by the range `[first; last)`. The iterator @a first does not need to be dereferenceable if `first == last`: erasing an empty range is a no-op. If called on a primitive type other than `null`, the resulting JSON value will be `null`. @param[in] first iterator to the beginning of the range to remove @param[in] last iterator past the end of the range to remove @return Iterator following the last removed element. If the iterator @a second refers to the last element, the `end()` iterator is returned. @tparam IteratorType an @ref iterator or @ref const_iterator @post Invalidates iterators and references at or after the point of the erase, including the `end()` iterator. @throw type_error.307 if called on a `null` value; example: `"cannot use erase() with null"` @throw invalid_iterator.203 if called on iterators which does not belong to the current JSON value; example: `"iterators do not fit current value"` @throw invalid_iterator.204 if called on a primitive type with invalid iterators (i.e., if `first != begin()` and `last != end()`); example: `"iterators out of range"` @complexity The complexity depends on the type: - objects: `log(size()) + std::distance(first, last)` - arrays: linear in the distance between @a first and @a last, plus linear in the distance between @a last and end of the container - strings and binary: linear in the length of the member - other types: constant @liveexample{The example shows the result of `erase()` for different JSON types.,erase__IteratorType_IteratorType} @sa see @ref erase(IteratorType) -- removes the element at a given position @sa see @ref erase(const typename object_t::key_type&) -- removes the element from an object at the given key @sa see @ref erase(const size_type) -- removes the element from an array at the given index @since version 1.0.0 */ template < class IteratorType, typename std::enable_if < std::is_same<IteratorType, typename basic_json_t::iterator>::value || std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int >::type = 0 > IteratorType erase(IteratorType first, IteratorType last) { // make sure iterator fits the current value if (JSON_HEDLEY_UNLIKELY(this != first.m_object || this != last.m_object)) { JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value", *this)); } IteratorType result = end(); switch (m_type) { case value_t::boolean: case value_t::number_float: case value_t::number_integer: case value_t::number_unsigned: case value_t::string: case value_t::binary: { if (JSON_HEDLEY_LIKELY(!first.m_it.primitive_iterator.is_begin() || !last.m_it.primitive_iterator.is_end())) { JSON_THROW(invalid_iterator::create(204, "iterators out of range", *this)); } if (is_string()) { AllocatorType<string_t> alloc; std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string); std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1); m_value.string = nullptr; } else if (is_binary()) { AllocatorType<binary_t> alloc; std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.binary); std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.binary, 1); m_value.binary = nullptr; } m_type = value_t::null; assert_invariant(); break; } case value_t::object: { result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator, last.m_it.object_iterator); break; } case value_t::array: { result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator, last.m_it.array_iterator); break; } default: JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this)); } return result; } /*! @brief remove element from a JSON object given a key Removes elements from a JSON object with the key value @a key. @param[in] key value of the elements to remove @return Number of elements removed. If @a ObjectType is the default `std::map` type, the return value will always be `0` (@a key was not found) or `1` (@a key was found). @post References and iterators to the erased elements are invalidated. Other references and iterators are not affected. @throw type_error.307 when called on a type other than JSON object; example: `"cannot use erase() with null"` @complexity `log(size()) + count(key)` @liveexample{The example shows the effect of `erase()`.,erase__key_type} @sa see @ref erase(IteratorType) -- removes the element at a given position @sa see @ref erase(IteratorType, IteratorType) -- removes the elements in the given range @sa see @ref erase(const size_type) -- removes the element from an array at the given index @since version 1.0.0 */ size_type erase(const typename object_t::key_type& key) { // this erase only works for objects if (JSON_HEDLEY_LIKELY(is_object())) { return m_value.object->erase(key); } JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this)); } /*! @brief remove element from a JSON array given an index Removes element from a JSON array at the index @a idx. @param[in] idx index of the element to remove @throw type_error.307 when called on a type other than JSON object; example: `"cannot use erase() with null"` @throw out_of_range.401 when `idx >= size()`; example: `"array index 17 is out of range"` @complexity Linear in distance between @a idx and the end of the container. @liveexample{The example shows the effect of `erase()`.,erase__size_type} @sa see @ref erase(IteratorType) -- removes the element at a given position @sa see @ref erase(IteratorType, IteratorType) -- removes the elements in the given range @sa see @ref erase(const typename object_t::key_type&) -- removes the element from an object at the given key @since version 1.0.0 */ void erase(const size_type idx) { // this erase only works for arrays if (JSON_HEDLEY_LIKELY(is_array())) { if (JSON_HEDLEY_UNLIKELY(idx >= size())) { JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", *this)); } m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx)); } else { JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this)); } } /// @} //////////// // lookup // //////////// /// @name lookup /// @{ /*! @brief find an element in a JSON object Finds an element in a JSON object with key equivalent to @a key. If the element is not found or the JSON value is not an object, end() is returned. @note This method always returns @ref end() when executed on a JSON type that is not an object. @param[in] key key value of the element to search for. @return Iterator to an element with key equivalent to @a key. If no such element is found or the JSON value is not an object, past-the-end (see @ref end()) iterator is returned. @complexity Logarithmic in the size of the JSON object. @liveexample{The example shows how `find()` is used.,find__key_type} @sa see @ref contains(KeyT&&) const -- checks whether a key exists @since version 1.0.0 */ template<typename KeyT> iterator find(KeyT&& key) { auto result = end(); if (is_object()) { result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key)); } return result; } /*! @brief find an element in a JSON object @copydoc find(KeyT&&) */ template<typename KeyT> const_iterator find(KeyT&& key) const { auto result = cend(); if (is_object()) { result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key)); } return result; } /*! @brief returns the number of occurrences of a key in a JSON object Returns the number of elements with key @a key. If ObjectType is the default `std::map` type, the return value will always be `0` (@a key was not found) or `1` (@a key was found). @note This method always returns `0` when executed on a JSON type that is not an object. @param[in] key key value of the element to count @return Number of elements with key @a key. If the JSON value is not an object, the return value will be `0`. @complexity Logarithmic in the size of the JSON object. @liveexample{The example shows how `count()` is used.,count} @since version 1.0.0 */ template<typename KeyT> size_type count(KeyT&& key) const { // return 0 for all nonobject types return is_object() ? m_value.object->count(std::forward<KeyT>(key)) : 0; } /*! @brief check the existence of an element in a JSON object Check whether an element exists in a JSON object with key equivalent to @a key. If the element is not found or the JSON value is not an object, false is returned. @note This method always returns false when executed on a JSON type that is not an object. @param[in] key key value to check its existence. @return true if an element with specified @a key exists. If no such element with such key is found or the JSON value is not an object, false is returned. @complexity Logarithmic in the size of the JSON object. @liveexample{The following code shows an example for `contains()`.,contains} @sa see @ref find(KeyT&&) -- returns an iterator to an object element @sa see @ref contains(const json_pointer&) const -- checks the existence for a JSON pointer @since version 3.6.0 */ template < typename KeyT, typename std::enable_if < !std::is_same<typename std::decay<KeyT>::type, json_pointer>::value, int >::type = 0 > bool contains(KeyT && key) const { return is_object() && m_value.object->find(std::forward<KeyT>(key)) != m_value.object->end(); } /*! @brief check the existence of an element in a JSON object given a JSON pointer Check whether the given JSON pointer @a ptr can be resolved in the current JSON value. @note This method can be executed on any JSON value type. @param[in] ptr JSON pointer to check its existence. @return true if the JSON pointer can be resolved to a stored value, false otherwise. @post If `j.contains(ptr)` returns true, it is safe to call `j[ptr]`. @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @complexity Logarithmic in the size of the JSON object. @liveexample{The following code shows an example for `contains()`.,contains_json_pointer} @sa see @ref contains(KeyT &&) const -- checks the existence of a key @since version 3.7.0 */ bool contains(const json_pointer& ptr) const { return ptr.contains(this); } /// @} /////////////// // iterators // /////////////// /// @name iterators /// @{ /*! @brief returns an iterator to the first element Returns an iterator to the first element. @image html range-begin-end.svg "Illustration from cppreference.com" @return iterator to the first element @complexity Constant. @requirement This function helps `basic_json` satisfying the [Container](https://en.cppreference.com/w/cpp/named_req/Container) requirements: - The complexity is constant. @liveexample{The following code shows an example for `begin()`.,begin} @sa see @ref cbegin() -- returns a const iterator to the beginning @sa see @ref end() -- returns an iterator to the end @sa see @ref cend() -- returns a const iterator to the end @since version 1.0.0 */ iterator begin() noexcept { iterator result(this); result.set_begin(); return result; } /*! @copydoc basic_json::cbegin() */ const_iterator begin() const noexcept { return cbegin(); } /*! @brief returns a const iterator to the first element Returns a const iterator to the first element. @image html range-begin-end.svg "Illustration from cppreference.com" @return const iterator to the first element @complexity Constant. @requirement This function helps `basic_json` satisfying the [Container](https://en.cppreference.com/w/cpp/named_req/Container) requirements: - The complexity is constant. - Has the semantics of `const_cast<const basic_json&>(*this).begin()`. @liveexample{The following code shows an example for `cbegin()`.,cbegin} @sa see @ref begin() -- returns an iterator to the beginning @sa see @ref end() -- returns an iterator to the end @sa see @ref cend() -- returns a const iterator to the end @since version 1.0.0 */ const_iterator cbegin() const noexcept { const_iterator result(this); result.set_begin(); return result; } /*! @brief returns an iterator to one past the last element Returns an iterator to one past the last element. @image html range-begin-end.svg "Illustration from cppreference.com" @return iterator one past the last element @complexity Constant. @requirement This function helps `basic_json` satisfying the [Container](https://en.cppreference.com/w/cpp/named_req/Container) requirements: - The complexity is constant. @liveexample{The following code shows an example for `end()`.,end} @sa see @ref cend() -- returns a const iterator to the end @sa see @ref begin() -- returns an iterator to the beginning @sa see @ref cbegin() -- returns a const iterator to the beginning @since version 1.0.0 */ iterator end() noexcept { iterator result(this); result.set_end(); return result; } /*! @copydoc basic_json::cend() */ const_iterator end() const noexcept { return cend(); } /*! @brief returns a const iterator to one past the last element Returns a const iterator to one past the last element. @image html range-begin-end.svg "Illustration from cppreference.com" @return const iterator one past the last element @complexity Constant. @requirement This function helps `basic_json` satisfying the [Container](https://en.cppreference.com/w/cpp/named_req/Container) requirements: - The complexity is constant. - Has the semantics of `const_cast<const basic_json&>(*this).end()`. @liveexample{The following code shows an example for `cend()`.,cend} @sa see @ref end() -- returns an iterator to the end @sa see @ref begin() -- returns an iterator to the beginning @sa see @ref cbegin() -- returns a const iterator to the beginning @since version 1.0.0 */ const_iterator cend() const noexcept { const_iterator result(this); result.set_end(); return result; } /*! @brief returns an iterator to the reverse-beginning Returns an iterator to the reverse-beginning; that is, the last element. @image html range-rbegin-rend.svg "Illustration from cppreference.com" @complexity Constant. @requirement This function helps `basic_json` satisfying the [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer) requirements: - The complexity is constant. - Has the semantics of `reverse_iterator(end())`. @liveexample{The following code shows an example for `rbegin()`.,rbegin} @sa see @ref crbegin() -- returns a const reverse iterator to the beginning @sa see @ref rend() -- returns a reverse iterator to the end @sa see @ref crend() -- returns a const reverse iterator to the end @since version 1.0.0 */ reverse_iterator rbegin() noexcept { return reverse_iterator(end()); } /*! @copydoc basic_json::crbegin() */ const_reverse_iterator rbegin() const noexcept { return crbegin(); } /*! @brief returns an iterator to the reverse-end Returns an iterator to the reverse-end; that is, one before the first element. @image html range-rbegin-rend.svg "Illustration from cppreference.com" @complexity Constant. @requirement This function helps `basic_json` satisfying the [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer) requirements: - The complexity is constant. - Has the semantics of `reverse_iterator(begin())`. @liveexample{The following code shows an example for `rend()`.,rend} @sa see @ref crend() -- returns a const reverse iterator to the end @sa see @ref rbegin() -- returns a reverse iterator to the beginning @sa see @ref crbegin() -- returns a const reverse iterator to the beginning @since version 1.0.0 */ reverse_iterator rend() noexcept { return reverse_iterator(begin()); } /*! @copydoc basic_json::crend() */ const_reverse_iterator rend() const noexcept { return crend(); } /*! @brief returns a const reverse iterator to the last element Returns a const iterator to the reverse-beginning; that is, the last element. @image html range-rbegin-rend.svg "Illustration from cppreference.com" @complexity Constant. @requirement This function helps `basic_json` satisfying the [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer) requirements: - The complexity is constant. - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`. @liveexample{The following code shows an example for `crbegin()`.,crbegin} @sa see @ref rbegin() -- returns a reverse iterator to the beginning @sa see @ref rend() -- returns a reverse iterator to the end @sa see @ref crend() -- returns a const reverse iterator to the end @since version 1.0.0 */ const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(cend()); } /*! @brief returns a const reverse iterator to one before the first Returns a const reverse iterator to the reverse-end; that is, one before the first element. @image html range-rbegin-rend.svg "Illustration from cppreference.com" @complexity Constant. @requirement This function helps `basic_json` satisfying the [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer) requirements: - The complexity is constant. - Has the semantics of `const_cast<const basic_json&>(*this).rend()`. @liveexample{The following code shows an example for `crend()`.,crend} @sa see @ref rend() -- returns a reverse iterator to the end @sa see @ref rbegin() -- returns a reverse iterator to the beginning @sa see @ref crbegin() -- returns a const reverse iterator to the beginning @since version 1.0.0 */ const_reverse_iterator crend() const noexcept { return const_reverse_iterator(cbegin()); } public: /*! @brief wrapper to access iterator member functions in range-based for This function allows to access @ref iterator::key() and @ref iterator::value() during range-based for loops. In these loops, a reference to the JSON values is returned, so there is no access to the underlying iterator. For loop without iterator_wrapper: @code{cpp} for (auto it = j_object.begin(); it != j_object.end(); ++it) { std::cout << "key: " << it.key() << ", value:" << it.value() << '\n'; } @endcode Range-based for loop without iterator proxy: @code{cpp} for (auto it : j_object) { // "it" is of type json::reference and has no key() member std::cout << "value: " << it << '\n'; } @endcode Range-based for loop with iterator proxy: @code{cpp} for (auto it : json::iterator_wrapper(j_object)) { std::cout << "key: " << it.key() << ", value:" << it.value() << '\n'; } @endcode @note When iterating over an array, `key()` will return the index of the element as string (see example). @param[in] ref reference to a JSON value @return iteration proxy object wrapping @a ref with an interface to use in range-based for loops @liveexample{The following code shows how the wrapper is used,iterator_wrapper} @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @complexity Constant. @note The name of this function is not yet final and may change in the future. @deprecated This stream operator is deprecated and will be removed in future 4.0.0 of the library. Please use @ref items() instead; that is, replace `json::iterator_wrapper(j)` with `j.items()`. */ JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items()) static iteration_proxy<iterator> iterator_wrapper(reference ref) noexcept { return ref.items(); } /*! @copydoc iterator_wrapper(reference) */ JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items()) static iteration_proxy<const_iterator> iterator_wrapper(const_reference ref) noexcept { return ref.items(); } /*! @brief helper to access iterator member functions in range-based for This function allows to access @ref iterator::key() and @ref iterator::value() during range-based for loops. In these loops, a reference to the JSON values is returned, so there is no access to the underlying iterator. For loop without `items()` function: @code{cpp} for (auto it = j_object.begin(); it != j_object.end(); ++it) { std::cout << "key: " << it.key() << ", value:" << it.value() << '\n'; } @endcode Range-based for loop without `items()` function: @code{cpp} for (auto it : j_object) { // "it" is of type json::reference and has no key() member std::cout << "value: " << it << '\n'; } @endcode Range-based for loop with `items()` function: @code{cpp} for (auto& el : j_object.items()) { std::cout << "key: " << el.key() << ", value:" << el.value() << '\n'; } @endcode The `items()` function also allows to use [structured bindings](https://en.cppreference.com/w/cpp/language/structured_binding) (C++17): @code{cpp} for (auto& [key, val] : j_object.items()) { std::cout << "key: " << key << ", value:" << val << '\n'; } @endcode @note When iterating over an array, `key()` will return the index of the element as string (see example). For primitive types (e.g., numbers), `key()` returns an empty string. @warning Using `items()` on temporary objects is dangerous. Make sure the object's lifetime exeeds the iteration. See <https://github.com/nlohmann/json/issues/2040> for more information. @return iteration proxy object wrapping @a ref with an interface to use in range-based for loops @liveexample{The following code shows how the function is used.,items} @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @complexity Constant. @since version 3.1.0, structured bindings support since 3.5.0. */ iteration_proxy<iterator> items() noexcept { return iteration_proxy<iterator>(*this); } /*! @copydoc items() */ iteration_proxy<const_iterator> items() const noexcept { return iteration_proxy<const_iterator>(*this); } /// @} ////////////// // capacity // ////////////// /// @name capacity /// @{ /*! @brief checks whether the container is empty. Checks if a JSON value has no elements (i.e. whether its @ref size is `0`). @return The return value depends on the different types and is defined as follows: Value type | return value ----------- | ------------- null | `true` boolean | `false` string | `false` number | `false` binary | `false` object | result of function `object_t::empty()` array | result of function `array_t::empty()` @liveexample{The following code uses `empty()` to check if a JSON object contains any elements.,empty} @complexity Constant, as long as @ref array_t and @ref object_t satisfy the Container concept; that is, their `empty()` functions have constant complexity. @iterators No changes. @exceptionsafety No-throw guarantee: this function never throws exceptions. @note This function does not return whether a string stored as JSON value is empty - it returns whether the JSON container itself is empty which is false in the case of a string. @requirement This function helps `basic_json` satisfying the [Container](https://en.cppreference.com/w/cpp/named_req/Container) requirements: - The complexity is constant. - Has the semantics of `begin() == end()`. @sa see @ref size() -- returns the number of elements @since version 1.0.0 */ bool empty() const noexcept { switch (m_type) { case value_t::null: { // null values are empty return true; } case value_t::array: { // delegate call to array_t::empty() return m_value.array->empty(); } case value_t::object: { // delegate call to object_t::empty() return m_value.object->empty(); } default: { // all other types are nonempty return false; } } } /*! @brief returns the number of elements Returns the number of elements in a JSON value. @return The return value depends on the different types and is defined as follows: Value type | return value ----------- | ------------- null | `0` boolean | `1` string | `1` number | `1` binary | `1` object | result of function object_t::size() array | result of function array_t::size() @liveexample{The following code calls `size()` on the different value types.,size} @complexity Constant, as long as @ref array_t and @ref object_t satisfy the Container concept; that is, their size() functions have constant complexity. @iterators No changes. @exceptionsafety No-throw guarantee: this function never throws exceptions. @note This function does not return the length of a string stored as JSON value - it returns the number of elements in the JSON value which is 1 in the case of a string. @requirement This function helps `basic_json` satisfying the [Container](https://en.cppreference.com/w/cpp/named_req/Container) requirements: - The complexity is constant. - Has the semantics of `std::distance(begin(), end())`. @sa see @ref empty() -- checks whether the container is empty @sa see @ref max_size() -- returns the maximal number of elements @since version 1.0.0 */ size_type size() const noexcept { switch (m_type) { case value_t::null: { // null values are empty return 0; } case value_t::array: { // delegate call to array_t::size() return m_value.array->size(); } case value_t::object: { // delegate call to object_t::size() return m_value.object->size(); } default: { // all other types have size 1 return 1; } } } /*! @brief returns the maximum possible number of elements Returns the maximum number of elements a JSON value is able to hold due to system or library implementation limitations, i.e. `std::distance(begin(), end())` for the JSON value. @return The return value depends on the different types and is defined as follows: Value type | return value ----------- | ------------- null | `0` (same as `size()`) boolean | `1` (same as `size()`) string | `1` (same as `size()`) number | `1` (same as `size()`) binary | `1` (same as `size()`) object | result of function `object_t::max_size()` array | result of function `array_t::max_size()` @liveexample{The following code calls `max_size()` on the different value types. Note the output is implementation specific.,max_size} @complexity Constant, as long as @ref array_t and @ref object_t satisfy the Container concept; that is, their `max_size()` functions have constant complexity. @iterators No changes. @exceptionsafety No-throw guarantee: this function never throws exceptions. @requirement This function helps `basic_json` satisfying the [Container](https://en.cppreference.com/w/cpp/named_req/Container) requirements: - The complexity is constant. - Has the semantics of returning `b.size()` where `b` is the largest possible JSON value. @sa see @ref size() -- returns the number of elements @since version 1.0.0 */ size_type max_size() const noexcept { switch (m_type) { case value_t::array: { // delegate call to array_t::max_size() return m_value.array->max_size(); } case value_t::object: { // delegate call to object_t::max_size() return m_value.object->max_size(); } default: { // all other types have max_size() == size() return size(); } } } /// @} /////////////// // modifiers // /////////////// /// @name modifiers /// @{ /*! @brief clears the contents Clears the content of a JSON value and resets it to the default value as if @ref basic_json(value_t) would have been called with the current value type from @ref type(): Value type | initial value ----------- | ------------- null | `null` boolean | `false` string | `""` number | `0` binary | An empty byte vector object | `{}` array | `[]` @post Has the same effect as calling @code {.cpp} *this = basic_json(type()); @endcode @liveexample{The example below shows the effect of `clear()` to different JSON types.,clear} @complexity Linear in the size of the JSON value. @iterators All iterators, pointers and references related to this container are invalidated. @exceptionsafety No-throw guarantee: this function never throws exceptions. @sa see @ref basic_json(value_t) -- constructor that creates an object with the same value than calling `clear()` @since version 1.0.0 */ void clear() noexcept { switch (m_type) { case value_t::number_integer: { m_value.number_integer = 0; break; } case value_t::number_unsigned: { m_value.number_unsigned = 0; break; } case value_t::number_float: { m_value.number_float = 0.0; break; } case value_t::boolean: { m_value.boolean = false; break; } case value_t::string: { m_value.string->clear(); break; } case value_t::binary: { m_value.binary->clear(); break; } case value_t::array: { m_value.array->clear(); break; } case value_t::object: { m_value.object->clear(); break; } default: break; } } /*! @brief add an object to an array Appends the given element @a val to the end of the JSON value. If the function is called on a JSON null value, an empty array is created before appending @a val. @param[in] val the value to add to the JSON array @throw type_error.308 when called on a type other than JSON array or null; example: `"cannot use push_back() with number"` @complexity Amortized constant. @liveexample{The example shows how `push_back()` and `+=` can be used to add elements to a JSON array. Note how the `null` value was silently converted to a JSON array.,push_back} @since version 1.0.0 */ void push_back(basic_json&& val) { // push_back only works for null objects or arrays if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array()))) { JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()), *this)); } // transform null object into an array if (is_null()) { m_type = value_t::array; m_value = value_t::array; assert_invariant(); } // add element to array (move semantics) const auto old_capacity = m_value.array->capacity(); m_value.array->push_back(std::move(val)); set_parent(m_value.array->back(), old_capacity); // if val is moved from, basic_json move constructor marks it null so we do not call the destructor } /*! @brief add an object to an array @copydoc push_back(basic_json&&) */ reference operator+=(basic_json&& val) { push_back(std::move(val)); return *this; } /*! @brief add an object to an array @copydoc push_back(basic_json&&) */ void push_back(const basic_json& val) { // push_back only works for null objects or arrays if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array()))) { JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()), *this)); } // transform null object into an array if (is_null()) { m_type = value_t::array; m_value = value_t::array; assert_invariant(); } // add element to array const auto old_capacity = m_value.array->capacity(); m_value.array->push_back(val); set_parent(m_value.array->back(), old_capacity); } /*! @brief add an object to an array @copydoc push_back(basic_json&&) */ reference operator+=(const basic_json& val) { push_back(val); return *this; } /*! @brief add an object to an object Inserts the given element @a val to the JSON object. If the function is called on a JSON null value, an empty object is created before inserting @a val. @param[in] val the value to add to the JSON object @throw type_error.308 when called on a type other than JSON object or null; example: `"cannot use push_back() with number"` @complexity Logarithmic in the size of the container, O(log(`size()`)). @liveexample{The example shows how `push_back()` and `+=` can be used to add elements to a JSON object. Note how the `null` value was silently converted to a JSON object.,push_back__object_t__value} @since version 1.0.0 */ void push_back(const typename object_t::value_type& val) { // push_back only works for null objects or objects if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object()))) { JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()), *this)); } // transform null object into an object if (is_null()) { m_type = value_t::object; m_value = value_t::object; assert_invariant(); } // add element to object auto res = m_value.object->insert(val); set_parent(res.first->second); } /*! @brief add an object to an object @copydoc push_back(const typename object_t::value_type&) */ reference operator+=(const typename object_t::value_type& val) { push_back(val); return *this; } /*! @brief add an object to an object This function allows to use `push_back` with an initializer list. In case 1. the current value is an object, 2. the initializer list @a init contains only two elements, and 3. the first element of @a init is a string, @a init is converted into an object element and added using @ref push_back(const typename object_t::value_type&). Otherwise, @a init is converted to a JSON value and added using @ref push_back(basic_json&&). @param[in] init an initializer list @complexity Linear in the size of the initializer list @a init. @note This function is required to resolve an ambiguous overload error, because pairs like `{"key", "value"}` can be both interpreted as `object_t::value_type` or `std::initializer_list<basic_json>`, see https://github.com/nlohmann/json/issues/235 for more information. @liveexample{The example shows how initializer lists are treated as objects when possible.,push_back__initializer_list} */ void push_back(initializer_list_t init) { if (is_object() && init.size() == 2 && (*init.begin())->is_string()) { basic_json&& key = init.begin()->moved_or_copied(); push_back(typename object_t::value_type( std::move(key.get_ref<string_t&>()), (init.begin() + 1)->moved_or_copied())); } else { push_back(basic_json(init)); } } /*! @brief add an object to an object @copydoc push_back(initializer_list_t) */ reference operator+=(initializer_list_t init) { push_back(init); return *this; } /*! @brief add an object to an array Creates a JSON value from the passed parameters @a args to the end of the JSON value. If the function is called on a JSON null value, an empty array is created before appending the value created from @a args. @param[in] args arguments to forward to a constructor of @ref basic_json @tparam Args compatible types to create a @ref basic_json object @return reference to the inserted element @throw type_error.311 when called on a type other than JSON array or null; example: `"cannot use emplace_back() with number"` @complexity Amortized constant. @liveexample{The example shows how `push_back()` can be used to add elements to a JSON array. Note how the `null` value was silently converted to a JSON array.,emplace_back} @since version 2.0.8, returns reference since 3.7.0 */ template<class... Args> reference emplace_back(Args&& ... args) { // emplace_back only works for null objects or arrays if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array()))) { JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name()), *this)); } // transform null object into an array if (is_null()) { m_type = value_t::array; m_value = value_t::array; assert_invariant(); } // add element to array (perfect forwarding) const auto old_capacity = m_value.array->capacity(); m_value.array->emplace_back(std::forward<Args>(args)...); return set_parent(m_value.array->back(), old_capacity); } /*! @brief add an object to an object if key does not exist Inserts a new element into a JSON object constructed in-place with the given @a args if there is no element with the key in the container. If the function is called on a JSON null value, an empty object is created before appending the value created from @a args. @param[in] args arguments to forward to a constructor of @ref basic_json @tparam Args compatible types to create a @ref basic_json object @return a pair consisting of an iterator to the inserted element, or the already-existing element if no insertion happened, and a bool denoting whether the insertion took place. @throw type_error.311 when called on a type other than JSON object or null; example: `"cannot use emplace() with number"` @complexity Logarithmic in the size of the container, O(log(`size()`)). @liveexample{The example shows how `emplace()` can be used to add elements to a JSON object. Note how the `null` value was silently converted to a JSON object. Further note how no value is added if there was already one value stored with the same key.,emplace} @since version 2.0.8 */ template<class... Args> std::pair<iterator, bool> emplace(Args&& ... args) { // emplace only works for null objects or arrays if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object()))) { JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name()), *this)); } // transform null object into an object if (is_null()) { m_type = value_t::object; m_value = value_t::object; assert_invariant(); } // add element to array (perfect forwarding) auto res = m_value.object->emplace(std::forward<Args>(args)...); set_parent(res.first->second); // create result iterator and set iterator to the result of emplace auto it = begin(); it.m_it.object_iterator = res.first; // return pair of iterator and boolean return {it, res.second}; } /// Helper for insertion of an iterator /// @note: This uses std::distance to support GCC 4.8, /// see https://github.com/nlohmann/json/pull/1257 template<typename... Args> iterator insert_iterator(const_iterator pos, Args&& ... args) { iterator result(this); JSON_ASSERT(m_value.array != nullptr); auto insert_pos = std::distance(m_value.array->begin(), pos.m_it.array_iterator); m_value.array->insert(pos.m_it.array_iterator, std::forward<Args>(args)...); result.m_it.array_iterator = m_value.array->begin() + insert_pos; // This could have been written as: // result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val); // but the return value of insert is missing in GCC 4.8, so it is written this way instead. set_parents(); return result; } /*! @brief inserts element Inserts element @a val before iterator @a pos. @param[in] pos iterator before which the content will be inserted; may be the end() iterator @param[in] val element to insert @return iterator pointing to the inserted @a val. @throw type_error.309 if called on JSON values other than arrays; example: `"cannot use insert() with string"` @throw invalid_iterator.202 if @a pos is not an iterator of *this; example: `"iterator does not fit current value"` @complexity Constant plus linear in the distance between @a pos and end of the container. @liveexample{The example shows how `insert()` is used.,insert} @since version 1.0.0 */ iterator insert(const_iterator pos, const basic_json& val) { // insert only works for arrays if (JSON_HEDLEY_LIKELY(is_array())) { // check if iterator pos fits to this JSON value if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) { JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this)); } // insert to array and return iterator return insert_iterator(pos, val); } JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this)); } /*! @brief inserts element @copydoc insert(const_iterator, const basic_json&) */ iterator insert(const_iterator pos, basic_json&& val) { return insert(pos, val); } /*! @brief inserts elements Inserts @a cnt copies of @a val before iterator @a pos. @param[in] pos iterator before which the content will be inserted; may be the end() iterator @param[in] cnt number of copies of @a val to insert @param[in] val element to insert @return iterator pointing to the first element inserted, or @a pos if `cnt==0` @throw type_error.309 if called on JSON values other than arrays; example: `"cannot use insert() with string"` @throw invalid_iterator.202 if @a pos is not an iterator of *this; example: `"iterator does not fit current value"` @complexity Linear in @a cnt plus linear in the distance between @a pos and end of the container. @liveexample{The example shows how `insert()` is used.,insert__count} @since version 1.0.0 */ iterator insert(const_iterator pos, size_type cnt, const basic_json& val) { // insert only works for arrays if (JSON_HEDLEY_LIKELY(is_array())) { // check if iterator pos fits to this JSON value if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) { JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this)); } // insert to array and return iterator return insert_iterator(pos, cnt, val); } JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this)); } /*! @brief inserts elements Inserts elements from range `[first, last)` before iterator @a pos. @param[in] pos iterator before which the content will be inserted; may be the end() iterator @param[in] first begin of the range of elements to insert @param[in] last end of the range of elements to insert @throw type_error.309 if called on JSON values other than arrays; example: `"cannot use insert() with string"` @throw invalid_iterator.202 if @a pos is not an iterator of *this; example: `"iterator does not fit current value"` @throw invalid_iterator.210 if @a first and @a last do not belong to the same JSON value; example: `"iterators do not fit"` @throw invalid_iterator.211 if @a first or @a last are iterators into container for which insert is called; example: `"passed iterators may not belong to container"` @return iterator pointing to the first element inserted, or @a pos if `first==last` @complexity Linear in `std::distance(first, last)` plus linear in the distance between @a pos and end of the container. @liveexample{The example shows how `insert()` is used.,insert__range} @since version 1.0.0 */ iterator insert(const_iterator pos, const_iterator first, const_iterator last) { // insert only works for arrays if (JSON_HEDLEY_UNLIKELY(!is_array())) { JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this)); } // check if iterator pos fits to this JSON value if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) { JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this)); } // check if range iterators belong to the same JSON object if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) { JSON_THROW(invalid_iterator::create(210, "iterators do not fit", *this)); } if (JSON_HEDLEY_UNLIKELY(first.m_object == this)) { JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container", *this)); } // insert to array and return iterator return insert_iterator(pos, first.m_it.array_iterator, last.m_it.array_iterator); } /*! @brief inserts elements Inserts elements from initializer list @a ilist before iterator @a pos. @param[in] pos iterator before which the content will be inserted; may be the end() iterator @param[in] ilist initializer list to insert the values from @throw type_error.309 if called on JSON values other than arrays; example: `"cannot use insert() with string"` @throw invalid_iterator.202 if @a pos is not an iterator of *this; example: `"iterator does not fit current value"` @return iterator pointing to the first element inserted, or @a pos if `ilist` is empty @complexity Linear in `ilist.size()` plus linear in the distance between @a pos and end of the container. @liveexample{The example shows how `insert()` is used.,insert__ilist} @since version 1.0.0 */ iterator insert(const_iterator pos, initializer_list_t ilist) { // insert only works for arrays if (JSON_HEDLEY_UNLIKELY(!is_array())) { JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this)); } // check if iterator pos fits to this JSON value if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) { JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this)); } // insert to array and return iterator return insert_iterator(pos, ilist.begin(), ilist.end()); } /*! @brief inserts elements Inserts elements from range `[first, last)`. @param[in] first begin of the range of elements to insert @param[in] last end of the range of elements to insert @throw type_error.309 if called on JSON values other than objects; example: `"cannot use insert() with string"` @throw invalid_iterator.202 if iterator @a first or @a last does does not point to an object; example: `"iterators first and last must point to objects"` @throw invalid_iterator.210 if @a first and @a last do not belong to the same JSON value; example: `"iterators do not fit"` @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number of elements to insert. @liveexample{The example shows how `insert()` is used.,insert__range_object} @since version 3.0.0 */ void insert(const_iterator first, const_iterator last) { // insert only works for objects if (JSON_HEDLEY_UNLIKELY(!is_object())) { JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this)); } // check if range iterators belong to the same JSON object if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) { JSON_THROW(invalid_iterator::create(210, "iterators do not fit", *this)); } // passed iterators must belong to objects if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object())) { JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects", *this)); } m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator); } /*! @brief updates a JSON object from another object, overwriting existing keys Inserts all values from JSON object @a j and overwrites existing keys. @param[in] j JSON object to read values from @throw type_error.312 if called on JSON values other than objects; example: `"cannot use update() with string"` @complexity O(N*log(size() + N)), where N is the number of elements to insert. @liveexample{The example shows how `update()` is used.,update} @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update @since version 3.0.0 */ void update(const_reference j) { // implicitly convert null value to an empty object if (is_null()) { m_type = value_t::object; m_value.object = create<object_t>(); assert_invariant(); } if (JSON_HEDLEY_UNLIKELY(!is_object())) { JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name()), *this)); } if (JSON_HEDLEY_UNLIKELY(!j.is_object())) { JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(j.type_name()), *this)); } for (auto it = j.cbegin(); it != j.cend(); ++it) { m_value.object->operator[](it.key()) = it.value(); } } /*! @brief updates a JSON object from another object, overwriting existing keys Inserts all values from from range `[first, last)` and overwrites existing keys. @param[in] first begin of the range of elements to insert @param[in] last end of the range of elements to insert @throw type_error.312 if called on JSON values other than objects; example: `"cannot use update() with string"` @throw invalid_iterator.202 if iterator @a first or @a last does does not point to an object; example: `"iterators first and last must point to objects"` @throw invalid_iterator.210 if @a first and @a last do not belong to the same JSON value; example: `"iterators do not fit"` @complexity O(N*log(size() + N)), where N is the number of elements to insert. @liveexample{The example shows how `update()` is used__range.,update} @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update @since version 3.0.0 */ void update(const_iterator first, const_iterator last) { // implicitly convert null value to an empty object if (is_null()) { m_type = value_t::object; m_value.object = create<object_t>(); assert_invariant(); } if (JSON_HEDLEY_UNLIKELY(!is_object())) { JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name()), *this)); } // check if range iterators belong to the same JSON object if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) { JSON_THROW(invalid_iterator::create(210, "iterators do not fit", *this)); } // passed iterators must belong to objects if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object() || !last.m_object->is_object())) { JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects", *this)); } for (auto it = first; it != last; ++it) { m_value.object->operator[](it.key()) = it.value(); } } /*! @brief exchanges the values Exchanges the contents of the JSON value with those of @a other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. @param[in,out] other JSON value to exchange the contents with @complexity Constant. @liveexample{The example below shows how JSON values can be swapped with `swap()`.,swap__reference} @since version 1.0.0 */ void swap(reference other) noexcept ( std::is_nothrow_move_constructible<value_t>::value&& std::is_nothrow_move_assignable<value_t>::value&& std::is_nothrow_move_constructible<json_value>::value&& std::is_nothrow_move_assignable<json_value>::value ) { std::swap(m_type, other.m_type); std::swap(m_value, other.m_value); set_parents(); other.set_parents(); assert_invariant(); } /*! @brief exchanges the values Exchanges the contents of the JSON value from @a left with those of @a right. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. implemented as a friend function callable via ADL. @param[in,out] left JSON value to exchange the contents with @param[in,out] right JSON value to exchange the contents with @complexity Constant. @liveexample{The example below shows how JSON values can be swapped with `swap()`.,swap__reference} @since version 1.0.0 */ friend void swap(reference left, reference right) noexcept ( std::is_nothrow_move_constructible<value_t>::value&& std::is_nothrow_move_assignable<value_t>::value&& std::is_nothrow_move_constructible<json_value>::value&& std::is_nothrow_move_assignable<json_value>::value ) { left.swap(right); } /*! @brief exchanges the values Exchanges the contents of a JSON array with those of @a other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. @param[in,out] other array to exchange the contents with @throw type_error.310 when JSON value is not an array; example: `"cannot use swap() with string"` @complexity Constant. @liveexample{The example below shows how arrays can be swapped with `swap()`.,swap__array_t} @since version 1.0.0 */ void swap(array_t& other) // NOLINT(bugprone-exception-escape) { // swap only works for arrays if (JSON_HEDLEY_LIKELY(is_array())) { std::swap(*(m_value.array), other); } else { JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this)); } } /*! @brief exchanges the values Exchanges the contents of a JSON object with those of @a other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. @param[in,out] other object to exchange the contents with @throw type_error.310 when JSON value is not an object; example: `"cannot use swap() with string"` @complexity Constant. @liveexample{The example below shows how objects can be swapped with `swap()`.,swap__object_t} @since version 1.0.0 */ void swap(object_t& other) // NOLINT(bugprone-exception-escape) { // swap only works for objects if (JSON_HEDLEY_LIKELY(is_object())) { std::swap(*(m_value.object), other); } else { JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this)); } } /*! @brief exchanges the values Exchanges the contents of a JSON string with those of @a other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. @param[in,out] other string to exchange the contents with @throw type_error.310 when JSON value is not a string; example: `"cannot use swap() with boolean"` @complexity Constant. @liveexample{The example below shows how strings can be swapped with `swap()`.,swap__string_t} @since version 1.0.0 */ void swap(string_t& other) // NOLINT(bugprone-exception-escape) { // swap only works for strings if (JSON_HEDLEY_LIKELY(is_string())) { std::swap(*(m_value.string), other); } else { JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this)); } } /*! @brief exchanges the values Exchanges the contents of a JSON string with those of @a other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. @param[in,out] other binary to exchange the contents with @throw type_error.310 when JSON value is not a string; example: `"cannot use swap() with boolean"` @complexity Constant. @liveexample{The example below shows how strings can be swapped with `swap()`.,swap__binary_t} @since version 3.8.0 */ void swap(binary_t& other) // NOLINT(bugprone-exception-escape) { // swap only works for strings if (JSON_HEDLEY_LIKELY(is_binary())) { std::swap(*(m_value.binary), other); } else { JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this)); } } /// @copydoc swap(binary_t&) void swap(typename binary_t::container_type& other) // NOLINT(bugprone-exception-escape) { // swap only works for strings if (JSON_HEDLEY_LIKELY(is_binary())) { std::swap(*(m_value.binary), other); } else { JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this)); } } /// @} public: ////////////////////////////////////////// // lexicographical comparison operators // ////////////////////////////////////////// /// @name lexicographical comparison operators /// @{ /*! @brief comparison: equal Compares two JSON values for equality according to the following rules: - Two JSON values are equal if (1) they are from the same type and (2) their stored values are the same according to their respective `operator==`. - Integer and floating-point numbers are automatically converted before comparison. Note that two NaN values are always treated as unequal. - Two JSON null values are equal. @note Floating-point inside JSON values numbers are compared with `json::number_float_t::operator==` which is `double::operator==` by default. To compare floating-point while respecting an epsilon, an alternative [comparison function](https://github.com/mariokonrad/marnav/blob/master/include/marnav/math/floatingpoint.hpp#L34-#L39) could be used, for instance @code {.cpp} template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type> inline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept { return std::abs(a - b) <= epsilon; } @endcode Or you can self-defined operator equal function like this: @code {.cpp} bool my_equal(const_reference lhs, const_reference rhs) { const auto lhs_type lhs.type(); const auto rhs_type rhs.type(); if (lhs_type == rhs_type) { switch(lhs_type) // self_defined case case value_t::number_float: return std::abs(lhs - rhs) <= std::numeric_limits<float>::epsilon(); // other cases remain the same with the original ... } ... } @endcode @note NaN values never compare equal to themselves or to other NaN values. @param[in] lhs first JSON value to consider @param[in] rhs second JSON value to consider @return whether the values @a lhs and @a rhs are equal @exceptionsafety No-throw guarantee: this function never throws exceptions. @complexity Linear. @liveexample{The example demonstrates comparing several JSON types.,operator__equal} @since version 1.0.0 */ friend bool operator==(const_reference lhs, const_reference rhs) noexcept { const auto lhs_type = lhs.type(); const auto rhs_type = rhs.type(); if (lhs_type == rhs_type) { switch (lhs_type) { case value_t::array: return *lhs.m_value.array == *rhs.m_value.array; case value_t::object: return *lhs.m_value.object == *rhs.m_value.object; case value_t::null: return true; case value_t::string: return *lhs.m_value.string == *rhs.m_value.string; case value_t::boolean: return lhs.m_value.boolean == rhs.m_value.boolean; case value_t::number_integer: return lhs.m_value.number_integer == rhs.m_value.number_integer; case value_t::number_unsigned: return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned; case value_t::number_float: return lhs.m_value.number_float == rhs.m_value.number_float; case value_t::binary: return *lhs.m_value.binary == *rhs.m_value.binary; default: return false; } } else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float) { return static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float; } else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer) { return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer); } else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float) { return static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float; } else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned) { return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned); } else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer) { return static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer; } else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned) { return lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned); } return false; } /*! @brief comparison: equal @copydoc operator==(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator==(const_reference lhs, ScalarType rhs) noexcept { return lhs == basic_json(rhs); } /*! @brief comparison: equal @copydoc operator==(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator==(ScalarType lhs, const_reference rhs) noexcept { return basic_json(lhs) == rhs; } /*! @brief comparison: not equal Compares two JSON values for inequality by calculating `not (lhs == rhs)`. @param[in] lhs first JSON value to consider @param[in] rhs second JSON value to consider @return whether the values @a lhs and @a rhs are not equal @complexity Linear. @exceptionsafety No-throw guarantee: this function never throws exceptions. @liveexample{The example demonstrates comparing several JSON types.,operator__notequal} @since version 1.0.0 */ friend bool operator!=(const_reference lhs, const_reference rhs) noexcept { return !(lhs == rhs); } /*! @brief comparison: not equal @copydoc operator!=(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator!=(const_reference lhs, ScalarType rhs) noexcept { return lhs != basic_json(rhs); } /*! @brief comparison: not equal @copydoc operator!=(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator!=(ScalarType lhs, const_reference rhs) noexcept { return basic_json(lhs) != rhs; } /*! @brief comparison: less than Compares whether one JSON value @a lhs is less than another JSON value @a rhs according to the following rules: - If @a lhs and @a rhs have the same type, the values are compared using the default `<` operator. - Integer and floating-point numbers are automatically converted before comparison - In case @a lhs and @a rhs have different types, the values are ignored and the order of the types is considered, see @ref operator<(const value_t, const value_t). @param[in] lhs first JSON value to consider @param[in] rhs second JSON value to consider @return whether @a lhs is less than @a rhs @complexity Linear. @exceptionsafety No-throw guarantee: this function never throws exceptions. @liveexample{The example demonstrates comparing several JSON types.,operator__less} @since version 1.0.0 */ friend bool operator<(const_reference lhs, const_reference rhs) noexcept { const auto lhs_type = lhs.type(); const auto rhs_type = rhs.type(); if (lhs_type == rhs_type) { switch (lhs_type) { case value_t::array: // note parentheses are necessary, see // https://github.com/nlohmann/json/issues/1530 return (*lhs.m_value.array) < (*rhs.m_value.array); case value_t::object: return (*lhs.m_value.object) < (*rhs.m_value.object); case value_t::null: return false; case value_t::string: return (*lhs.m_value.string) < (*rhs.m_value.string); case value_t::boolean: return (lhs.m_value.boolean) < (rhs.m_value.boolean); case value_t::number_integer: return (lhs.m_value.number_integer) < (rhs.m_value.number_integer); case value_t::number_unsigned: return (lhs.m_value.number_unsigned) < (rhs.m_value.number_unsigned); case value_t::number_float: return (lhs.m_value.number_float) < (rhs.m_value.number_float); case value_t::binary: return (*lhs.m_value.binary) < (*rhs.m_value.binary); default: return false; } } else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float) { return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float; } else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer) { return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer); } else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float) { return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float; } else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned) { return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned); } else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned) { return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned); } else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer) { return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer; } // We only reach this line if we cannot compare values. In that case, // we compare types. Note we have to call the operator explicitly, // because MSVC has problems otherwise. return operator<(lhs_type, rhs_type); } /*! @brief comparison: less than @copydoc operator<(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator<(const_reference lhs, ScalarType rhs) noexcept { return lhs < basic_json(rhs); } /*! @brief comparison: less than @copydoc operator<(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator<(ScalarType lhs, const_reference rhs) noexcept { return basic_json(lhs) < rhs; } /*! @brief comparison: less than or equal Compares whether one JSON value @a lhs is less than or equal to another JSON value by calculating `not (rhs < lhs)`. @param[in] lhs first JSON value to consider @param[in] rhs second JSON value to consider @return whether @a lhs is less than or equal to @a rhs @complexity Linear. @exceptionsafety No-throw guarantee: this function never throws exceptions. @liveexample{The example demonstrates comparing several JSON types.,operator__greater} @since version 1.0.0 */ friend bool operator<=(const_reference lhs, const_reference rhs) noexcept { return !(rhs < lhs); } /*! @brief comparison: less than or equal @copydoc operator<=(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator<=(const_reference lhs, ScalarType rhs) noexcept { return lhs <= basic_json(rhs); } /*! @brief comparison: less than or equal @copydoc operator<=(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator<=(ScalarType lhs, const_reference rhs) noexcept { return basic_json(lhs) <= rhs; } /*! @brief comparison: greater than Compares whether one JSON value @a lhs is greater than another JSON value by calculating `not (lhs <= rhs)`. @param[in] lhs first JSON value to consider @param[in] rhs second JSON value to consider @return whether @a lhs is greater than to @a rhs @complexity Linear. @exceptionsafety No-throw guarantee: this function never throws exceptions. @liveexample{The example demonstrates comparing several JSON types.,operator__lessequal} @since version 1.0.0 */ friend bool operator>(const_reference lhs, const_reference rhs) noexcept { return !(lhs <= rhs); } /*! @brief comparison: greater than @copydoc operator>(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator>(const_reference lhs, ScalarType rhs) noexcept { return lhs > basic_json(rhs); } /*! @brief comparison: greater than @copydoc operator>(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator>(ScalarType lhs, const_reference rhs) noexcept { return basic_json(lhs) > rhs; } /*! @brief comparison: greater than or equal Compares whether one JSON value @a lhs is greater than or equal to another JSON value by calculating `not (lhs < rhs)`. @param[in] lhs first JSON value to consider @param[in] rhs second JSON value to consider @return whether @a lhs is greater than or equal to @a rhs @complexity Linear. @exceptionsafety No-throw guarantee: this function never throws exceptions. @liveexample{The example demonstrates comparing several JSON types.,operator__greaterequal} @since version 1.0.0 */ friend bool operator>=(const_reference lhs, const_reference rhs) noexcept { return !(lhs < rhs); } /*! @brief comparison: greater than or equal @copydoc operator>=(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator>=(const_reference lhs, ScalarType rhs) noexcept { return lhs >= basic_json(rhs); } /*! @brief comparison: greater than or equal @copydoc operator>=(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator>=(ScalarType lhs, const_reference rhs) noexcept { return basic_json(lhs) >= rhs; } /// @} /////////////////// // serialization // /////////////////// /// @name serialization /// @{ #ifndef JSON_NO_IO /*! @brief serialize to stream Serialize the given JSON value @a j to the output stream @a o. The JSON value will be serialized using the @ref dump member function. - The indentation of the output can be controlled with the member variable `width` of the output stream @a o. For instance, using the manipulator `std::setw(4)` on @a o sets the indentation level to `4` and the serialization result is the same as calling `dump(4)`. - The indentation character can be controlled with the member variable `fill` of the output stream @a o. For instance, the manipulator `std::setfill('\\t')` sets indentation to use a tab character rather than the default space character. @param[in,out] o stream to serialize to @param[in] j JSON value to serialize @return the stream @a o @throw type_error.316 if a string stored inside the JSON value is not UTF-8 encoded @complexity Linear. @liveexample{The example below shows the serialization with different parameters to `width` to adjust the indentation level.,operator_serialize} @since version 1.0.0; indentation character added in version 3.0.0 */ friend std::ostream& operator<<(std::ostream& o, const basic_json& j) { // read width member and use it as indentation parameter if nonzero const bool pretty_print = o.width() > 0; const auto indentation = pretty_print ? o.width() : 0; // reset width to 0 for subsequent calls to this stream o.width(0); // do the actual serialization serializer s(detail::output_adapter<char>(o), o.fill()); s.dump(j, pretty_print, false, static_cast<unsigned int>(indentation)); return o; } /*! @brief serialize to stream @deprecated This stream operator is deprecated and will be removed in future 4.0.0 of the library. Please use @ref operator<<(std::ostream&, const basic_json&) instead; that is, replace calls like `j >> o;` with `o << j;`. @since version 1.0.0; deprecated since version 3.0.0 */ JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator<<(std::ostream&, const basic_json&)) friend std::ostream& operator>>(const basic_json& j, std::ostream& o) { return o << j; } #endif // JSON_NO_IO /// @} ///////////////////// // deserialization // ///////////////////// /// @name deserialization /// @{ /*! @brief deserialize from a compatible input @tparam InputType A compatible input, for instance - an std::istream object - a FILE pointer - a C-style array of characters - a pointer to a null-terminated string of single byte characters - an object obj for which begin(obj) and end(obj) produces a valid pair of iterators. @param[in] i input to read from @param[in] cb a parser callback function of type @ref parser_callback_t which is used to control the deserialization by filtering unwanted values (optional) @param[in] allow_exceptions whether to throw exceptions in case of a parse error (optional, true by default) @param[in] ignore_comments whether comments should be ignored and treated like whitespace (true) or yield a parse error (true); (optional, false by default) @return deserialized JSON value; in case of a parse error and @a allow_exceptions set to `false`, the return value will be value_t::discarded. @throw parse_error.101 if a parse error occurs; example: `""unexpected end of input; expected string literal""` @throw parse_error.102 if to_unicode fails or surrogate error @throw parse_error.103 if to_unicode fails @complexity Linear in the length of the input. The parser is a predictive LL(1) parser. The complexity can be higher if the parser callback function @a cb or reading from the input @a i has a super-linear complexity. @note A UTF-8 byte order mark is silently ignored. @liveexample{The example below demonstrates the `parse()` function reading from an array.,parse__array__parser_callback_t} @liveexample{The example below demonstrates the `parse()` function with and without callback function.,parse__string__parser_callback_t} @liveexample{The example below demonstrates the `parse()` function with and without callback function.,parse__istream__parser_callback_t} @liveexample{The example below demonstrates the `parse()` function reading from a contiguous container.,parse__contiguouscontainer__parser_callback_t} @since version 2.0.3 (contiguous containers); version 3.9.0 allowed to ignore comments. */ template<typename InputType> JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json parse(InputType&& i, const parser_callback_t cb = nullptr, const bool allow_exceptions = true, const bool ignore_comments = false) { basic_json result; parser(detail::input_adapter(std::forward<InputType>(i)), cb, allow_exceptions, ignore_comments).parse(true, result); return result; } /*! @brief deserialize from a pair of character iterators The value_type of the iterator must be a integral type with size of 1, 2 or 4 bytes, which will be interpreted respectively as UTF-8, UTF-16 and UTF-32. @param[in] first iterator to start of character range @param[in] last iterator to end of character range @param[in] cb a parser callback function of type @ref parser_callback_t which is used to control the deserialization by filtering unwanted values (optional) @param[in] allow_exceptions whether to throw exceptions in case of a parse error (optional, true by default) @param[in] ignore_comments whether comments should be ignored and treated like whitespace (true) or yield a parse error (true); (optional, false by default) @return deserialized JSON value; in case of a parse error and @a allow_exceptions set to `false`, the return value will be value_t::discarded. @throw parse_error.101 if a parse error occurs; example: `""unexpected end of input; expected string literal""` @throw parse_error.102 if to_unicode fails or surrogate error @throw parse_error.103 if to_unicode fails */ template<typename IteratorType> JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json parse(IteratorType first, IteratorType last, const parser_callback_t cb = nullptr, const bool allow_exceptions = true, const bool ignore_comments = false) { basic_json result; parser(detail::input_adapter(std::move(first), std::move(last)), cb, allow_exceptions, ignore_comments).parse(true, result); return result; } JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DEPRECATED_FOR(3.8.0, parse(ptr, ptr + len)) static basic_json parse(detail::span_input_adapter&& i, const parser_callback_t cb = nullptr, const bool allow_exceptions = true, const bool ignore_comments = false) { basic_json result; parser(i.get(), cb, allow_exceptions, ignore_comments).parse(true, result); return result; } /*! @brief check if the input is valid JSON Unlike the @ref parse(InputType&&, const parser_callback_t,const bool) function, this function neither throws an exception in case of invalid JSON input (i.e., a parse error) nor creates diagnostic information. @tparam InputType A compatible input, for instance - an std::istream object - a FILE pointer - a C-style array of characters - a pointer to a null-terminated string of single byte characters - an object obj for which begin(obj) and end(obj) produces a valid pair of iterators. @param[in] i input to read from @param[in] ignore_comments whether comments should be ignored and treated like whitespace (true) or yield a parse error (true); (optional, false by default) @return Whether the input read from @a i is valid JSON. @complexity Linear in the length of the input. The parser is a predictive LL(1) parser. @note A UTF-8 byte order mark is silently ignored. @liveexample{The example below demonstrates the `accept()` function reading from a string.,accept__string} */ template<typename InputType> static bool accept(InputType&& i, const bool ignore_comments = false) { return parser(detail::input_adapter(std::forward<InputType>(i)), nullptr, false, ignore_comments).accept(true); } template<typename IteratorType> static bool accept(IteratorType first, IteratorType last, const bool ignore_comments = false) { return parser(detail::input_adapter(std::move(first), std::move(last)), nullptr, false, ignore_comments).accept(true); } JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DEPRECATED_FOR(3.8.0, accept(ptr, ptr + len)) static bool accept(detail::span_input_adapter&& i, const bool ignore_comments = false) { return parser(i.get(), nullptr, false, ignore_comments).accept(true); } /*! @brief generate SAX events The SAX event lister must follow the interface of @ref json_sax. This function reads from a compatible input. Examples are: - an std::istream object - a FILE pointer - a C-style array of characters - a pointer to a null-terminated string of single byte characters - an object obj for which begin(obj) and end(obj) produces a valid pair of iterators. @param[in] i input to read from @param[in,out] sax SAX event listener @param[in] format the format to parse (JSON, CBOR, MessagePack, or UBJSON) @param[in] strict whether the input has to be consumed completely @param[in] ignore_comments whether comments should be ignored and treated like whitespace (true) or yield a parse error (true); (optional, false by default); only applies to the JSON file format. @return return value of the last processed SAX event @throw parse_error.101 if a parse error occurs; example: `""unexpected end of input; expected string literal""` @throw parse_error.102 if to_unicode fails or surrogate error @throw parse_error.103 if to_unicode fails @complexity Linear in the length of the input. The parser is a predictive LL(1) parser. The complexity can be higher if the SAX consumer @a sax has a super-linear complexity. @note A UTF-8 byte order mark is silently ignored. @liveexample{The example below demonstrates the `sax_parse()` function reading from string and processing the events with a user-defined SAX event consumer.,sax_parse} @since version 3.2.0 */ template <typename InputType, typename SAX> JSON_HEDLEY_NON_NULL(2) static bool sax_parse(InputType&& i, SAX* sax, input_format_t format = input_format_t::json, const bool strict = true, const bool ignore_comments = false) { auto ia = detail::input_adapter(std::forward<InputType>(i)); return format == input_format_t::json ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict) : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia)).sax_parse(format, sax, strict); } template<class IteratorType, class SAX> JSON_HEDLEY_NON_NULL(3) static bool sax_parse(IteratorType first, IteratorType last, SAX* sax, input_format_t format = input_format_t::json, const bool strict = true, const bool ignore_comments = false) { auto ia = detail::input_adapter(std::move(first), std::move(last)); return format == input_format_t::json ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict) : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia)).sax_parse(format, sax, strict); } template <typename SAX> JSON_HEDLEY_DEPRECATED_FOR(3.8.0, sax_parse(ptr, ptr + len, ...)) JSON_HEDLEY_NON_NULL(2) static bool sax_parse(detail::span_input_adapter&& i, SAX* sax, input_format_t format = input_format_t::json, const bool strict = true, const bool ignore_comments = false) { auto ia = i.get(); return format == input_format_t::json // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict) // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia)).sax_parse(format, sax, strict); } #ifndef JSON_NO_IO /*! @brief deserialize from stream @deprecated This stream operator is deprecated and will be removed in version 4.0.0 of the library. Please use @ref operator>>(std::istream&, basic_json&) instead; that is, replace calls like `j << i;` with `i >> j;`. @since version 1.0.0; deprecated since version 3.0.0 */ JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator>>(std::istream&, basic_json&)) friend std::istream& operator<<(basic_json& j, std::istream& i) { return operator>>(i, j); } /*! @brief deserialize from stream Deserializes an input stream to a JSON value. @param[in,out] i input stream to read a serialized JSON value from @param[in,out] j JSON value to write the deserialized input to @throw parse_error.101 in case of an unexpected token @throw parse_error.102 if to_unicode fails or surrogate error @throw parse_error.103 if to_unicode fails @complexity Linear in the length of the input. The parser is a predictive LL(1) parser. @note A UTF-8 byte order mark is silently ignored. @liveexample{The example below shows how a JSON value is constructed by reading a serialization from a stream.,operator_deserialize} @sa parse(std::istream&, const parser_callback_t) for a variant with a parser callback function to filter values while parsing @since version 1.0.0 */ friend std::istream& operator>>(std::istream& i, basic_json& j) { parser(detail::input_adapter(i)).parse(false, j); return i; } #endif // JSON_NO_IO /// @} /////////////////////////// // convenience functions // /////////////////////////// /*! @brief return the type as string Returns the type name as string to be used in error messages - usually to indicate that a function was called on a wrong JSON type. @return a string representation of a the @a m_type member: Value type | return value ----------- | ------------- null | `"null"` boolean | `"boolean"` string | `"string"` number | `"number"` (for all number types) object | `"object"` array | `"array"` binary | `"binary"` discarded | `"discarded"` @exceptionsafety No-throw guarantee: this function never throws exceptions. @complexity Constant. @liveexample{The following code exemplifies `type_name()` for all JSON types.,type_name} @sa see @ref type() -- return the type of the JSON value @sa see @ref operator value_t() -- return the type of the JSON value (implicit) @since version 1.0.0, public since 2.1.0, `const char*` and `noexcept` since 3.0.0 */ JSON_HEDLEY_RETURNS_NON_NULL const char* type_name() const noexcept { { switch (m_type) { case value_t::null: return "null"; case value_t::object: return "object"; case value_t::array: return "array"; case value_t::string: return "string"; case value_t::boolean: return "boolean"; case value_t::binary: return "binary"; case value_t::discarded: return "discarded"; default: return "number"; } } } JSON_PRIVATE_UNLESS_TESTED: ////////////////////// // member variables // ////////////////////// /// the type of the current element value_t m_type = value_t::null; /// the value of the current element json_value m_value = {}; #if JSON_DIAGNOSTICS /// a pointer to a parent value (for debugging purposes) basic_json* m_parent = nullptr; #endif ////////////////////////////////////////// // binary serialization/deserialization // ////////////////////////////////////////// /// @name binary serialization/deserialization support /// @{ public: /*! @brief create a CBOR serialization of a given JSON value Serializes a given JSON value @a j to a byte vector using the CBOR (Concise Binary Object Representation) serialization format. CBOR is a binary serialization format which aims to be more compact than JSON itself, yet more efficient to parse. The library uses the following mapping from JSON values types to CBOR types according to the CBOR specification (RFC 7049): JSON value type | value/range | CBOR type | first byte --------------- | ------------------------------------------ | ---------------------------------- | --------------- null | `null` | Null | 0xF6 boolean | `true` | True | 0xF5 boolean | `false` | False | 0xF4 number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3B number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3A number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39 number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38 number_integer | -24..-1 | Negative integer | 0x20..0x37 number_integer | 0..23 | Integer | 0x00..0x17 number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18 number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19 number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B number_unsigned | 0..23 | Integer | 0x00..0x17 number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18 number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19 number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B number_float | *any value representable by a float* | Single-Precision Float | 0xFA number_float | *any value NOT representable by a float* | Double-Precision Float | 0xFB string | *length*: 0..23 | UTF-8 string | 0x60..0x77 string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78 string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79 string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7A string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7B array | *size*: 0..23 | array | 0x80..0x97 array | *size*: 23..255 | array (1 byte follow) | 0x98 array | *size*: 256..65535 | array (2 bytes follow) | 0x99 array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9A array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9B object | *size*: 0..23 | map | 0xA0..0xB7 object | *size*: 23..255 | map (1 byte follow) | 0xB8 object | *size*: 256..65535 | map (2 bytes follow) | 0xB9 object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xBA object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xBB binary | *size*: 0..23 | byte string | 0x40..0x57 binary | *size*: 23..255 | byte string (1 byte follow) | 0x58 binary | *size*: 256..65535 | byte string (2 bytes follow) | 0x59 binary | *size*: 65536..4294967295 | byte string (4 bytes follow) | 0x5A binary | *size*: 4294967296..18446744073709551615 | byte string (8 bytes follow) | 0x5B @note The mapping is **complete** in the sense that any JSON value type can be converted to a CBOR value. @note If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the @ref dump() function which serializes NaN or Infinity to `null`. @note The following CBOR types are not used in the conversion: - UTF-8 strings terminated by "break" (0x7F) - arrays terminated by "break" (0x9F) - maps terminated by "break" (0xBF) - byte strings terminated by "break" (0x5F) - date/time (0xC0..0xC1) - bignum (0xC2..0xC3) - decimal fraction (0xC4) - bigfloat (0xC5) - expected conversions (0xD5..0xD7) - simple values (0xE0..0xF3, 0xF8) - undefined (0xF7) - half-precision floats (0xF9) - break (0xFF) @param[in] j JSON value to serialize @return CBOR serialization as byte vector @complexity Linear in the size of the JSON value @a j. @liveexample{The example shows the serialization of a JSON value to a byte vector in CBOR format.,to_cbor} @sa http://cbor.io @sa see @ref from_cbor(InputType&&, const bool, const bool, const cbor_tag_handler_t) for the analogous deserialization @sa see @ref to_msgpack(const basic_json&) for the related MessagePack format @sa see @ref to_ubjson(const basic_json&, const bool, const bool) for the related UBJSON format @since version 2.0.9; compact representation of floating-point numbers since version 3.8.0 */ static std::vector<uint8_t> to_cbor(const basic_json& j) { std::vector<uint8_t> result; to_cbor(j, result); return result; } static void to_cbor(const basic_json& j, detail::output_adapter<uint8_t> o) { binary_writer<uint8_t>(o).write_cbor(j); } static void to_cbor(const basic_json& j, detail::output_adapter<char> o) { binary_writer<char>(o).write_cbor(j); } /*! @brief create a MessagePack serialization of a given JSON value Serializes a given JSON value @a j to a byte vector using the MessagePack serialization format. MessagePack is a binary serialization format which aims to be more compact than JSON itself, yet more efficient to parse. The library uses the following mapping from JSON values types to MessagePack types according to the MessagePack specification: JSON value type | value/range | MessagePack type | first byte --------------- | --------------------------------- | ---------------- | ---------- null | `null` | nil | 0xC0 boolean | `true` | true | 0xC3 boolean | `false` | false | 0xC2 number_integer | -9223372036854775808..-2147483649 | int64 | 0xD3 number_integer | -2147483648..-32769 | int32 | 0xD2 number_integer | -32768..-129 | int16 | 0xD1 number_integer | -128..-33 | int8 | 0xD0 number_integer | -32..-1 | negative fixint | 0xE0..0xFF number_integer | 0..127 | positive fixint | 0x00..0x7F number_integer | 128..255 | uint 8 | 0xCC number_integer | 256..65535 | uint 16 | 0xCD number_integer | 65536..4294967295 | uint 32 | 0xCE number_integer | 4294967296..18446744073709551615 | uint 64 | 0xCF number_unsigned | 0..127 | positive fixint | 0x00..0x7F number_unsigned | 128..255 | uint 8 | 0xCC number_unsigned | 256..65535 | uint 16 | 0xCD number_unsigned | 65536..4294967295 | uint 32 | 0xCE number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xCF number_float | *any value representable by a float* | float 32 | 0xCA number_float | *any value NOT representable by a float* | float 64 | 0xCB string | *length*: 0..31 | fixstr | 0xA0..0xBF string | *length*: 32..255 | str 8 | 0xD9 string | *length*: 256..65535 | str 16 | 0xDA string | *length*: 65536..4294967295 | str 32 | 0xDB array | *size*: 0..15 | fixarray | 0x90..0x9F array | *size*: 16..65535 | array 16 | 0xDC array | *size*: 65536..4294967295 | array 32 | 0xDD object | *size*: 0..15 | fix map | 0x80..0x8F object | *size*: 16..65535 | map 16 | 0xDE object | *size*: 65536..4294967295 | map 32 | 0xDF binary | *size*: 0..255 | bin 8 | 0xC4 binary | *size*: 256..65535 | bin 16 | 0xC5 binary | *size*: 65536..4294967295 | bin 32 | 0xC6 @note The mapping is **complete** in the sense that any JSON value type can be converted to a MessagePack value. @note The following values can **not** be converted to a MessagePack value: - strings with more than 4294967295 bytes - byte strings with more than 4294967295 bytes - arrays with more than 4294967295 elements - objects with more than 4294967295 elements @note Any MessagePack output created @ref to_msgpack can be successfully parsed by @ref from_msgpack. @note If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the @ref dump() function which serializes NaN or Infinity to `null`. @param[in] j JSON value to serialize @return MessagePack serialization as byte vector @complexity Linear in the size of the JSON value @a j. @liveexample{The example shows the serialization of a JSON value to a byte vector in MessagePack format.,to_msgpack} @sa http://msgpack.org @sa see @ref from_msgpack for the analogous deserialization @sa see @ref to_cbor(const basic_json& for the related CBOR format @sa see @ref to_ubjson(const basic_json&, const bool, const bool) for the related UBJSON format @since version 2.0.9 */ static std::vector<uint8_t> to_msgpack(const basic_json& j) { std::vector<uint8_t> result; to_msgpack(j, result); return result; } static void to_msgpack(const basic_json& j, detail::output_adapter<uint8_t> o) { binary_writer<uint8_t>(o).write_msgpack(j); } static void to_msgpack(const basic_json& j, detail::output_adapter<char> o) { binary_writer<char>(o).write_msgpack(j); } /*! @brief create a UBJSON serialization of a given JSON value Serializes a given JSON value @a j to a byte vector using the UBJSON (Universal Binary JSON) serialization format. UBJSON aims to be more compact than JSON itself, yet more efficient to parse. The library uses the following mapping from JSON values types to UBJSON types according to the UBJSON specification: JSON value type | value/range | UBJSON type | marker --------------- | --------------------------------- | ----------- | ------ null | `null` | null | `Z` boolean | `true` | true | `T` boolean | `false` | false | `F` number_integer | -9223372036854775808..-2147483649 | int64 | `L` number_integer | -2147483648..-32769 | int32 | `l` number_integer | -32768..-129 | int16 | `I` number_integer | -128..127 | int8 | `i` number_integer | 128..255 | uint8 | `U` number_integer | 256..32767 | int16 | `I` number_integer | 32768..2147483647 | int32 | `l` number_integer | 2147483648..9223372036854775807 | int64 | `L` number_unsigned | 0..127 | int8 | `i` number_unsigned | 128..255 | uint8 | `U` number_unsigned | 256..32767 | int16 | `I` number_unsigned | 32768..2147483647 | int32 | `l` number_unsigned | 2147483648..9223372036854775807 | int64 | `L` number_unsigned | 2147483649..18446744073709551615 | high-precision | `H` number_float | *any value* | float64 | `D` string | *with shortest length indicator* | string | `S` array | *see notes on optimized format* | array | `[` object | *see notes on optimized format* | map | `{` @note The mapping is **complete** in the sense that any JSON value type can be converted to a UBJSON value. @note The following values can **not** be converted to a UBJSON value: - strings with more than 9223372036854775807 bytes (theoretical) @note The following markers are not used in the conversion: - `Z`: no-op values are not created. - `C`: single-byte strings are serialized with `S` markers. @note Any UBJSON output created @ref to_ubjson can be successfully parsed by @ref from_ubjson. @note If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the @ref dump() function which serializes NaN or Infinity to `null`. @note The optimized formats for containers are supported: Parameter @a use_size adds size information to the beginning of a container and removes the closing marker. Parameter @a use_type further checks whether all elements of a container have the same type and adds the type marker to the beginning of the container. The @a use_type parameter must only be used together with @a use_size = true. Note that @a use_size = true alone may result in larger representations - the benefit of this parameter is that the receiving side is immediately informed on the number of elements of the container. @note If the JSON data contains the binary type, the value stored is a list of integers, as suggested by the UBJSON documentation. In particular, this means that serialization and the deserialization of a JSON containing binary values into UBJSON and back will result in a different JSON object. @param[in] j JSON value to serialize @param[in] use_size whether to add size annotations to container types @param[in] use_type whether to add type annotations to container types (must be combined with @a use_size = true) @return UBJSON serialization as byte vector @complexity Linear in the size of the JSON value @a j. @liveexample{The example shows the serialization of a JSON value to a byte vector in UBJSON format.,to_ubjson} @sa http://ubjson.org @sa see @ref from_ubjson(InputType&&, const bool, const bool) for the analogous deserialization @sa see @ref to_cbor(const basic_json& for the related CBOR format @sa see @ref to_msgpack(const basic_json&) for the related MessagePack format @since version 3.1.0 */ static std::vector<uint8_t> to_ubjson(const basic_json& j, const bool use_size = false, const bool use_type = false) { std::vector<uint8_t> result; to_ubjson(j, result, use_size, use_type); return result; } static void to_ubjson(const basic_json& j, detail::output_adapter<uint8_t> o, const bool use_size = false, const bool use_type = false) { binary_writer<uint8_t>(o).write_ubjson(j, use_size, use_type); } static void to_ubjson(const basic_json& j, detail::output_adapter<char> o, const bool use_size = false, const bool use_type = false) { binary_writer<char>(o).write_ubjson(j, use_size, use_type); } /*! @brief Serializes the given JSON object `j` to BSON and returns a vector containing the corresponding BSON-representation. BSON (Binary JSON) is a binary format in which zero or more ordered key/value pairs are stored as a single entity (a so-called document). The library uses the following mapping from JSON values types to BSON types: JSON value type | value/range | BSON type | marker --------------- | --------------------------------- | ----------- | ------ null | `null` | null | 0x0A boolean | `true`, `false` | boolean | 0x08 number_integer | -9223372036854775808..-2147483649 | int64 | 0x12 number_integer | -2147483648..2147483647 | int32 | 0x10 number_integer | 2147483648..9223372036854775807 | int64 | 0x12 number_unsigned | 0..2147483647 | int32 | 0x10 number_unsigned | 2147483648..9223372036854775807 | int64 | 0x12 number_unsigned | 9223372036854775808..18446744073709551615| -- | -- number_float | *any value* | double | 0x01 string | *any value* | string | 0x02 array | *any value* | document | 0x04 object | *any value* | document | 0x03 binary | *any value* | binary | 0x05 @warning The mapping is **incomplete**, since only JSON-objects (and things contained therein) can be serialized to BSON. Also, integers larger than 9223372036854775807 cannot be serialized to BSON, and the keys may not contain U+0000, since they are serialized a zero-terminated c-strings. @throw out_of_range.407 if `j.is_number_unsigned() && j.get<std::uint64_t>() > 9223372036854775807` @throw out_of_range.409 if a key in `j` contains a NULL (U+0000) @throw type_error.317 if `!j.is_object()` @pre The input `j` is required to be an object: `j.is_object() == true`. @note Any BSON output created via @ref to_bson can be successfully parsed by @ref from_bson. @param[in] j JSON value to serialize @return BSON serialization as byte vector @complexity Linear in the size of the JSON value @a j. @liveexample{The example shows the serialization of a JSON value to a byte vector in BSON format.,to_bson} @sa http://bsonspec.org/spec.html @sa see @ref from_bson(detail::input_adapter&&, const bool strict) for the analogous deserialization @sa see @ref to_ubjson(const basic_json&, const bool, const bool) for the related UBJSON format @sa see @ref to_cbor(const basic_json&) for the related CBOR format @sa see @ref to_msgpack(const basic_json&) for the related MessagePack format */ static std::vector<uint8_t> to_bson(const basic_json& j) { std::vector<uint8_t> result; to_bson(j, result); return result; } /*! @brief Serializes the given JSON object `j` to BSON and forwards the corresponding BSON-representation to the given output_adapter `o`. @param j The JSON object to convert to BSON. @param o The output adapter that receives the binary BSON representation. @pre The input `j` shall be an object: `j.is_object() == true` @sa see @ref to_bson(const basic_json&) */ static void to_bson(const basic_json& j, detail::output_adapter<uint8_t> o) { binary_writer<uint8_t>(o).write_bson(j); } /*! @copydoc to_bson(const basic_json&, detail::output_adapter<uint8_t>) */ static void to_bson(const basic_json& j, detail::output_adapter<char> o) { binary_writer<char>(o).write_bson(j); } /*! @brief create a JSON value from an input in CBOR format Deserializes a given input @a i to a JSON value using the CBOR (Concise Binary Object Representation) serialization format. The library maps CBOR types to JSON value types as follows: CBOR type | JSON value type | first byte ---------------------- | --------------- | ---------- Integer | number_unsigned | 0x00..0x17 Unsigned integer | number_unsigned | 0x18 Unsigned integer | number_unsigned | 0x19 Unsigned integer | number_unsigned | 0x1A Unsigned integer | number_unsigned | 0x1B Negative integer | number_integer | 0x20..0x37 Negative integer | number_integer | 0x38 Negative integer | number_integer | 0x39 Negative integer | number_integer | 0x3A Negative integer | number_integer | 0x3B Byte string | binary | 0x40..0x57 Byte string | binary | 0x58 Byte string | binary | 0x59 Byte string | binary | 0x5A Byte string | binary | 0x5B UTF-8 string | string | 0x60..0x77 UTF-8 string | string | 0x78 UTF-8 string | string | 0x79 UTF-8 string | string | 0x7A UTF-8 string | string | 0x7B UTF-8 string | string | 0x7F array | array | 0x80..0x97 array | array | 0x98 array | array | 0x99 array | array | 0x9A array | array | 0x9B array | array | 0x9F map | object | 0xA0..0xB7 map | object | 0xB8 map | object | 0xB9 map | object | 0xBA map | object | 0xBB map | object | 0xBF False | `false` | 0xF4 True | `true` | 0xF5 Null | `null` | 0xF6 Half-Precision Float | number_float | 0xF9 Single-Precision Float | number_float | 0xFA Double-Precision Float | number_float | 0xFB @warning The mapping is **incomplete** in the sense that not all CBOR types can be converted to a JSON value. The following CBOR types are not supported and will yield parse errors (parse_error.112): - date/time (0xC0..0xC1) - bignum (0xC2..0xC3) - decimal fraction (0xC4) - bigfloat (0xC5) - expected conversions (0xD5..0xD7) - simple values (0xE0..0xF3, 0xF8) - undefined (0xF7) @warning CBOR allows map keys of any type, whereas JSON only allows strings as keys in object values. Therefore, CBOR maps with keys other than UTF-8 strings are rejected (parse_error.113). @note Any CBOR output created @ref to_cbor can be successfully parsed by @ref from_cbor. @param[in] i an input in CBOR format convertible to an input adapter @param[in] strict whether to expect the input to be consumed until EOF (true by default) @param[in] allow_exceptions whether to throw exceptions in case of a parse error (optional, true by default) @param[in] tag_handler how to treat CBOR tags (optional, error by default) @return deserialized JSON value; in case of a parse error and @a allow_exceptions set to `false`, the return value will be value_t::discarded. @throw parse_error.110 if the given input ends prematurely or the end of file was not reached when @a strict was set to true @throw parse_error.112 if unsupported features from CBOR were used in the given input @a v or if the input is not valid CBOR @throw parse_error.113 if a string was expected as map key, but not found @complexity Linear in the size of the input @a i. @liveexample{The example shows the deserialization of a byte vector in CBOR format to a JSON value.,from_cbor} @sa http://cbor.io @sa see @ref to_cbor(const basic_json&) for the analogous serialization @sa see @ref from_msgpack(InputType&&, const bool, const bool) for the related MessagePack format @sa see @ref from_ubjson(InputType&&, const bool, const bool) for the related UBJSON format @since version 2.0.9; parameter @a start_index since 2.1.1; changed to consume input adapters, removed start_index parameter, and added @a strict parameter since 3.0.0; added @a allow_exceptions parameter since 3.2.0; added @a tag_handler parameter since 3.9.0. */ template<typename InputType> JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json from_cbor(InputType&& i, const bool strict = true, const bool allow_exceptions = true, const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) { basic_json result; detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions); auto ia = detail::input_adapter(std::forward<InputType>(i)); const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler); return res ? result : basic_json(value_t::discarded); } /*! @copydoc from_cbor(InputType&&, const bool, const bool, const cbor_tag_handler_t) */ template<typename IteratorType> JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json from_cbor(IteratorType first, IteratorType last, const bool strict = true, const bool allow_exceptions = true, const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) { basic_json result; detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions); auto ia = detail::input_adapter(std::move(first), std::move(last)); const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler); return res ? result : basic_json(value_t::discarded); } template<typename T> JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len)) static basic_json from_cbor(const T* ptr, std::size_t len, const bool strict = true, const bool allow_exceptions = true, const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) { return from_cbor(ptr, ptr + len, strict, allow_exceptions, tag_handler); } JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len)) static basic_json from_cbor(detail::span_input_adapter&& i, const bool strict = true, const bool allow_exceptions = true, const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) { basic_json result; detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions); auto ia = i.get(); // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler); return res ? result : basic_json(value_t::discarded); } /*! @brief create a JSON value from an input in MessagePack format Deserializes a given input @a i to a JSON value using the MessagePack serialization format. The library maps MessagePack types to JSON value types as follows: MessagePack type | JSON value type | first byte ---------------- | --------------- | ---------- positive fixint | number_unsigned | 0x00..0x7F fixmap | object | 0x80..0x8F fixarray | array | 0x90..0x9F fixstr | string | 0xA0..0xBF nil | `null` | 0xC0 false | `false` | 0xC2 true | `true` | 0xC3 float 32 | number_float | 0xCA float 64 | number_float | 0xCB uint 8 | number_unsigned | 0xCC uint 16 | number_unsigned | 0xCD uint 32 | number_unsigned | 0xCE uint 64 | number_unsigned | 0xCF int 8 | number_integer | 0xD0 int 16 | number_integer | 0xD1 int 32 | number_integer | 0xD2 int 64 | number_integer | 0xD3 str 8 | string | 0xD9 str 16 | string | 0xDA str 32 | string | 0xDB array 16 | array | 0xDC array 32 | array | 0xDD map 16 | object | 0xDE map 32 | object | 0xDF bin 8 | binary | 0xC4 bin 16 | binary | 0xC5 bin 32 | binary | 0xC6 ext 8 | binary | 0xC7 ext 16 | binary | 0xC8 ext 32 | binary | 0xC9 fixext 1 | binary | 0xD4 fixext 2 | binary | 0xD5 fixext 4 | binary | 0xD6 fixext 8 | binary | 0xD7 fixext 16 | binary | 0xD8 negative fixint | number_integer | 0xE0-0xFF @note Any MessagePack output created @ref to_msgpack can be successfully parsed by @ref from_msgpack. @param[in] i an input in MessagePack format convertible to an input adapter @param[in] strict whether to expect the input to be consumed until EOF (true by default) @param[in] allow_exceptions whether to throw exceptions in case of a parse error (optional, true by default) @return deserialized JSON value; in case of a parse error and @a allow_exceptions set to `false`, the return value will be value_t::discarded. @throw parse_error.110 if the given input ends prematurely or the end of file was not reached when @a strict was set to true @throw parse_error.112 if unsupported features from MessagePack were used in the given input @a i or if the input is not valid MessagePack @throw parse_error.113 if a string was expected as map key, but not found @complexity Linear in the size of the input @a i. @liveexample{The example shows the deserialization of a byte vector in MessagePack format to a JSON value.,from_msgpack} @sa http://msgpack.org @sa see @ref to_msgpack(const basic_json&) for the analogous serialization @sa see @ref from_cbor(InputType&&, const bool, const bool, const cbor_tag_handler_t) for the related CBOR format @sa see @ref from_ubjson(InputType&&, const bool, const bool) for the related UBJSON format @sa see @ref from_bson(InputType&&, const bool, const bool) for the related BSON format @since version 2.0.9; parameter @a start_index since 2.1.1; changed to consume input adapters, removed start_index parameter, and added @a strict parameter since 3.0.0; added @a allow_exceptions parameter since 3.2.0 */ template<typename InputType> JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json from_msgpack(InputType&& i, const bool strict = true, const bool allow_exceptions = true) { basic_json result; detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions); auto ia = detail::input_adapter(std::forward<InputType>(i)); const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict); return res ? result : basic_json(value_t::discarded); } /*! @copydoc from_msgpack(InputType&&, const bool, const bool) */ template<typename IteratorType> JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json from_msgpack(IteratorType first, IteratorType last, const bool strict = true, const bool allow_exceptions = true) { basic_json result; detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions); auto ia = detail::input_adapter(std::move(first), std::move(last)); const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict); return res ? result : basic_json(value_t::discarded); } template<typename T> JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len)) static basic_json from_msgpack(const T* ptr, std::size_t len, const bool strict = true, const bool allow_exceptions = true) { return from_msgpack(ptr, ptr + len, strict, allow_exceptions); } JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len)) static basic_json from_msgpack(detail::span_input_adapter&& i, const bool strict = true, const bool allow_exceptions = true) { basic_json result; detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions); auto ia = i.get(); // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict); return res ? result : basic_json(value_t::discarded); } /*! @brief create a JSON value from an input in UBJSON format Deserializes a given input @a i to a JSON value using the UBJSON (Universal Binary JSON) serialization format. The library maps UBJSON types to JSON value types as follows: UBJSON type | JSON value type | marker ----------- | --------------------------------------- | ------ no-op | *no value, next value is read* | `N` null | `null` | `Z` false | `false` | `F` true | `true` | `T` float32 | number_float | `d` float64 | number_float | `D` uint8 | number_unsigned | `U` int8 | number_integer | `i` int16 | number_integer | `I` int32 | number_integer | `l` int64 | number_integer | `L` high-precision number | number_integer, number_unsigned, or number_float - depends on number string | 'H' string | string | `S` char | string | `C` array | array (optimized values are supported) | `[` object | object (optimized values are supported) | `{` @note The mapping is **complete** in the sense that any UBJSON value can be converted to a JSON value. @param[in] i an input in UBJSON format convertible to an input adapter @param[in] strict whether to expect the input to be consumed until EOF (true by default) @param[in] allow_exceptions whether to throw exceptions in case of a parse error (optional, true by default) @return deserialized JSON value; in case of a parse error and @a allow_exceptions set to `false`, the return value will be value_t::discarded. @throw parse_error.110 if the given input ends prematurely or the end of file was not reached when @a strict was set to true @throw parse_error.112 if a parse error occurs @throw parse_error.113 if a string could not be parsed successfully @complexity Linear in the size of the input @a i. @liveexample{The example shows the deserialization of a byte vector in UBJSON format to a JSON value.,from_ubjson} @sa http://ubjson.org @sa see @ref to_ubjson(const basic_json&, const bool, const bool) for the analogous serialization @sa see @ref from_cbor(InputType&&, const bool, const bool, const cbor_tag_handler_t) for the related CBOR format @sa see @ref from_msgpack(InputType&&, const bool, const bool) for the related MessagePack format @sa see @ref from_bson(InputType&&, const bool, const bool) for the related BSON format @since version 3.1.0; added @a allow_exceptions parameter since 3.2.0 */ template<typename InputType> JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json from_ubjson(InputType&& i, const bool strict = true, const bool allow_exceptions = true) { basic_json result; detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions); auto ia = detail::input_adapter(std::forward<InputType>(i)); const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict); return res ? result : basic_json(value_t::discarded); } /*! @copydoc from_ubjson(InputType&&, const bool, const bool) */ template<typename IteratorType> JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json from_ubjson(IteratorType first, IteratorType last, const bool strict = true, const bool allow_exceptions = true) { basic_json result; detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions); auto ia = detail::input_adapter(std::move(first), std::move(last)); const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict); return res ? result : basic_json(value_t::discarded); } template<typename T> JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len)) static basic_json from_ubjson(const T* ptr, std::size_t len, const bool strict = true, const bool allow_exceptions = true) { return from_ubjson(ptr, ptr + len, strict, allow_exceptions); } JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len)) static basic_json from_ubjson(detail::span_input_adapter&& i, const bool strict = true, const bool allow_exceptions = true) { basic_json result; detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions); auto ia = i.get(); // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict); return res ? result : basic_json(value_t::discarded); } /*! @brief Create a JSON value from an input in BSON format Deserializes a given input @a i to a JSON value using the BSON (Binary JSON) serialization format. The library maps BSON record types to JSON value types as follows: BSON type | BSON marker byte | JSON value type --------------- | ---------------- | --------------------------- double | 0x01 | number_float string | 0x02 | string document | 0x03 | object array | 0x04 | array binary | 0x05 | binary undefined | 0x06 | still unsupported ObjectId | 0x07 | still unsupported boolean | 0x08 | boolean UTC Date-Time | 0x09 | still unsupported null | 0x0A | null Regular Expr. | 0x0B | still unsupported DB Pointer | 0x0C | still unsupported JavaScript Code | 0x0D | still unsupported Symbol | 0x0E | still unsupported JavaScript Code | 0x0F | still unsupported int32 | 0x10 | number_integer Timestamp | 0x11 | still unsupported 128-bit decimal float | 0x13 | still unsupported Max Key | 0x7F | still unsupported Min Key | 0xFF | still unsupported @warning The mapping is **incomplete**. The unsupported mappings are indicated in the table above. @param[in] i an input in BSON format convertible to an input adapter @param[in] strict whether to expect the input to be consumed until EOF (true by default) @param[in] allow_exceptions whether to throw exceptions in case of a parse error (optional, true by default) @return deserialized JSON value; in case of a parse error and @a allow_exceptions set to `false`, the return value will be value_t::discarded. @throw parse_error.114 if an unsupported BSON record type is encountered @complexity Linear in the size of the input @a i. @liveexample{The example shows the deserialization of a byte vector in BSON format to a JSON value.,from_bson} @sa http://bsonspec.org/spec.html @sa see @ref to_bson(const basic_json&) for the analogous serialization @sa see @ref from_cbor(InputType&&, const bool, const bool, const cbor_tag_handler_t) for the related CBOR format @sa see @ref from_msgpack(InputType&&, const bool, const bool) for the related MessagePack format @sa see @ref from_ubjson(InputType&&, const bool, const bool) for the related UBJSON format */ template<typename InputType> JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json from_bson(InputType&& i, const bool strict = true, const bool allow_exceptions = true) { basic_json result; detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions); auto ia = detail::input_adapter(std::forward<InputType>(i)); const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict); return res ? result : basic_json(value_t::discarded); } /*! @copydoc from_bson(InputType&&, const bool, const bool) */ template<typename IteratorType> JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json from_bson(IteratorType first, IteratorType last, const bool strict = true, const bool allow_exceptions = true) { basic_json result; detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions); auto ia = detail::input_adapter(std::move(first), std::move(last)); const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict); return res ? result : basic_json(value_t::discarded); } template<typename T> JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len)) static basic_json from_bson(const T* ptr, std::size_t len, const bool strict = true, const bool allow_exceptions = true) { return from_bson(ptr, ptr + len, strict, allow_exceptions); } JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len)) static basic_json from_bson(detail::span_input_adapter&& i, const bool strict = true, const bool allow_exceptions = true) { basic_json result; detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions); auto ia = i.get(); // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict); return res ? result : basic_json(value_t::discarded); } /// @} ////////////////////////// // JSON Pointer support // ////////////////////////// /// @name JSON Pointer functions /// @{ /*! @brief access specified element via JSON Pointer Uses a JSON pointer to retrieve a reference to the respective JSON value. No bound checking is performed. Similar to @ref operator[](const typename object_t::key_type&), `null` values are created in arrays and objects if necessary. In particular: - If the JSON pointer points to an object key that does not exist, it is created an filled with a `null` value before a reference to it is returned. - If the JSON pointer points to an array index that does not exist, it is created an filled with a `null` value before a reference to it is returned. All indices between the current maximum and the given index are also filled with `null`. - The special value `-` is treated as a synonym for the index past the end. @param[in] ptr a JSON pointer @return reference to the element pointed to by @a ptr @complexity Constant. @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.404 if the JSON pointer can not be resolved @liveexample{The behavior is shown in the example.,operatorjson_pointer} @since version 2.0.0 */ reference operator[](const json_pointer& ptr) { return ptr.get_unchecked(this); } /*! @brief access specified element via JSON Pointer Uses a JSON pointer to retrieve a reference to the respective JSON value. No bound checking is performed. The function does not change the JSON value; no `null` values are created. In particular, the special value `-` yields an exception. @param[in] ptr JSON pointer to the desired element @return const reference to the element pointed to by @a ptr @complexity Constant. @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.402 if the array index '-' is used @throw out_of_range.404 if the JSON pointer can not be resolved @liveexample{The behavior is shown in the example.,operatorjson_pointer_const} @since version 2.0.0 */ const_reference operator[](const json_pointer& ptr) const { return ptr.get_unchecked(this); } /*! @brief access specified element via JSON Pointer Returns a reference to the element at with specified JSON pointer @a ptr, with bounds checking. @param[in] ptr JSON pointer to the desired element @return reference to the element pointed to by @a ptr @throw parse_error.106 if an array index in the passed JSON pointer @a ptr begins with '0'. See example below. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr is not a number. See example below. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr is out of range. See example below. @throw out_of_range.402 if the array index '-' is used in the passed JSON pointer @a ptr. As `at` provides checked access (and no elements are implicitly inserted), the index '-' is always invalid. See example below. @throw out_of_range.403 if the JSON pointer describes a key of an object which cannot be found. See example below. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved. See example below. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @complexity Constant. @since version 2.0.0 @liveexample{The behavior is shown in the example.,at_json_pointer} */ reference at(const json_pointer& ptr) { return ptr.get_checked(this); } /*! @brief access specified element via JSON Pointer Returns a const reference to the element at with specified JSON pointer @a ptr, with bounds checking. @param[in] ptr JSON pointer to the desired element @return reference to the element pointed to by @a ptr @throw parse_error.106 if an array index in the passed JSON pointer @a ptr begins with '0'. See example below. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr is not a number. See example below. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr is out of range. See example below. @throw out_of_range.402 if the array index '-' is used in the passed JSON pointer @a ptr. As `at` provides checked access (and no elements are implicitly inserted), the index '-' is always invalid. See example below. @throw out_of_range.403 if the JSON pointer describes a key of an object which cannot be found. See example below. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved. See example below. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @complexity Constant. @since version 2.0.0 @liveexample{The behavior is shown in the example.,at_json_pointer_const} */ const_reference at(const json_pointer& ptr) const { return ptr.get_checked(this); } /*! @brief return flattened JSON value The function creates a JSON object whose keys are JSON pointers (see [RFC 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all primitive. The original JSON value can be restored using the @ref unflatten() function. @return an object that maps JSON pointers to primitive values @note Empty objects and arrays are flattened to `null` and will not be reconstructed correctly by the @ref unflatten() function. @complexity Linear in the size the JSON value. @liveexample{The following code shows how a JSON object is flattened to an object whose keys consist of JSON pointers.,flatten} @sa see @ref unflatten() for the reverse function @since version 2.0.0 */ basic_json flatten() const { basic_json result(value_t::object); json_pointer::flatten("", *this, result); return result; } /*! @brief unflatten a previously flattened JSON value The function restores the arbitrary nesting of a JSON value that has been flattened before using the @ref flatten() function. The JSON value must meet certain constraints: 1. The value must be an object. 2. The keys must be JSON pointers (see [RFC 6901](https://tools.ietf.org/html/rfc6901)) 3. The mapped values must be primitive JSON types. @return the original JSON from a flattened version @note Empty objects and arrays are flattened by @ref flatten() to `null` values and can not unflattened to their original type. Apart from this example, for a JSON value `j`, the following is always true: `j == j.flatten().unflatten()`. @complexity Linear in the size the JSON value. @throw type_error.314 if value is not an object @throw type_error.315 if object values are not primitive @liveexample{The following code shows how a flattened JSON object is unflattened into the original nested JSON object.,unflatten} @sa see @ref flatten() for the reverse function @since version 2.0.0 */ basic_json unflatten() const { return json_pointer::unflatten(*this); } /// @} ////////////////////////// // JSON Patch functions // ////////////////////////// /// @name JSON Patch functions /// @{ /*! @brief applies a JSON patch [JSON Patch](http://jsonpatch.com) defines a JSON document structure for expressing a sequence of operations to apply to a JSON) document. With this function, a JSON Patch is applied to the current JSON value by executing all operations from the patch. @param[in] json_patch JSON patch document @return patched document @note The application of a patch is atomic: Either all operations succeed and the patched document is returned or an exception is thrown. In any case, the original value is not changed: the patch is applied to a copy of the value. @throw parse_error.104 if the JSON patch does not consist of an array of objects @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory attributes are missing); example: `"operation add must have member path"` @throw out_of_range.401 if an array index is out of range. @throw out_of_range.403 if a JSON pointer inside the patch could not be resolved successfully in the current JSON value; example: `"key baz not found"` @throw out_of_range.405 if JSON pointer has no parent ("add", "remove", "move") @throw other_error.501 if "test" operation was unsuccessful @complexity Linear in the size of the JSON value and the length of the JSON patch. As usually only a fraction of the JSON value is affected by the patch, the complexity can usually be neglected. @liveexample{The following code shows how a JSON patch is applied to a value.,patch} @sa see @ref diff -- create a JSON patch by comparing two JSON values @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902) @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901) @since version 2.0.0 */ basic_json patch(const basic_json& json_patch) const { // make a working copy to apply the patch to basic_json result = *this; // the valid JSON Patch operations enum class patch_operations {add, remove, replace, move, copy, test, invalid}; const auto get_op = [](const std::string & op) { if (op == "add") { return patch_operations::add; } if (op == "remove") { return patch_operations::remove; } if (op == "replace") { return patch_operations::replace; } if (op == "move") { return patch_operations::move; } if (op == "copy") { return patch_operations::copy; } if (op == "test") { return patch_operations::test; } return patch_operations::invalid; }; // wrapper for "add" operation; add value at ptr const auto operation_add = [&result](json_pointer & ptr, basic_json val) { // adding to the root of the target document means replacing it if (ptr.empty()) { result = val; return; } // make sure the top element of the pointer exists json_pointer top_pointer = ptr.top(); if (top_pointer != ptr) { result.at(top_pointer); } // get reference to parent of JSON pointer ptr const auto last_path = ptr.back(); ptr.pop_back(); basic_json& parent = result[ptr]; switch (parent.m_type) { case value_t::null: case value_t::object: { // use operator[] to add value parent[last_path] = val; break; } case value_t::array: { if (last_path == "-") { // special case: append to back parent.push_back(val); } else { const auto idx = json_pointer::array_index(last_path); if (JSON_HEDLEY_UNLIKELY(idx > parent.size())) { // avoid undefined behavior JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", parent)); } // default case: insert add offset parent.insert(parent.begin() + static_cast<difference_type>(idx), val); } break; } // if there exists a parent it cannot be primitive default: // LCOV_EXCL_LINE JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE } }; // wrapper for "remove" operation; remove value at ptr const auto operation_remove = [this, &result](json_pointer & ptr) { // get reference to parent of JSON pointer ptr const auto last_path = ptr.back(); ptr.pop_back(); basic_json& parent = result.at(ptr); // remove child if (parent.is_object()) { // perform range check auto it = parent.find(last_path); if (JSON_HEDLEY_LIKELY(it != parent.end())) { parent.erase(it); } else { JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found", *this)); } } else if (parent.is_array()) { // note erase performs range check parent.erase(json_pointer::array_index(last_path)); } }; // type check: top level value must be an array if (JSON_HEDLEY_UNLIKELY(!json_patch.is_array())) { JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects", json_patch)); } // iterate and apply the operations for (const auto& val : json_patch) { // wrapper to get a value for an operation const auto get_value = [&val](const std::string & op, const std::string & member, bool string_type) -> basic_json & { // find value auto it = val.m_value.object->find(member); // context-sensitive error message const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'"; // check if desired value is present if (JSON_HEDLEY_UNLIKELY(it == val.m_value.object->end())) { // NOLINTNEXTLINE(performance-inefficient-string-concatenation) JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'", val)); } // check if result is of type string if (JSON_HEDLEY_UNLIKELY(string_type && !it->second.is_string())) { // NOLINTNEXTLINE(performance-inefficient-string-concatenation) JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'", val)); } // no error: return value return it->second; }; // type check: every element of the array must be an object if (JSON_HEDLEY_UNLIKELY(!val.is_object())) { JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects", val)); } // collect mandatory members const auto op = get_value("op", "op", true).template get<std::string>(); const auto path = get_value(op, "path", true).template get<std::string>(); json_pointer ptr(path); switch (get_op(op)) { case patch_operations::add: { operation_add(ptr, get_value("add", "value", false)); break; } case patch_operations::remove: { operation_remove(ptr); break; } case patch_operations::replace: { // the "path" location must exist - use at() result.at(ptr) = get_value("replace", "value", false); break; } case patch_operations::move: { const auto from_path = get_value("move", "from", true).template get<std::string>(); json_pointer from_ptr(from_path); // the "from" location must exist - use at() basic_json v = result.at(from_ptr); // The move operation is functionally identical to a // "remove" operation on the "from" location, followed // immediately by an "add" operation at the target // location with the value that was just removed. operation_remove(from_ptr); operation_add(ptr, v); break; } case patch_operations::copy: { const auto from_path = get_value("copy", "from", true).template get<std::string>(); const json_pointer from_ptr(from_path); // the "from" location must exist - use at() basic_json v = result.at(from_ptr); // The copy is functionally identical to an "add" // operation at the target location using the value // specified in the "from" member. operation_add(ptr, v); break; } case patch_operations::test: { bool success = false; JSON_TRY { // check if "value" matches the one at "path" // the "path" location must exist - use at() success = (result.at(ptr) == get_value("test", "value", false)); } JSON_INTERNAL_CATCH (out_of_range&) { // ignore out of range errors: success remains false } // throw an exception if test fails if (JSON_HEDLEY_UNLIKELY(!success)) { JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump(), val)); } break; } default: { // op must be "add", "remove", "replace", "move", "copy", or // "test" JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid", val)); } } } return result; } /*! @brief creates a diff as a JSON patch Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can be changed into the value @a target by calling @ref patch function. @invariant For two JSON values @a source and @a target, the following code yields always `true`: @code {.cpp} source.patch(diff(source, target)) == target; @endcode @note Currently, only `remove`, `add`, and `replace` operations are generated. @param[in] source JSON value to compare from @param[in] target JSON value to compare against @param[in] path helper value to create JSON pointers @return a JSON patch to convert the @a source to @a target @complexity Linear in the lengths of @a source and @a target. @liveexample{The following code shows how a JSON patch is created as a diff for two JSON values.,diff} @sa see @ref patch -- apply a JSON patch @sa see @ref merge_patch -- apply a JSON Merge Patch @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902) @since version 2.0.0 */ JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json diff(const basic_json& source, const basic_json& target, const std::string& path = "") { // the patch basic_json result(value_t::array); // if the values are the same, return empty patch if (source == target) { return result; } if (source.type() != target.type()) { // different types: replace value result.push_back( { {"op", "replace"}, {"path", path}, {"value", target} }); return result; } switch (source.type()) { case value_t::array: { // first pass: traverse common elements std::size_t i = 0; while (i < source.size() && i < target.size()) { // recursive call to compare array values at index i auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i)); result.insert(result.end(), temp_diff.begin(), temp_diff.end()); ++i; } // i now reached the end of at least one array // in a second pass, traverse the remaining elements // remove my remaining elements const auto end_index = static_cast<difference_type>(result.size()); while (i < source.size()) { // add operations in reverse order to avoid invalid // indices result.insert(result.begin() + end_index, object( { {"op", "remove"}, {"path", path + "/" + std::to_string(i)} })); ++i; } // add other remaining elements while (i < target.size()) { result.push_back( { {"op", "add"}, {"path", path + "/-"}, {"value", target[i]} }); ++i; } break; } case value_t::object: { // first pass: traverse this object's elements for (auto it = source.cbegin(); it != source.cend(); ++it) { // escape the key name to be used in a JSON patch const auto path_key = path + "/" + detail::escape(it.key()); if (target.find(it.key()) != target.end()) { // recursive call to compare object values at key it auto temp_diff = diff(it.value(), target[it.key()], path_key); result.insert(result.end(), temp_diff.begin(), temp_diff.end()); } else { // found a key that is not in o -> remove it result.push_back(object( { {"op", "remove"}, {"path", path_key} })); } } // second pass: traverse other object's elements for (auto it = target.cbegin(); it != target.cend(); ++it) { if (source.find(it.key()) == source.end()) { // found a key that is not in this -> add it const auto path_key = path + "/" + detail::escape(it.key()); result.push_back( { {"op", "add"}, {"path", path_key}, {"value", it.value()} }); } } break; } default: { // both primitive type: replace value result.push_back( { {"op", "replace"}, {"path", path}, {"value", target} }); break; } } return result; } /// @} //////////////////////////////// // JSON Merge Patch functions // //////////////////////////////// /// @name JSON Merge Patch functions /// @{ /*! @brief applies a JSON Merge Patch The merge patch format is primarily intended for use with the HTTP PATCH method as a means of describing a set of modifications to a target resource's content. This function applies a merge patch to the current JSON value. The function implements the following algorithm from Section 2 of [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396): ``` define MergePatch(Target, Patch): if Patch is an Object: if Target is not an Object: Target = {} // Ignore the contents and set it to an empty Object for each Name/Value pair in Patch: if Value is null: if Name exists in Target: remove the Name/Value pair from Target else: Target[Name] = MergePatch(Target[Name], Value) return Target else: return Patch ``` Thereby, `Target` is the current object; that is, the patch is applied to the current value. @param[in] apply_patch the patch to apply @complexity Linear in the lengths of @a patch. @liveexample{The following code shows how a JSON Merge Patch is applied to a JSON document.,merge_patch} @sa see @ref patch -- apply a JSON patch @sa [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396) @since version 3.0.0 */ void merge_patch(const basic_json& apply_patch) { if (apply_patch.is_object()) { if (!is_object()) { *this = object(); } for (auto it = apply_patch.begin(); it != apply_patch.end(); ++it) { if (it.value().is_null()) { erase(it.key()); } else { operator[](it.key()).merge_patch(it.value()); } } } else { *this = apply_patch; } } /// @} }; /*! @brief user-defined to_string function for JSON values This function implements a user-defined to_string for JSON objects. @param[in] j a JSON object @return a std::string object */ NLOHMANN_BASIC_JSON_TPL_DECLARATION std::string to_string(const NLOHMANN_BASIC_JSON_TPL& j) { return j.dump(); } } // namespace nlohmann /////////////////////// // nonmember support // /////////////////////// // specialization of std::swap, and std::hash namespace std { /// hash value for JSON objects template<> struct hash<nlohmann::json> { /*! @brief return a hash value for a JSON object @since version 1.0.0 */ std::size_t operator()(const nlohmann::json& j) const { return nlohmann::detail::hash(j); } }; /// specialization for std::less<value_t> /// @note: do not remove the space after '<', /// see https://github.com/nlohmann/json/pull/679 template<> struct less<::nlohmann::detail::value_t> { /*! @brief compare two value_t enum values @since version 3.0.0 */ bool operator()(nlohmann::detail::value_t lhs, nlohmann::detail::value_t rhs) const noexcept { return nlohmann::detail::operator<(lhs, rhs); } }; // C++20 prohibit function specialization in the std namespace. #ifndef JSON_HAS_CPP_20 /*! @brief exchanges the values of two JSON objects @since version 1.0.0 */ template<> inline void swap<nlohmann::json>(nlohmann::json& j1, nlohmann::json& j2) noexcept( // NOLINT(readability-inconsistent-declaration-parameter-name) is_nothrow_move_constructible<nlohmann::json>::value&& // NOLINT(misc-redundant-expression) is_nothrow_move_assignable<nlohmann::json>::value ) { j1.swap(j2); } #endif } // namespace std /*! @brief user-defined string literal for JSON values This operator implements a user-defined string literal for JSON objects. It can be used by adding `"_json"` to a string literal and returns a JSON object if no parse error occurred. @param[in] s a string representation of a JSON object @param[in] n the length of string @a s @return a JSON object @since version 1.0.0 */ JSON_HEDLEY_NON_NULL(1) inline nlohmann::json operator "" _json(const char* s, std::size_t n) { return nlohmann::json::parse(s, s + n); } /*! @brief user-defined string literal for JSON pointer This operator implements a user-defined string literal for JSON Pointers. It can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer object if no parse error occurred. @param[in] s a string representation of a JSON Pointer @param[in] n the length of string @a s @return a JSON pointer object @since version 2.0.0 */ JSON_HEDLEY_NON_NULL(1) inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n) { return nlohmann::json::json_pointer(std::string(s, n)); } // #include <nlohmann/detail/macro_unscope.hpp> // restore GCC/clang diagnostic settings #if defined(__clang__) #pragma GCC diagnostic pop #endif // clean up #undef JSON_ASSERT #undef JSON_INTERNAL_CATCH #undef JSON_CATCH #undef JSON_THROW #undef JSON_TRY #undef JSON_PRIVATE_UNLESS_TESTED #undef JSON_HAS_CPP_11 #undef JSON_HAS_CPP_14 #undef JSON_HAS_CPP_17 #undef JSON_HAS_CPP_20 #undef NLOHMANN_BASIC_JSON_TPL_DECLARATION #undef NLOHMANN_BASIC_JSON_TPL #undef JSON_EXPLICIT // #include <nlohmann/thirdparty/hedley/hedley_undef.hpp> #undef JSON_HEDLEY_ALWAYS_INLINE #undef JSON_HEDLEY_ARM_VERSION #undef JSON_HEDLEY_ARM_VERSION_CHECK #undef JSON_HEDLEY_ARRAY_PARAM #undef JSON_HEDLEY_ASSUME #undef JSON_HEDLEY_BEGIN_C_DECLS #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE #undef JSON_HEDLEY_CLANG_HAS_BUILTIN #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE #undef JSON_HEDLEY_CLANG_HAS_EXTENSION #undef JSON_HEDLEY_CLANG_HAS_FEATURE #undef JSON_HEDLEY_CLANG_HAS_WARNING #undef JSON_HEDLEY_COMPCERT_VERSION #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK #undef JSON_HEDLEY_CONCAT #undef JSON_HEDLEY_CONCAT3 #undef JSON_HEDLEY_CONCAT3_EX #undef JSON_HEDLEY_CONCAT_EX #undef JSON_HEDLEY_CONST #undef JSON_HEDLEY_CONSTEXPR #undef JSON_HEDLEY_CONST_CAST #undef JSON_HEDLEY_CPP_CAST #undef JSON_HEDLEY_CRAY_VERSION #undef JSON_HEDLEY_CRAY_VERSION_CHECK #undef JSON_HEDLEY_C_DECL #undef JSON_HEDLEY_DEPRECATED #undef JSON_HEDLEY_DEPRECATED_FOR #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION #undef JSON_HEDLEY_DIAGNOSTIC_POP #undef JSON_HEDLEY_DIAGNOSTIC_PUSH #undef JSON_HEDLEY_DMC_VERSION #undef JSON_HEDLEY_DMC_VERSION_CHECK #undef JSON_HEDLEY_EMPTY_BASES #undef JSON_HEDLEY_EMSCRIPTEN_VERSION #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK #undef JSON_HEDLEY_END_C_DECLS #undef JSON_HEDLEY_FLAGS #undef JSON_HEDLEY_FLAGS_CAST #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE #undef JSON_HEDLEY_GCC_HAS_BUILTIN #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE #undef JSON_HEDLEY_GCC_HAS_EXTENSION #undef JSON_HEDLEY_GCC_HAS_FEATURE #undef JSON_HEDLEY_GCC_HAS_WARNING #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK #undef JSON_HEDLEY_GCC_VERSION #undef JSON_HEDLEY_GCC_VERSION_CHECK #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE #undef JSON_HEDLEY_GNUC_HAS_BUILTIN #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE #undef JSON_HEDLEY_GNUC_HAS_EXTENSION #undef JSON_HEDLEY_GNUC_HAS_FEATURE #undef JSON_HEDLEY_GNUC_HAS_WARNING #undef JSON_HEDLEY_GNUC_VERSION #undef JSON_HEDLEY_GNUC_VERSION_CHECK #undef JSON_HEDLEY_HAS_ATTRIBUTE #undef JSON_HEDLEY_HAS_BUILTIN #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE #undef JSON_HEDLEY_HAS_EXTENSION #undef JSON_HEDLEY_HAS_FEATURE #undef JSON_HEDLEY_HAS_WARNING #undef JSON_HEDLEY_IAR_VERSION #undef JSON_HEDLEY_IAR_VERSION_CHECK #undef JSON_HEDLEY_IBM_VERSION #undef JSON_HEDLEY_IBM_VERSION_CHECK #undef JSON_HEDLEY_IMPORT #undef JSON_HEDLEY_INLINE #undef JSON_HEDLEY_INTEL_CL_VERSION #undef JSON_HEDLEY_INTEL_CL_VERSION_CHECK #undef JSON_HEDLEY_INTEL_VERSION #undef JSON_HEDLEY_INTEL_VERSION_CHECK #undef JSON_HEDLEY_IS_CONSTANT #undef JSON_HEDLEY_IS_CONSTEXPR_ #undef JSON_HEDLEY_LIKELY #undef JSON_HEDLEY_MALLOC #undef JSON_HEDLEY_MCST_LCC_VERSION #undef JSON_HEDLEY_MCST_LCC_VERSION_CHECK #undef JSON_HEDLEY_MESSAGE #undef JSON_HEDLEY_MSVC_VERSION #undef JSON_HEDLEY_MSVC_VERSION_CHECK #undef JSON_HEDLEY_NEVER_INLINE #undef JSON_HEDLEY_NON_NULL #undef JSON_HEDLEY_NO_ESCAPE #undef JSON_HEDLEY_NO_RETURN #undef JSON_HEDLEY_NO_THROW #undef JSON_HEDLEY_NULL #undef JSON_HEDLEY_PELLES_VERSION #undef JSON_HEDLEY_PELLES_VERSION_CHECK #undef JSON_HEDLEY_PGI_VERSION #undef JSON_HEDLEY_PGI_VERSION_CHECK #undef JSON_HEDLEY_PREDICT #undef JSON_HEDLEY_PRINTF_FORMAT #undef JSON_HEDLEY_PRIVATE #undef JSON_HEDLEY_PUBLIC #undef JSON_HEDLEY_PURE #undef JSON_HEDLEY_REINTERPRET_CAST #undef JSON_HEDLEY_REQUIRE #undef JSON_HEDLEY_REQUIRE_CONSTEXPR #undef JSON_HEDLEY_REQUIRE_MSG #undef JSON_HEDLEY_RESTRICT #undef JSON_HEDLEY_RETURNS_NON_NULL #undef JSON_HEDLEY_SENTINEL #undef JSON_HEDLEY_STATIC_ASSERT #undef JSON_HEDLEY_STATIC_CAST #undef JSON_HEDLEY_STRINGIFY #undef JSON_HEDLEY_STRINGIFY_EX #undef JSON_HEDLEY_SUNPRO_VERSION #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK #undef JSON_HEDLEY_TINYC_VERSION #undef JSON_HEDLEY_TINYC_VERSION_CHECK #undef JSON_HEDLEY_TI_ARMCL_VERSION #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK #undef JSON_HEDLEY_TI_CL2000_VERSION #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK #undef JSON_HEDLEY_TI_CL430_VERSION #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK #undef JSON_HEDLEY_TI_CL6X_VERSION #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK #undef JSON_HEDLEY_TI_CL7X_VERSION #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK #undef JSON_HEDLEY_TI_CLPRU_VERSION #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK #undef JSON_HEDLEY_TI_VERSION #undef JSON_HEDLEY_TI_VERSION_CHECK #undef JSON_HEDLEY_UNAVAILABLE #undef JSON_HEDLEY_UNLIKELY #undef JSON_HEDLEY_UNPREDICTABLE #undef JSON_HEDLEY_UNREACHABLE #undef JSON_HEDLEY_UNREACHABLE_RETURN #undef JSON_HEDLEY_VERSION #undef JSON_HEDLEY_VERSION_DECODE_MAJOR #undef JSON_HEDLEY_VERSION_DECODE_MINOR #undef JSON_HEDLEY_VERSION_DECODE_REVISION #undef JSON_HEDLEY_VERSION_ENCODE #undef JSON_HEDLEY_WARNING #undef JSON_HEDLEY_WARN_UNUSED_RESULT #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG #undef JSON_HEDLEY_FALL_THROUGH #endif // INCLUDE_NLOHMANN_JSON_HPP_
[ "brandont.dev@protonmail.com" ]
brandont.dev@protonmail.com
ff94807c21032464d0653771b5b2327ef06f287e
6506a1f7f639d9cf6ca5921d17012d872368b843
/Baekjoon/2947.cpp
f7baf1a2e434aa9cacf0230cf48d69d26d034f5e
[]
no_license
onnoo/Online-Judge
c844dd1a6032eff2df32598ef93d6d9e3a4a070f
7df441657cc7750c3d90141e7462f3a2f72213a0
refs/heads/master
2022-06-06T18:30:57.732490
2022-03-19T09:28:15
2022-03-19T09:28:15
163,737,364
1
0
null
null
null
null
UTF-8
C++
false
false
646
cpp
#include <iostream> using namespace std; int main(void) { int arr[5]; for (int i = 0; i < 5; i++) scanf("%d", arr + i); bool con = true; while (con) { for (int i = 0; i < 4; i++) if (arr[i] > arr[i + 1]) { int tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; for (int k = 0; k < 5; k++) printf("%d ", arr[k]); printf("\n"); } con = false; for (int i = 0; i < 5; i++) if (arr[i] != i + 1) con = true; } return 0; }
[ "sweyjw@gmail.com" ]
sweyjw@gmail.com
b2f8f26d6384c2eb7a77d175af1caf198159709f
bee55c8da97e1f4769103ac34f71814edb66ad41
/src/qt/optionsdialog.cpp
7b6a14555bfef3bab9e4bf3721d71abedbb070fd
[ "MIT" ]
permissive
DSSCOS/DSSC-Public-Chain
d245240e48aa914e7b82449a458c4ac8017773d4
b82c9a1f78420d7de1c118bc0af6d3008d889e10
refs/heads/master
2021-04-07T15:32:50.260916
2020-03-20T06:53:03
2020-03-20T06:53:03
248,686,157
0
0
null
null
null
null
UTF-8
C++
false
false
15,060
cpp
// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/bitpcoin-config.h" #endif #include "optionsdialog.h" #include "ui_optionsdialog.h" #include "bitcoinunits.h" #include "guiutil.h" #include "obfuscation.h" #include "optionsmodel.h" #include "main.h" // for MAX_SCRIPTCHECK_THREADS #include "netbase.h" #include "txdb.h" // for -dbcache defaults #ifdef ENABLE_WALLET #include "wallet.h" // for CWallet::minTxFee #endif #include <boost/thread.hpp> #include <QDataWidgetMapper> #include <QDir> #include <QIntValidator> #include <QLocale> #include <QMessageBox> #include <QTimer> #include <QSettings> OptionsDialog::OptionsDialog(QWidget* parent, bool enableWallet) : QDialog(parent), ui(new Ui::OptionsDialog), model(0), mapper(0), fProxyIpValid(true) { ui->setupUi(this); GUIUtil::restoreWindowGeometry("nOptionsDialogWindow", this->size(), this); //tmp ui->percentage_label->setVisible(false); ui->obfuscationRounds->setVisible(false); ui->label_2->setVisible(false); ui->anonymizePhc->setVisible(false); /* Main elements init */ ui->databaseCache->setMinimum(nMinDbCache); ui->databaseCache->setMaximum(nMaxDbCache); ui->threadsScriptVerif->setMinimum(-(int)boost::thread::hardware_concurrency()); ui->threadsScriptVerif->setMaximum(MAX_SCRIPTCHECK_THREADS); /* Network elements init */ #ifndef USE_UPNP ui->mapPortUpnp->setEnabled(false); #endif ui->proxyIp->setEnabled(false); ui->proxyPort->setEnabled(false); ui->proxyPort->setValidator(new QIntValidator(1, 65535, this)); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool))); ui->proxyIp->installEventFilter(this); /* Window elements init */ #ifdef Q_OS_MAC /* remove Window tab on Mac */ ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->tabWindow)); #endif /* remove Wallet tab in case of -disablewallet */ if (!enableWallet) { ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->tabWallet)); } else { if (pwalletMain && !pwalletMain->fCombineDust) ui->autoCombineFrame->setVisible(false); } /* Display elements init */ /* Number of displayed decimal digits selector */ QString digits; for (int index = 2; index <= 8; index++) { digits.setNum(index); ui->digits->addItem(digits, digits); } /* Theme selector static themes */ ui->theme->addItem(QString("Dark Blue"), QVariant("dblue")); ui->theme->addItem(QString("Light Blue"), QVariant("default")); ui->theme->addItem(QString("Dark Chocolate"), QVariant("dark")); /* Toolbar selector */ ui->toolbarPosition->addItem(QString("Top of window"), QVariant("Top")); ui->toolbarPosition->addItem(QString("Left side"), QVariant("Left")); /* Theme selector external themes */ boost::filesystem::path pathAddr = GetDataDir() / "themes"; QDir dir(pathAddr.string().c_str()); dir.setFilter(QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot); QFileInfoList list = dir.entryInfoList(); for (int i = 0; i < list.size(); ++i) { QFileInfo fileInfo = list.at(i); ui->theme->addItem(fileInfo.fileName(), QVariant(fileInfo.fileName())); } /* Language selector */ QDir translations(":translations"); ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant("")); foreach (const QString& langStr, translations.entryList()) { QLocale locale(langStr); /** check if the locale name consists of 2 parts (language_country) */ if (langStr.contains("_")) { #if QT_VERSION >= 0x040800 /** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); #else /** display language strings as "language - country (locale name)", e.g. "German - Germany (de)" */ ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" - ") + QLocale::countryToString(locale.country()) + QString(" (") + langStr + QString(")"), QVariant(langStr)); #endif } else { #if QT_VERSION >= 0x040800 /** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); #else /** display language strings as "language (locale name)", e.g. "German (de)" */ ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" (") + langStr + QString(")"), QVariant(langStr)); #endif } } #if QT_VERSION >= 0x040700 ui->thirdPartyTxUrls->setPlaceholderText("https://example.com/tx/%s"); #endif ui->unit->setModel(new BitcoinUnits(this)); /* Widget-to-option mapper */ mapper = new QDataWidgetMapper(this); mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); mapper->setOrientation(Qt::Vertical); /* setup/change UI elements when proxy IP is invalid/valid */ connect(this, SIGNAL(proxyIpChecks(QValidatedLineEdit*, int)), this, SLOT(doProxyIpChecks(QValidatedLineEdit*, int))); ui->unitLabel->setVisible(true); ui->unit->setVisible(true); ui->digitsLabel->setVisible(true); ui->digits->setVisible(true); ui->thirdPartyTxUrlsLabel->setVisible(true); ui->thirdPartyTxUrls->setVisible(true); ui->themeLabel->setVisible(true); ui->theme->setVisible(true); ui->toolbarLabel->setVisible(true); ui->toolbarPosition->setVisible(true); } OptionsDialog::~OptionsDialog() { GUIUtil::saveWindowGeometry("nOptionsDialogWindow", this); delete ui; } void OptionsDialog::setModel(OptionsModel* model) { this->model = model; if (model) { /* check if client restart is needed and show persistent message */ if (model->isRestartRequired()) showRestartWarning(true); QString strLabel = model->getOverriddenByCommandLine(); if (strLabel.isEmpty()) strLabel = tr("none"); ui->overriddenByCommandLineLabel->setText(strLabel); mapper->setModel(model); setMapper(); mapper->toFirst(); } /* warn when one of the following settings changes by user action (placed here so init via mapper doesn't trigger them) */ /* Main */ connect(ui->databaseCache, SIGNAL(valueChanged(int)), this, SLOT(showRestartWarning())); connect(ui->threadsScriptVerif, SIGNAL(valueChanged(int)), this, SLOT(showRestartWarning())); /* Wallet */ connect(ui->spendZeroConfChange, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning())); /* Network */ connect(ui->allowIncoming, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning())); connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning())); /* Display */ connect(ui->digits, SIGNAL(valueChanged()), this, SLOT(showRestartWarning())); connect(ui->theme, SIGNAL(valueChanged()), this, SLOT(showRestartWarning())); connect(ui->toolbarPosition, SIGNAL(valueChanged()), this, SLOT(showRestartWarning())); connect(ui->lang, SIGNAL(valueChanged()), this, SLOT(showRestartWarning())); connect(ui->thirdPartyTxUrls, SIGNAL(textChanged(const QString&)), this, SLOT(showRestartWarning())); connect(ui->showMasternodesTab, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning())); } void OptionsDialog::setMapper() { /* Main */ mapper->addMapping(ui->bitcoinAtStartup, OptionsModel::StartAtStartup); mapper->addMapping(ui->threadsScriptVerif, OptionsModel::ThreadsScriptVerif); mapper->addMapping(ui->databaseCache, OptionsModel::DatabaseCache); /* Wallet */ mapper->addMapping(ui->spendZeroConfChange, OptionsModel::SpendZeroConfChange); mapper->addMapping(ui->coinControlFeatures, OptionsModel::CoinControlFeatures); mapper->addMapping(ui->stakeThresholdEdit, OptionsModel::StakeSplitThreshold); mapper->addMapping(ui->autoCombineEdit, OptionsModel::AutoCombineRewards); mapper->addMapping(ui->autoCombineCheckBox, OptionsModel::AutoCombine); mapper->addMapping(ui->autoCombineLimitEdit, OptionsModel::AutoCombineLimit); /* Network */ mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP); mapper->addMapping(ui->allowIncoming, OptionsModel::Listen); mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse); mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP); mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort); /* Window */ #ifndef Q_OS_MAC mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray); mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose); #endif /* Display */ mapper->addMapping(ui->digits, OptionsModel::Digits); mapper->addMapping(ui->theme, OptionsModel::Theme); // mapper->addMapping(ui->theme, OptionsModel::Theme); mapper->addMapping(ui->toolbarPosition, OptionsModel::ToolbarPosition); mapper->addMapping(ui->lang, OptionsModel::Language); mapper->addMapping(ui->unit, OptionsModel::DisplayUnit); mapper->addMapping(ui->thirdPartyTxUrls, OptionsModel::ThirdPartyTxUrls); /* Obfuscation Rounds */ mapper->addMapping(ui->obfuscationRounds, OptionsModel::ObfuscationRounds); mapper->addMapping(ui->anonymizePhc, OptionsModel::AnonymizePhcAmount); /* Masternode Tab */ mapper->addMapping(ui->showMasternodesTab, OptionsModel::ShowMasternodesTab); } void OptionsDialog::enableOkButton() { /* prevent enabling of the OK button when data modified, if there is an invalid proxy address present */ if (fProxyIpValid) setOkButtonState(true); } void OptionsDialog::disableOkButton() { setOkButtonState(false); } void OptionsDialog::setOkButtonState(bool fState) { ui->okButton->setEnabled(fState); } void OptionsDialog::on_resetButton_clicked() { if (model) { // confirmation dialog QMessageBox::StandardButton btnRetVal = QMessageBox::question(this, tr("Confirm options reset"), tr("Client restart required to activate changes.") + "<br><br>" + tr("Client will be shutdown, do you want to proceed?"), QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel); if (btnRetVal == QMessageBox::Cancel) return; /* reset all options and close GUI */ model->Reset(); QApplication::quit(); } } void OptionsDialog::on_okButton_clicked() { mapper->submit(); obfuScationPool.cachedNumBlocks = std::numeric_limits<int>::max(); //setStakeSplitThreshold(); //setAutoCombineRewards(); setWalletOptions(); pwalletMain->MarkDirty(); accept(); } void OptionsDialog::on_cancelButton_clicked() { reject(); } void OptionsDialog::showRestartWarning(bool fPersistent) { ui->statusLabel->setStyleSheet("QLabel { color: red; }"); if (fPersistent) { ui->statusLabel->setText(tr("Client restart required to activate changes.")); } else { ui->statusLabel->setText(tr("This change would require a client restart.")); // clear non-persistent status label after 10 seconds // Todo: should perhaps be a class attribute, if we extend the use of statusLabel QTimer::singleShot(10000, this, SLOT(clearStatusLabel())); } } void OptionsDialog::clearStatusLabel() { ui->statusLabel->clear(); } void OptionsDialog::doProxyIpChecks(QValidatedLineEdit* pUiProxyIp, int nProxyPort) { Q_UNUSED(nProxyPort); const std::string strAddrProxy = pUiProxyIp->text().toStdString(); CService addrProxy; /* Check for a valid IPv4 / IPv6 address */ if (!(fProxyIpValid = LookupNumeric(strAddrProxy.c_str(), addrProxy))) { disableOkButton(); pUiProxyIp->setValid(false); ui->statusLabel->setStyleSheet("QLabel { color: red; }"); ui->statusLabel->setText(tr("The supplied proxy address is invalid.")); } else { enableOkButton(); ui->statusLabel->clear(); } } bool OptionsDialog::eventFilter(QObject* object, QEvent* event) { if (event->type() == QEvent::FocusOut) { if (object == ui->proxyIp) { emit proxyIpChecks(ui->proxyIp, ui->proxyPort->text().toInt()); } } return QDialog::eventFilter(object, event); } void OptionsDialog::on_stakeThresholdEdit_valueChanged(int i) { ui->stakeThresholdSlider->setValue(i); } void OptionsDialog::on_stakeThresholdSlider_valueChanged(int value) { ui->stakeThresholdEdit->setValue(value); } void OptionsDialog::on_autoCombineEdit_valueChanged(int i) { ui->autoCombineSlider->setValue(i); } void OptionsDialog::on_autoCombineSlider_valueChanged(int value) { ui->autoCombineEdit->setValue(value); } void OptionsDialog::on_autoCombineLimitEdit_valueChanged(int i) { ui->autoCombineLimitSlider->setValue(i); } void OptionsDialog::on_autoCombineLimitSlider_valueChanged(int value) { ui->autoCombineLimitEdit->setValue(value); } void OptionsDialog::on_autoCombineCheckBox_stateChanged(int state) { if (state == Qt::Checked) { ui->autoCombineFrame->setVisible(true); } else { ui->autoCombineFrame->setVisible(false); } } void OptionsDialog::setWalletOptions() { QSettings settings; uint64_t nStakeSplitThreshold = settings.value("nStakeSplitThreshold").toInt(); bool AutoCombine = settings.value("bAutoCombine").toBool(); int AutoCombineRewards = settings.value("nAutoCombineRewards").toInt(); int AutoCombineLimit = settings.value("nAutoCombineLimit").toInt(); if (pwalletMain) { CWalletDB walletdb(pwalletMain->strWalletFile); { LOCK(pwalletMain->cs_wallet); /* Update StakeSplitThreshold's value in wallet */ pwalletMain->nStakeSplitThreshold = nStakeSplitThreshold; /* Update AutoCombineRewards value in wallet */ pwalletMain->fCombineDust = AutoCombine; pwalletMain->nAutoCombineThreshold = AutoCombineRewards; pwalletMain->nAutoCombineLimit = AutoCombineLimit; /* Write settings to wallet */ if (pwalletMain->fFileBacked) { walletdb.WriteStakeSplitThreshold(nStakeSplitThreshold); walletdb.WriteAutoCombineSettings(AutoCombine, AutoCombineRewards, AutoCombineLimit); } } } }
[ "lyyyouqian1992" ]
lyyyouqian1992
8d5593fc630547e24dcb3faf27ecc0044fb7087a
f2c48401a2bbe43c730f009b55674d8844cebe90
/TRooFit/TRooChi2Constraint.h
34012540db8acae2fd276b8ebff042ba60a0a4d1
[]
no_license
PrimeZhang/TRooFit
423d863359cb85e7caeb9dbc40445359611c246c
d57a61fe045438afcbfdb233723cbac24e85b864
refs/heads/master
2020-12-20T14:45:12.805028
2018-09-05T08:49:42
2018-09-05T08:50:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,253
h
#ifndef TROO_CHI2_VAR #define TROO_CHI2_VAR #include "RooAbsReal.h" #include "RooCmdArg.h" #include "RooDataHist.h" #include "RooAbsPdf.h" #include "RooRealProxy.h" class TRooChi2Constraint : public RooAbsPdf { public: // Constructors, assignment etc enum FuncMode { Function, Pdf, ExtendedPdf } ; TRooChi2Constraint(const char *name, const char *title, RooAbsPdf& pdf, RooDataHist& data, Bool_t extended=kFALSE, const char* rangeName=0, const char* addCoefRangeName=0); TRooChi2Constraint(const TRooChi2Constraint& other, const char* name=0); virtual TObject* clone(const char* newname) const { return new TRooChi2Constraint(*this,newname); } virtual ~TRooChi2Constraint(); protected: RooRealProxy fChi2; virtual Bool_t selfNormalized() const { return true; } virtual Double_t evaluate() const { return std::exp(-0.5*fChi2); } ClassDef(TRooChi2Constraint,1) // Chi^2 function of p.d.f w.r.t a binned dataset. pdf value is exp(-0.5*chi^2) }; // #include "RooGaussian.h" // // class TRooGaussian : public RooGaussian { // public: // using RooGaussian::RooGaussian; // // virtual Bool_t selfNormalized() const { return true; } // // protected: // ClassDef(TRooGaussian,1) // }; #endif
[ "will@cern.ch" ]
will@cern.ch
46346aeb8e87506d90c625f0cb4a905d3e15da56
c60638380ab1a6a01138d467a7c69bd5c0c5e162
/library/solver/loop/tools/ordinates.hpp
bb6efdea74f3735430a6cbce3c5df53074a66aec
[]
no_license
kbeling4/1Dsolver
f655eb74381ccfe7e4f40c13ccedc679bb95528f
361506855e2138bc7828b845e141f650ef3a160a
refs/heads/master
2020-08-23T17:00:46.897054
2019-12-07T18:50:25
2019-12-07T18:50:25
216,668,885
3
0
null
null
null
null
UTF-8
C++
false
false
3,255
hpp
struct Ordinate { double value; double weight; }; double PI = std::atan(1.0) * 4.0; double get_error(std::vector<double> &first_arr, std::vector<double> &second_arr) { // Return the L-2 norm of the difference between two vectors double error, difference, sum; sum = 0.0; for (unsigned int i = 0; i < first_arr.size(); i++) { difference = first_arr[i] - second_arr[i]; sum += difference * difference; } error = std::sqrt(sum); return error; } std::vector<double> linspace(double x_start, double x_fin, int x_len) { // Cold-copy of the linspace command for vector datatype double delta_x; std::vector<double> arr_x; delta_x = (x_fin - x_start) / ((double)x_len - 1.0); for (int i = 0; i < x_len; i++) { arr_x.push_back(x_start + (double)i * delta_x); } return arr_x; } template<typename L, typename U> auto get_ordinates(int order, L intv_a, U intv_b) { int order_place, order_one, order_two; double error, y_const = 2.0; std::vector<double> x_space(order), y_space(order), y_hold(order), prime(order); std::vector<std::vector<double>> legendre(order, std::vector<double>(order + 1)); std::vector<Ordinate> ordinates(order); if (order < 1) { std::cout << "Truncation order must be an integer greater than 0\n"; exit(EXIT_FAILURE); } // Used for indexing purposes order_place = order - 1; order_one = order_place + 1; order_two = order_place + 2; // Assign the arrays x_space = linspace(-1.0, 1.0, order_one); for (int i = 0; i < order_one; i++) { y_space[i] = std::cos((2.0 * (double)i + 1.0) / (2.0 * order_place + 2.0) * PI) + (0.27 / order_one) * std::sin((PI * x_space[i] * order_place) / order_two); y_hold[i] = y_const; } error = get_error(y_space, y_hold); // Compute the zeros of the N+1 Legendre Polynomial using the recursion // relation and the Newton-Raphson method while (error > std::numeric_limits<double>::epsilon()) { for (int i = 0; i < order; i++) { // First Legendre polynomial legendre[i][0] = 1.0; // Second Legendre polynomial legendre[i][1] = y_space[i]; // Remaining Legendre polynomials if (order > 1) { for (int j = 2; j < order_two; j++) { legendre[i][j] = ((2.0 * (double)j - 1.0) * y_space[i] * legendre[i][j - 1] - ((double)j - 1.0) * legendre[i][j - 2]) / (double)j; } } // Derivative of the Legendre polynomial prime[i] = order_two * (legendre[i][order_place] - y_space[i] * legendre[i][order_one]) / (1.0 - std::pow(y_space[i], 2.0)); // Error allocation y_hold[i] = y_space[i]; y_space[i] = y_hold[i] - legendre[i][order_one] / prime[i]; error = get_error(y_space, y_hold); } } // Linear map from [-1, 1] to [intv_a, intv_b] for (int i = 0; i < order; i++) { // Compute the ordinate values ordinates[i].value = (double)intv_a * (1.0 - y_space[i]) / 2.0 + (double)intv_b * (1.0 + y_space[i]) / 2.0; // Compute the weights ordinates[i].weight = (double)(intv_b - intv_a) / ((1.0 - std::pow(y_space[i], 2.0)) * std::pow(prime[i], 2.0)) * std::pow((double)order_two / (double)order_one, 2.0); } std::reverse(ordinates.begin(), ordinates.end()); return ordinates; }
[ "pcxcx2@gmail.com" ]
pcxcx2@gmail.com
e8ae137a9ae437818c0c948ee34b0fc5c8c74e8d
bb04f391bb0a0bd5f7e146d35241744b9a09bd79
/entities/ZigZagEnemy.cpp
98a07a1cb1447c1dc503890b8e0532e034031d53
[]
no_license
scurvysteve/galaga-esque
e4dcb475e10eaff64a30eaab336903847ac15fd3
3447430eea665a9ce8d3b8e34da71d7f755d98df
refs/heads/master
2020-12-25T11:05:51.883875
2013-09-09T04:55:21
2013-09-09T04:55:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
697
cpp
/* * ZigZagEnemy.cpp * * Created on: Apr 8, 2013 * Author: joe */ #include "ZigZagEnemy.h" ZigZagEnemy::ZigZagEnemy() { // TODO Auto-generated constructor stub } ZigZagEnemy::ZigZagEnemy(int initialX, int initialY){ GenericEntity::initEntity(initialX, initialY, 20, 20); image.loadImage("zigZagEnemy.png"); pointValue = 15; currentHP = 1; maxHP = 1; zigCounter = 0; bullets = std::vector<Bullet>(); } ZigZagEnemy::~ZigZagEnemy() { // TODO Auto-generated destructor stub } void ZigZagEnemy::handleLogic(){ zigCounter++; if(zigCounter>40){ box.y += SPEED; box.x += SPEED; } else{ box.y += SPEED; box.x -= SPEED; } if(zigCounter>80){ zigCounter = 0; } }
[ "joe@Babel.Babylon" ]
joe@Babel.Babylon
d59bbdc674025c49a7f76885aa401f56246600cc
e4625e88354a5a5964441bdfe474ff20a04b34c9
/Test/UnitTest/UnitTestRunner.cpp
4490fe52694eb8999a1e3fe74a962e5d6a5d3b9c
[]
no_license
frostazy/VoxelGame
0d46d63587ee76b34a6384295d60583a43bb6206
6ab76fd001fc601ba30ebab4b4be3f6b52ed63e6
refs/heads/master
2020-12-03T09:15:01.697059
2016-09-19T03:11:06
2016-09-19T03:11:06
68,564,067
1
0
null
null
null
null
UTF-8
C++
false
false
1,305
cpp
#include <windows.h> #include <string> #include <fstream> #include <iostream> using namespace std; typedef int (*RunAllUnitTestsPtr)(int argc, char* argv[]); bool FileExist(const string& filePath) { ifstream file(filePath); return !file.fail(); } int main(int argc, char* argv[]) { HMODULE hModule = GetModuleHandle(NULL); char runnerFilePath_c[MAX_PATH]; GetModuleFileName(hModule, runnerFilePath_c, MAX_PATH); string runnerFilePath = runnerFilePath_c; string binDir; const size_t last_slash_idx = runnerFilePath.rfind('\\'); if (std::string::npos != last_slash_idx) { binDir = runnerFilePath.substr(0, last_slash_idx); } string hyVoxelFilePath = binDir + "\\HyVoxel.dll"; if (!FileExist(hyVoxelFilePath)) { cout << "HyVoxel.dll is not found." << endl; return 1; } HINSTANCE hinstLib = LoadLibrary(hyVoxelFilePath.c_str()); if (hinstLib == NULL) { cout << "Failed to load HyVoxel.dll" << endl; return 1; } RunAllUnitTestsPtr runAllUnitTestsPtr = (RunAllUnitTestsPtr)GetProcAddress(hinstLib, "RunAllUnitTests"); if (runAllUnitTestsPtr == NULL) { cout << "RunAllUnitTests not found in HyVoxel.dll. Check if HyVoxel.dll is shipping version." << endl; return 1; } // The unit tests will be run during this query. return (*runAllUnitTestsPtr)(argc, argv); }
[ "Zhou Yun" ]
Zhou Yun
c3deedb07a601b32b5e2b679a322d1a64d06b3d2
d8033ee59a652736710748261771012f356b3431
/include/engine/system/platform/RenderAPI/OpenGL/OpenGLVAO.hpp
b38346f75683801df6de5904237083fa74ca041e
[]
no_license
Shwastya/MyTFMDescent
4f696a38d9e68bbaad2e5c40715465abdf536e84
1b872dd7682623de8a54cce1bfa8134a57694260
refs/heads/master
2023-06-23T12:24:23.310130
2021-07-17T20:54:22
2021-07-17T20:54:22
347,040,611
0
0
null
null
null
null
UTF-8
C++
false
false
694
hpp
#pragma once #include "engine/system/renderer/VAO.hpp" namespace MHelmet { class OpenGLVAO : public VAO { public: OpenGLVAO(); virtual ~OpenGLVAO(); virtual void Bind() const override; virtual void Unbind() const override; // conteo de referencias virtual void Add__VBO(const RefCount<VBO>& _vbo) override; virtual void Add__EBO(const RefCount<EBO>& _ebo) override; virtual const std::vector<RefCount<VBO>>& GetVBO() const override { return m_VBOs; } inline virtual const RefCount<EBO>& GetEBO() const override { return m_EBO; } private: // using std::shared_ptr<Type> uint32_t m_ID_VAO; std::vector<RefCount<VBO>> m_VBOs; RefCount<EBO> m_EBO; }; }
[ "jose.l.rosa.m@gmail.com" ]
jose.l.rosa.m@gmail.com
a77541ac68ffb578cb8b377ad6221c264cb8eaf8
6751cd2fdc5833e6281ddc7a6a6581ead1062cc1
/src/robolisp/val/int_num.cpp
2be03d283870edd65557565f0c28a981efd48cba
[ "BSD-3-Clause-Clear" ]
permissive
mrpengyu/robolisp
7c2c066441c0803060684d47fd393fc4589f427f
22a9cda2fe43b859a4c5ab559bb7c55756ee0951
refs/heads/master
2022-04-08T15:54:04.792895
2020-03-04T17:50:18
2020-03-04T17:50:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
591
cpp
#include "int_num.hpp" #include <cinttypes> #include <string> #include "../val.hpp" #include "../val_vis.hpp" using namespace robolisp::impl; using namespace val; IntNum::IntNum(int val) : val_ {val} {} ValPtr IntNum::copy() const { return ValPtr(new IntNum(*this)); } std::string IntNum::to_str() const { return std::to_string(val_); } const std::int32_t &IntNum::get() const { return val_; } void IntNum::accept_vis(ValVis *val_vis) { val_vis->visit(this); } ValPtr robolisp::impl::val::create_int_num(std::int32_t val) { return ValPtr(new IntNum(val)); }
[ "59334029+szsy-robotics@users.noreply.github.com" ]
59334029+szsy-robotics@users.noreply.github.com
ff4e658f09cd961bc230107fd4778d1b70b2c2af
cba12a4049fc3db690cffb631f5e29cf22de5e1c
/src/code/warning.h
d3d95a197ea7d0891a2d620a50dae0edb4242465
[]
no_license
RogerLrc/Eight_Puzzle
78b13272fadded380f586cadb3c96ed47b15958e
c7dcca726245f1e4c0eb71a2bac3b9ddf2eae284
refs/heads/master
2020-03-11T20:01:42.541784
2018-04-19T14:24:29
2018-04-19T14:24:29
130,224,980
0
0
null
null
null
null
UTF-8
C++
false
false
309
h
#ifndef WARNING_H #define WARNING_H #include <QDialog> namespace Ui { class Warning; } class Warning : public QDialog { Q_OBJECT public: explicit Warning(QWidget *parent = 0); ~Warning(); private slots: void on_buttonBox_accepted(); private: Ui::Warning *ui; }; #endif // WARNING_H
[ "noreply@github.com" ]
RogerLrc.noreply@github.com
9564ba565321bab5d04e5e5febab67275d633f77
615622849d5e7ffbc4ea9c537edfc0d8fb3a02a4
/submits.old/10_33_46_111_B_4202.cpp
0dea2c2626d529ac93679cf75dcf2ba351461d54
[]
no_license
lisiynos/train
f714d11e9e71f27472ca3f6fbfd576c849c07c5f
a3b9f9babf9587eabde8d94b76a52f8ae9d5addc
refs/heads/master
2020-12-13T15:32:29.862614
2016-08-29T09:35:00
2016-08-29T09:35:00
28,248,330
0
0
null
null
null
null
UTF-8
C++
false
false
284
cpp
#include <iostream> #include <cstdio> #include <stdlib.h> #include <string> using namespace std; int main() { freopen ("string.in", "r", stdin); freopen ("string.out", "w", stdout); string s; getline(cin, s); for (int i = s.length() - 1; i >= 0; --i) cout << s[i]; }
[ "super.denis@gmail.com" ]
super.denis@gmail.com
cc2f8c20b8bf67ee85196dbf7f3a3ff36be5a720
a33aac97878b2cb15677be26e308cbc46e2862d2
/program_data/PKU_raw/100/521.c
ad7f9dccf184cc01604a51962865be2f163b4344
[]
no_license
GabeOchieng/ggnn.tensorflow
f5d7d0bca52258336fc12c9de6ae38223f28f786
7c62c0e8427bea6c8bec2cebf157b6f1ea70a213
refs/heads/master
2022-05-30T11:17:42.278048
2020-05-02T11:33:31
2020-05-02T11:33:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
402
c
void main() { char *p1,*p2,a[300],b[26]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}; int *q,c[26]={0},t=0; gets(a); for(p1=a;p1<a+strlen(a);p1++) { for(p2=b,q=c;p2<b+26;p2++,q++) if(*p1==*p2) {*q=*q+1;t=1;break;} } for(p2=b,q=c;p2<b+26;p2++,q++) {if(*q>0)printf("%c=%d\n",*p2,*q);} if(t==0) printf("No"); }
[ "bdqnghi@gmail.com" ]
bdqnghi@gmail.com