Compare commits
70 Commits
2806086558
...
PIThreadPo
| Author | SHA1 | Date | |
|---|---|---|---|
| a16f629dc5 | |||
| 5868e0ec9d | |||
| 3102b985d5 | |||
| 93547beb38 | |||
| 5794eac20a | |||
| edb7189013 | |||
| dc16a0c903 | |||
| 96c22e1184 | |||
| 4537e40832 | |||
| 6efe77a395 | |||
| 6cfc4524f0 | |||
| fe3b30bd49 | |||
|
a1be5be5a1
|
|||
|
99c99c39c2
|
|||
| ba63e72bfa | |||
| 79fa549201 | |||
| 35140ee002 | |||
| f0c8bfef0a | |||
| ba57aa0144 | |||
| ccbf86f781 | |||
| ac415ebbb6 | |||
| c02b627d47 | |||
| 9dc1af921c | |||
| e761625eab | |||
| 449978bda0 | |||
| fe01c353e6 | |||
| 9f57f0107e | |||
| ac877f1024 | |||
| 8ccc05ee78 | |||
| 2798d7de9c | |||
| 767bb2b382 | |||
| 3e5714a5e1 | |||
| 6e4a64e64a | |||
| 40cdc90131 | |||
| d758cea974 | |||
| ed13838237 | |||
| 07ae277f9e | |||
| 46f86b6591 | |||
| 9588b48105 | |||
| 1739836a18 | |||
| 7195734765 | |||
| 8ecec6b914 | |||
| 9029bcf099 | |||
| 6f1660fd9e | |||
| f50a3abc8e | |||
| 8c15113cb0 | |||
| 4253acb72b | |||
| e22630b1bd | |||
| 563d9c5487 | |||
| 34bc322b9b | |||
| 6c3c763934 | |||
| 4d841787fc | |||
| 790246afea | |||
| 978e350722 | |||
| 1d76cacae2 | |||
| db954ffdaa | |||
| 8d6ae976a3 | |||
| e767fae934 | |||
| 5db97ca959 | |||
| daab41e41e | |||
| a61c8477c7 | |||
| 788ad8f2c0 | |||
| 78afc179c4 | |||
| 69ec4c9837 | |||
| 2368de6e93 | |||
| e5df76ab1d | |||
| fdec0e66a8 | |||
| 5f3baa5580 | |||
| 7083b2c32b | |||
| af02684dc5 |
@@ -134,8 +134,8 @@ JavaScriptQuotes: Leave
|
||||
JavaScriptWrapImports: true
|
||||
KeepEmptyLinesAtTheStartOfBlocks: false
|
||||
LambdaBodyIndentation: Signature
|
||||
MacroBlockBegin: "PRIVATE_DEFINITION_START|STATIC_INITIALIZER_BEGIN"
|
||||
MacroBlockEnd: "PRIVATE_DEFINITION_END|STATIC_INITIALIZER_END"
|
||||
MacroBlockBegin: "PRIVATE_DEFINITION_START|STATIC_INITIALIZER_BEGIN|DECLARE_UNIT_CLASS_BEGIN"
|
||||
MacroBlockEnd: "PRIVATE_DEFINITION_END|PRIVATE_DEFINITION_END_NO_INITIALIZE|STATIC_INITIALIZER_END|DECLARE_UNIT_CLASS_END"
|
||||
MaxEmptyLinesToKeep: 2
|
||||
NamespaceIndentation: None
|
||||
ObjCBinPackProtocolList: Auto
|
||||
|
||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -1,8 +1,10 @@
|
||||
/src_main/piversion.h
|
||||
/.svn
|
||||
/.*
|
||||
/doc/rtf
|
||||
_unsused
|
||||
CMakeLists.txt.user*
|
||||
/include
|
||||
/release
|
||||
/build*
|
||||
/AGENTS.md
|
||||
/plans
|
||||
|
||||
121
3rd/BLAKE2/COPYING
Normal file
121
3rd/BLAKE2/COPYING
Normal file
@@ -0,0 +1,121 @@
|
||||
Creative Commons Legal Code
|
||||
|
||||
CC0 1.0 Universal
|
||||
|
||||
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
|
||||
LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
|
||||
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
|
||||
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
|
||||
REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
|
||||
PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
|
||||
THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
|
||||
HEREUNDER.
|
||||
|
||||
Statement of Purpose
|
||||
|
||||
The laws of most jurisdictions throughout the world automatically confer
|
||||
exclusive Copyright and Related Rights (defined below) upon the creator
|
||||
and subsequent owner(s) (each and all, an "owner") of an original work of
|
||||
authorship and/or a database (each, a "Work").
|
||||
|
||||
Certain owners wish to permanently relinquish those rights to a Work for
|
||||
the purpose of contributing to a commons of creative, cultural and
|
||||
scientific works ("Commons") that the public can reliably and without fear
|
||||
of later claims of infringement build upon, modify, incorporate in other
|
||||
works, reuse and redistribute as freely as possible in any form whatsoever
|
||||
and for any purposes, including without limitation commercial purposes.
|
||||
These owners may contribute to the Commons to promote the ideal of a free
|
||||
culture and the further production of creative, cultural and scientific
|
||||
works, or to gain reputation or greater distribution for their Work in
|
||||
part through the use and efforts of others.
|
||||
|
||||
For these and/or other purposes and motivations, and without any
|
||||
expectation of additional consideration or compensation, the person
|
||||
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
|
||||
is an owner of Copyright and Related Rights in the Work, voluntarily
|
||||
elects to apply CC0 to the Work and publicly distribute the Work under its
|
||||
terms, with knowledge of his or her Copyright and Related Rights in the
|
||||
Work and the meaning and intended legal effect of CC0 on those rights.
|
||||
|
||||
1. Copyright and Related Rights. A Work made available under CC0 may be
|
||||
protected by copyright and related or neighboring rights ("Copyright and
|
||||
Related Rights"). Copyright and Related Rights include, but are not
|
||||
limited to, the following:
|
||||
|
||||
i. the right to reproduce, adapt, distribute, perform, display,
|
||||
communicate, and translate a Work;
|
||||
ii. moral rights retained by the original author(s) and/or performer(s);
|
||||
iii. publicity and privacy rights pertaining to a person's image or
|
||||
likeness depicted in a Work;
|
||||
iv. rights protecting against unfair competition in regards to a Work,
|
||||
subject to the limitations in paragraph 4(a), below;
|
||||
v. rights protecting the extraction, dissemination, use and reuse of data
|
||||
in a Work;
|
||||
vi. database rights (such as those arising under Directive 96/9/EC of the
|
||||
European Parliament and of the Council of 11 March 1996 on the legal
|
||||
protection of databases, and under any national implementation
|
||||
thereof, including any amended or successor version of such
|
||||
directive); and
|
||||
vii. other similar, equivalent or corresponding rights throughout the
|
||||
world based on applicable law or treaty, and any national
|
||||
implementations thereof.
|
||||
|
||||
2. Waiver. To the greatest extent permitted by, but not in contravention
|
||||
of, applicable law, Affirmer hereby overtly, fully, permanently,
|
||||
irrevocably and unconditionally waives, abandons, and surrenders all of
|
||||
Affirmer's Copyright and Related Rights and associated claims and causes
|
||||
of action, whether now known or unknown (including existing as well as
|
||||
future claims and causes of action), in the Work (i) in all territories
|
||||
worldwide, (ii) for the maximum duration provided by applicable law or
|
||||
treaty (including future time extensions), (iii) in any current or future
|
||||
medium and for any number of copies, and (iv) for any purpose whatsoever,
|
||||
including without limitation commercial, advertising or promotional
|
||||
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
|
||||
member of the public at large and to the detriment of Affirmer's heirs and
|
||||
successors, fully intending that such Waiver shall not be subject to
|
||||
revocation, rescission, cancellation, termination, or any other legal or
|
||||
equitable action to disrupt the quiet enjoyment of the Work by the public
|
||||
as contemplated by Affirmer's express Statement of Purpose.
|
||||
|
||||
3. Public License Fallback. Should any part of the Waiver for any reason
|
||||
be judged legally invalid or ineffective under applicable law, then the
|
||||
Waiver shall be preserved to the maximum extent permitted taking into
|
||||
account Affirmer's express Statement of Purpose. In addition, to the
|
||||
extent the Waiver is so judged Affirmer hereby grants to each affected
|
||||
person a royalty-free, non transferable, non sublicensable, non exclusive,
|
||||
irrevocable and unconditional license to exercise Affirmer's Copyright and
|
||||
Related Rights in the Work (i) in all territories worldwide, (ii) for the
|
||||
maximum duration provided by applicable law or treaty (including future
|
||||
time extensions), (iii) in any current or future medium and for any number
|
||||
of copies, and (iv) for any purpose whatsoever, including without
|
||||
limitation commercial, advertising or promotional purposes (the
|
||||
"License"). The License shall be deemed effective as of the date CC0 was
|
||||
applied by Affirmer to the Work. Should any part of the License for any
|
||||
reason be judged legally invalid or ineffective under applicable law, such
|
||||
partial invalidity or ineffectiveness shall not invalidate the remainder
|
||||
of the License, and in such case Affirmer hereby affirms that he or she
|
||||
will not (i) exercise any of his or her remaining Copyright and Related
|
||||
Rights in the Work or (ii) assert any associated claims and causes of
|
||||
action with respect to the Work, in either case contrary to Affirmer's
|
||||
express Statement of Purpose.
|
||||
|
||||
4. Limitations and Disclaimers.
|
||||
|
||||
a. No trademark or patent rights held by Affirmer are waived, abandoned,
|
||||
surrendered, licensed or otherwise affected by this document.
|
||||
b. Affirmer offers the Work as-is and makes no representations or
|
||||
warranties of any kind concerning the Work, express, implied,
|
||||
statutory or otherwise, including without limitation warranties of
|
||||
title, merchantability, fitness for a particular purpose, non
|
||||
infringement, or the absence of latent or other defects, accuracy, or
|
||||
the present or absence of errors, whether or not discoverable, all to
|
||||
the greatest extent permissible under applicable law.
|
||||
c. Affirmer disclaims responsibility for clearing rights of other persons
|
||||
that may apply to the Work or any use thereof, including without
|
||||
limitation any person's Copyright and Related Rights in the Work.
|
||||
Further, Affirmer disclaims responsibility for obtaining any necessary
|
||||
consents, permissions or other rights required for any use of the
|
||||
Work.
|
||||
d. Affirmer understands and acknowledges that Creative Commons is not a
|
||||
party to this document and has no duty or obligation with respect to
|
||||
this CC0 or use of the Work.
|
||||
@@ -97,8 +97,10 @@ public:
|
||||
{
|
||||
int code = lua_pcall (L, nargs, nresults, msgh);
|
||||
|
||||
if (code != LUABRIDGE_LUA_OK)
|
||||
Throw (LuaException (L, code));
|
||||
if (code != LUABRIDGE_LUA_OK) {
|
||||
// Throw (LuaException (L, code));
|
||||
assert(true);
|
||||
}
|
||||
}
|
||||
|
||||
//----------------------------------------------------------------------------
|
||||
@@ -128,7 +130,8 @@ protected:
|
||||
private:
|
||||
static int throwAtPanic (lua_State* L)
|
||||
{
|
||||
throw LuaException (L, -1);
|
||||
// throw LuaException (L, -1);
|
||||
return -1;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -101,7 +101,8 @@ protected:
|
||||
{
|
||||
if (m_stackSize == 0)
|
||||
{
|
||||
throw std::logic_error ("Unable to continue registration");
|
||||
std::cerr << ("Unable to continue registration");
|
||||
assert(true);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -1054,7 +1055,8 @@ public:
|
||||
{
|
||||
if (m_stackSize == 1)
|
||||
{
|
||||
throw std::logic_error ("endNamespace () called on global namespace");
|
||||
std::cerr << ("endNamespace () called on global namespace");
|
||||
assert(true);
|
||||
}
|
||||
|
||||
assert (m_stackSize > 1);
|
||||
@@ -1150,7 +1152,8 @@ public:
|
||||
{
|
||||
if (m_stackSize == 1)
|
||||
{
|
||||
throw std::logic_error ("addProperty () called on global namespace");
|
||||
std::cerr << ("addProperty () called on global namespace");
|
||||
assert(true);
|
||||
}
|
||||
|
||||
assert (lua_istable (L, -1)); // Stack: namespace table (ns)
|
||||
|
||||
@@ -33,6 +33,7 @@
|
||||
|
||||
#include <cassert>
|
||||
#include <stdexcept>
|
||||
#include <iostream>
|
||||
|
||||
|
||||
namespace luabridge {
|
||||
@@ -320,7 +321,8 @@ public:
|
||||
lua_rawgetp (L, LUA_REGISTRYINDEX, ClassInfo <T>::getClassKey ());
|
||||
if (!lua_istable (L, -1))
|
||||
{
|
||||
throw std::logic_error ("The class is not registered in LuaBridge");
|
||||
std::cerr << ("The class is not registered in LuaBridge");
|
||||
assert(true);
|
||||
}
|
||||
lua_setmetatable (L, -2);
|
||||
return ud;
|
||||
@@ -375,7 +377,8 @@ private:
|
||||
lua_rawgetp (L, LUA_REGISTRYINDEX, key);
|
||||
if (!lua_istable (L, -1))
|
||||
{
|
||||
throw std::logic_error ("The class is not registered in LuaBridge");
|
||||
std::cerr << ("The class is not registered in LuaBridge");
|
||||
assert(true);
|
||||
}
|
||||
lua_setmetatable (L, -2);
|
||||
}
|
||||
|
||||
219
3rd/SipHash/LICENSE_A2LLVM
Normal file
219
3rd/SipHash/LICENSE_A2LLVM
Normal file
@@ -0,0 +1,219 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
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.
|
||||
|
||||
|
||||
---- LLVM Exceptions to the Apache 2.0 License ----
|
||||
|
||||
As an exception, if, as a result of your compiling your source code, portions
|
||||
of this Software are embedded into an Object form of such source code, you
|
||||
may redistribute such embedded portions in such Object form without complying
|
||||
with the conditions of Sections 4(a), 4(b) and 4(d) of the License.
|
||||
|
||||
In addition, if you combine or link compiled forms of this Software with
|
||||
software that is licensed under the GPLv2 ("Combined Software") and if a
|
||||
court of competent jurisdiction determines that the patent provision (Section
|
||||
3), the indemnity provision (Section 9) or other Section of the License
|
||||
conflicts with the conditions of the GPLv2, you may retroactively and
|
||||
prospectively choose to deem waived or otherwise exclude such Section(s) of
|
||||
the License, but only in their entirety and only with respect to the Combined
|
||||
Software.
|
||||
|
||||
116
3rd/SipHash/LICENSE_CC0
Normal file
116
3rd/SipHash/LICENSE_CC0
Normal file
@@ -0,0 +1,116 @@
|
||||
CC0 1.0 Universal
|
||||
|
||||
Statement of Purpose
|
||||
|
||||
The laws of most jurisdictions throughout the world automatically confer
|
||||
exclusive Copyright and Related Rights (defined below) upon the creator and
|
||||
subsequent owner(s) (each and all, an "owner") of an original work of
|
||||
authorship and/or a database (each, a "Work").
|
||||
|
||||
Certain owners wish to permanently relinquish those rights to a Work for the
|
||||
purpose of contributing to a commons of creative, cultural and scientific
|
||||
works ("Commons") that the public can reliably and without fear of later
|
||||
claims of infringement build upon, modify, incorporate in other works, reuse
|
||||
and redistribute as freely as possible in any form whatsoever and for any
|
||||
purposes, including without limitation commercial purposes. These owners may
|
||||
contribute to the Commons to promote the ideal of a free culture and the
|
||||
further production of creative, cultural and scientific works, or to gain
|
||||
reputation or greater distribution for their Work in part through the use and
|
||||
efforts of others.
|
||||
|
||||
For these and/or other purposes and motivations, and without any expectation
|
||||
of additional consideration or compensation, the person associating CC0 with a
|
||||
Work (the "Affirmer"), to the extent that he or she is an owner of Copyright
|
||||
and Related Rights in the Work, voluntarily elects to apply CC0 to the Work
|
||||
and publicly distribute the Work under its terms, with knowledge of his or her
|
||||
Copyright and Related Rights in the Work and the meaning and intended legal
|
||||
effect of CC0 on those rights.
|
||||
|
||||
1. Copyright and Related Rights. A Work made available under CC0 may be
|
||||
protected by copyright and related or neighboring rights ("Copyright and
|
||||
Related Rights"). Copyright and Related Rights include, but are not limited
|
||||
to, the following:
|
||||
|
||||
i. the right to reproduce, adapt, distribute, perform, display, communicate,
|
||||
and translate a Work;
|
||||
|
||||
ii. moral rights retained by the original author(s) and/or performer(s);
|
||||
|
||||
iii. publicity and privacy rights pertaining to a person's image or likeness
|
||||
depicted in a Work;
|
||||
|
||||
iv. rights protecting against unfair competition in regards to a Work,
|
||||
subject to the limitations in paragraph 4(a), below;
|
||||
|
||||
v. rights protecting the extraction, dissemination, use and reuse of data in
|
||||
a Work;
|
||||
|
||||
vi. database rights (such as those arising under Directive 96/9/EC of the
|
||||
European Parliament and of the Council of 11 March 1996 on the legal
|
||||
protection of databases, and under any national implementation thereof,
|
||||
including any amended or successor version of such directive); and
|
||||
|
||||
vii. other similar, equivalent or corresponding rights throughout the world
|
||||
based on applicable law or treaty, and any national implementations thereof.
|
||||
|
||||
2. Waiver. To the greatest extent permitted by, but not in contravention of,
|
||||
applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and
|
||||
unconditionally waives, abandons, and surrenders all of Affirmer's Copyright
|
||||
and Related Rights and associated claims and causes of action, whether now
|
||||
known or unknown (including existing as well as future claims and causes of
|
||||
action), in the Work (i) in all territories worldwide, (ii) for the maximum
|
||||
duration provided by applicable law or treaty (including future time
|
||||
extensions), (iii) in any current or future medium and for any number of
|
||||
copies, and (iv) for any purpose whatsoever, including without limitation
|
||||
commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes
|
||||
the Waiver for the benefit of each member of the public at large and to the
|
||||
detriment of Affirmer's heirs and successors, fully intending that such Waiver
|
||||
shall not be subject to revocation, rescission, cancellation, termination, or
|
||||
any other legal or equitable action to disrupt the quiet enjoyment of the Work
|
||||
by the public as contemplated by Affirmer's express Statement of Purpose.
|
||||
|
||||
3. Public License Fallback. Should any part of the Waiver for any reason be
|
||||
judged legally invalid or ineffective under applicable law, then the Waiver
|
||||
shall be preserved to the maximum extent permitted taking into account
|
||||
Affirmer's express Statement of Purpose. In addition, to the extent the Waiver
|
||||
is so judged Affirmer hereby grants to each affected person a royalty-free,
|
||||
non transferable, non sublicensable, non exclusive, irrevocable and
|
||||
unconditional license to exercise Affirmer's Copyright and Related Rights in
|
||||
the Work (i) in all territories worldwide, (ii) for the maximum duration
|
||||
provided by applicable law or treaty (including future time extensions), (iii)
|
||||
in any current or future medium and for any number of copies, and (iv) for any
|
||||
purpose whatsoever, including without limitation commercial, advertising or
|
||||
promotional purposes (the "License"). The License shall be deemed effective as
|
||||
of the date CC0 was applied by Affirmer to the Work. Should any part of the
|
||||
License for any reason be judged legally invalid or ineffective under
|
||||
applicable law, such partial invalidity or ineffectiveness shall not
|
||||
invalidate the remainder of the License, and in such case Affirmer hereby
|
||||
affirms that he or she will not (i) exercise any of his or her remaining
|
||||
Copyright and Related Rights in the Work or (ii) assert any associated claims
|
||||
and causes of action with respect to the Work, in either case contrary to
|
||||
Affirmer's express Statement of Purpose.
|
||||
|
||||
4. Limitations and Disclaimers.
|
||||
|
||||
a. No trademark or patent rights held by Affirmer are waived, abandoned,
|
||||
surrendered, licensed or otherwise affected by this document.
|
||||
|
||||
b. Affirmer offers the Work as-is and makes no representations or warranties
|
||||
of any kind concerning the Work, express, implied, statutory or otherwise,
|
||||
including without limitation warranties of title, merchantability, fitness
|
||||
for a particular purpose, non infringement, or the absence of latent or
|
||||
other defects, accuracy, or the present or absence of errors, whether or not
|
||||
discoverable, all to the greatest extent permissible under applicable law.
|
||||
|
||||
c. Affirmer disclaims responsibility for clearing rights of other persons
|
||||
that may apply to the Work or any use thereof, including without limitation
|
||||
any person's Copyright and Related Rights in the Work. Further, Affirmer
|
||||
disclaims responsibility for obtaining any necessary consents, permissions
|
||||
or other rights required for any use of the Work.
|
||||
|
||||
d. Affirmer understands and acknowledges that Creative Commons is not a
|
||||
party to this document and has no duty or obligation with respect to this
|
||||
CC0 or use of the Work.
|
||||
|
||||
For more information, please see
|
||||
<http://creativecommons.org/publicdomain/zero/1.0/>
|
||||
7
3rd/SipHash/LICENSE_MIT
Normal file
7
3rd/SipHash/LICENSE_MIT
Normal file
@@ -0,0 +1,7 @@
|
||||
Copyright 2012-2024 JP Aumasson
|
||||
|
||||
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.
|
||||
166
3rd/SipHash/halfsiphash.c
Normal file
166
3rd/SipHash/halfsiphash.c
Normal file
@@ -0,0 +1,166 @@
|
||||
|
||||
/*
|
||||
SipHash reference C implementation
|
||||
|
||||
Copyright (c) 2016 Jean-Philippe Aumasson <jeanphilippe.aumasson@gmail.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.
|
||||
|
||||
You should have received a copy of the CC0 Public Domain Dedication along
|
||||
with
|
||||
this software. If not, see
|
||||
<http://creativecommons.org/publicdomain/zero/1.0/>.
|
||||
*/
|
||||
#include "halfsiphash.h"
|
||||
#include <assert.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
/* default: SipHash-2-4 */
|
||||
#ifndef cROUNDS
|
||||
#define cROUNDS 2
|
||||
#endif
|
||||
#ifndef dROUNDS
|
||||
#define dROUNDS 4
|
||||
#endif
|
||||
|
||||
#define ROTL(x, b) (uint32_t)(((x) << (b)) | ((x) >> (32 - (b))))
|
||||
|
||||
#define U32TO8_LE(p, v) \
|
||||
(p)[0] = (uint8_t)((v)); \
|
||||
(p)[1] = (uint8_t)((v) >> 8); \
|
||||
(p)[2] = (uint8_t)((v) >> 16); \
|
||||
(p)[3] = (uint8_t)((v) >> 24);
|
||||
|
||||
#define U8TO32_LE(p) \
|
||||
(((uint32_t)((p)[0])) | ((uint32_t)((p)[1]) << 8) | \
|
||||
((uint32_t)((p)[2]) << 16) | ((uint32_t)((p)[3]) << 24))
|
||||
|
||||
#define SIPROUND \
|
||||
do { \
|
||||
v0 += v1; \
|
||||
v1 = ROTL(v1, 5); \
|
||||
v1 ^= v0; \
|
||||
v0 = ROTL(v0, 16); \
|
||||
v2 += v3; \
|
||||
v3 = ROTL(v3, 8); \
|
||||
v3 ^= v2; \
|
||||
v0 += v3; \
|
||||
v3 = ROTL(v3, 7); \
|
||||
v3 ^= v0; \
|
||||
v2 += v1; \
|
||||
v1 = ROTL(v1, 13); \
|
||||
v1 ^= v2; \
|
||||
v2 = ROTL(v2, 16); \
|
||||
} while (0)
|
||||
|
||||
|
||||
#ifdef DEBUG_SIPHASH
|
||||
#include <stdio.h>
|
||||
|
||||
#define TRACE \
|
||||
do { \
|
||||
printf("(%3zu) v0 %08" PRIx32 "\n", inlen, v0); \
|
||||
printf("(%3zu) v1 %08" PRIx32 "\n", inlen, v1); \
|
||||
printf("(%3zu) v2 %08" PRIx32 "\n", inlen, v2); \
|
||||
printf("(%3zu) v3 %08" PRIx32 "\n", inlen, v3); \
|
||||
} while (0)
|
||||
#else
|
||||
#define TRACE
|
||||
#endif
|
||||
|
||||
/*
|
||||
Computes a SipHash value
|
||||
*in: pointer to input data (read-only)
|
||||
inlen: input data length in bytes (any size_t value)
|
||||
*k: pointer to the key data (read-only), must be 8 bytes
|
||||
*out: pointer to output data (write-only), outlen bytes must be allocated
|
||||
outlen: length of the output in bytes, must be 4 or 8
|
||||
*/
|
||||
int halfsiphash(const void *in, const size_t inlen, const void *k, uint8_t *out,
|
||||
const size_t outlen) {
|
||||
|
||||
const unsigned char *ni = (const unsigned char *)in;
|
||||
const unsigned char *kk = (const unsigned char *)k;
|
||||
|
||||
assert((outlen == 4) || (outlen == 8));
|
||||
uint32_t v0 = 0;
|
||||
uint32_t v1 = 0;
|
||||
uint32_t v2 = UINT32_C(0x6c796765);
|
||||
uint32_t v3 = UINT32_C(0x74656462);
|
||||
uint32_t k0 = U8TO32_LE(kk);
|
||||
uint32_t k1 = U8TO32_LE(kk + 4);
|
||||
uint32_t m;
|
||||
int i;
|
||||
const unsigned char *end = ni + inlen - (inlen % sizeof(uint32_t));
|
||||
const int left = inlen & 3;
|
||||
uint32_t b = ((uint32_t)inlen) << 24;
|
||||
v3 ^= k1;
|
||||
v2 ^= k0;
|
||||
v1 ^= k1;
|
||||
v0 ^= k0;
|
||||
|
||||
if (outlen == 8)
|
||||
v1 ^= 0xee;
|
||||
|
||||
for (; ni != end; ni += 4) {
|
||||
m = U8TO32_LE(ni);
|
||||
v3 ^= m;
|
||||
|
||||
TRACE;
|
||||
for (i = 0; i < cROUNDS; ++i)
|
||||
SIPROUND;
|
||||
|
||||
v0 ^= m;
|
||||
}
|
||||
|
||||
switch (left) {
|
||||
case 3:
|
||||
b |= ((uint32_t)ni[2]) << 16;
|
||||
/* FALLTHRU */
|
||||
case 2:
|
||||
b |= ((uint32_t)ni[1]) << 8;
|
||||
/* FALLTHRU */
|
||||
case 1:
|
||||
b |= ((uint32_t)ni[0]);
|
||||
break;
|
||||
case 0:
|
||||
break;
|
||||
}
|
||||
|
||||
v3 ^= b;
|
||||
|
||||
TRACE;
|
||||
for (i = 0; i < cROUNDS; ++i)
|
||||
SIPROUND;
|
||||
|
||||
v0 ^= b;
|
||||
|
||||
if (outlen == 8)
|
||||
v2 ^= 0xee;
|
||||
else
|
||||
v2 ^= 0xff;
|
||||
|
||||
TRACE;
|
||||
for (i = 0; i < dROUNDS; ++i)
|
||||
SIPROUND;
|
||||
|
||||
b = v1 ^ v3;
|
||||
U32TO8_LE(out, b);
|
||||
|
||||
if (outlen == 4)
|
||||
return 0;
|
||||
|
||||
v1 ^= 0xdd;
|
||||
|
||||
TRACE;
|
||||
for (i = 0; i < dROUNDS; ++i)
|
||||
SIPROUND;
|
||||
|
||||
b = v1 ^ v3;
|
||||
U32TO8_LE(out + 4, b);
|
||||
|
||||
return 0;
|
||||
}
|
||||
34
3rd/SipHash/halfsiphash.h
Normal file
34
3rd/SipHash/halfsiphash.h
Normal file
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
SipHash reference C implementation
|
||||
|
||||
Copyright (c) 2012-2021 Jean-Philippe Aumasson
|
||||
<jeanphilippe.aumasson@gmail.com>
|
||||
Copyright (c) 2012-2014 Daniel J. Bernstein <djb@cr.yp.to>
|
||||
|
||||
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.
|
||||
|
||||
You should have received a copy of the CC0 Public Domain Dedication along
|
||||
with
|
||||
this software. If not, see
|
||||
<http://creativecommons.org/publicdomain/zero/1.0/>.
|
||||
*/
|
||||
|
||||
#ifndef HALFSIPHASH_H
|
||||
#define HALFSIPHASH_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#if defined(__cplusplus)
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
int halfsiphash(const void * in, const size_t inlen, const void * k, uint8_t * out, const size_t outlen);
|
||||
|
||||
#if defined(__cplusplus)
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
185
3rd/SipHash/siphash.c
Normal file
185
3rd/SipHash/siphash.c
Normal file
@@ -0,0 +1,185 @@
|
||||
/*
|
||||
SipHash reference C implementation
|
||||
|
||||
Copyright (c) 2012-2022 Jean-Philippe Aumasson
|
||||
<jeanphilippe.aumasson@gmail.com>
|
||||
Copyright (c) 2012-2014 Daniel J. Bernstein <djb@cr.yp.to>
|
||||
|
||||
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.
|
||||
|
||||
You should have received a copy of the CC0 Public Domain Dedication along
|
||||
with
|
||||
this software. If not, see
|
||||
<http://creativecommons.org/publicdomain/zero/1.0/>.
|
||||
*/
|
||||
|
||||
#include "siphash.h"
|
||||
#include <assert.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
/* default: SipHash-2-4 */
|
||||
#ifndef cROUNDS
|
||||
#define cROUNDS 2
|
||||
#endif
|
||||
#ifndef dROUNDS
|
||||
#define dROUNDS 4
|
||||
#endif
|
||||
|
||||
#define ROTL(x, b) (uint64_t)(((x) << (b)) | ((x) >> (64 - (b))))
|
||||
|
||||
#define U32TO8_LE(p, v) \
|
||||
(p)[0] = (uint8_t)((v)); \
|
||||
(p)[1] = (uint8_t)((v) >> 8); \
|
||||
(p)[2] = (uint8_t)((v) >> 16); \
|
||||
(p)[3] = (uint8_t)((v) >> 24);
|
||||
|
||||
#define U64TO8_LE(p, v) \
|
||||
U32TO8_LE((p), (uint32_t)((v))); \
|
||||
U32TO8_LE((p) + 4, (uint32_t)((v) >> 32));
|
||||
|
||||
#define U8TO64_LE(p) \
|
||||
(((uint64_t)((p)[0])) | ((uint64_t)((p)[1]) << 8) | \
|
||||
((uint64_t)((p)[2]) << 16) | ((uint64_t)((p)[3]) << 24) | \
|
||||
((uint64_t)((p)[4]) << 32) | ((uint64_t)((p)[5]) << 40) | \
|
||||
((uint64_t)((p)[6]) << 48) | ((uint64_t)((p)[7]) << 56))
|
||||
|
||||
#define SIPROUND \
|
||||
do { \
|
||||
v0 += v1; \
|
||||
v1 = ROTL(v1, 13); \
|
||||
v1 ^= v0; \
|
||||
v0 = ROTL(v0, 32); \
|
||||
v2 += v3; \
|
||||
v3 = ROTL(v3, 16); \
|
||||
v3 ^= v2; \
|
||||
v0 += v3; \
|
||||
v3 = ROTL(v3, 21); \
|
||||
v3 ^= v0; \
|
||||
v2 += v1; \
|
||||
v1 = ROTL(v1, 17); \
|
||||
v1 ^= v2; \
|
||||
v2 = ROTL(v2, 32); \
|
||||
} while (0)
|
||||
|
||||
#ifdef DEBUG_SIPHASH
|
||||
#include <stdio.h>
|
||||
|
||||
#define TRACE \
|
||||
do { \
|
||||
printf("(%3zu) v0 %016" PRIx64 "\n", inlen, v0); \
|
||||
printf("(%3zu) v1 %016" PRIx64 "\n", inlen, v1); \
|
||||
printf("(%3zu) v2 %016" PRIx64 "\n", inlen, v2); \
|
||||
printf("(%3zu) v3 %016" PRIx64 "\n", inlen, v3); \
|
||||
} while (0)
|
||||
#else
|
||||
#define TRACE
|
||||
#endif
|
||||
|
||||
/*
|
||||
Computes a SipHash value
|
||||
*in: pointer to input data (read-only)
|
||||
inlen: input data length in bytes (any size_t value)
|
||||
*k: pointer to the key data (read-only), must be 16 bytes
|
||||
*out: pointer to output data (write-only), outlen bytes must be allocated
|
||||
outlen: length of the output in bytes, must be 8 or 16
|
||||
*/
|
||||
int siphash(const void *in, const size_t inlen, const void *k, uint8_t *out,
|
||||
const size_t outlen) {
|
||||
|
||||
const unsigned char *ni = (const unsigned char *)in;
|
||||
const unsigned char *kk = (const unsigned char *)k;
|
||||
|
||||
assert((outlen == 8) || (outlen == 16));
|
||||
uint64_t v0 = UINT64_C(0x736f6d6570736575);
|
||||
uint64_t v1 = UINT64_C(0x646f72616e646f6d);
|
||||
uint64_t v2 = UINT64_C(0x6c7967656e657261);
|
||||
uint64_t v3 = UINT64_C(0x7465646279746573);
|
||||
uint64_t k0 = U8TO64_LE(kk);
|
||||
uint64_t k1 = U8TO64_LE(kk + 8);
|
||||
uint64_t m;
|
||||
int i;
|
||||
const unsigned char *end = ni + inlen - (inlen % sizeof(uint64_t));
|
||||
const int left = inlen & 7;
|
||||
uint64_t b = ((uint64_t)inlen) << 56;
|
||||
v3 ^= k1;
|
||||
v2 ^= k0;
|
||||
v1 ^= k1;
|
||||
v0 ^= k0;
|
||||
|
||||
if (outlen == 16)
|
||||
v1 ^= 0xee;
|
||||
|
||||
for (; ni != end; ni += 8) {
|
||||
m = U8TO64_LE(ni);
|
||||
v3 ^= m;
|
||||
|
||||
TRACE;
|
||||
for (i = 0; i < cROUNDS; ++i)
|
||||
SIPROUND;
|
||||
|
||||
v0 ^= m;
|
||||
}
|
||||
|
||||
switch (left) {
|
||||
case 7:
|
||||
b |= ((uint64_t)ni[6]) << 48;
|
||||
/* FALLTHRU */
|
||||
case 6:
|
||||
b |= ((uint64_t)ni[5]) << 40;
|
||||
/* FALLTHRU */
|
||||
case 5:
|
||||
b |= ((uint64_t)ni[4]) << 32;
|
||||
/* FALLTHRU */
|
||||
case 4:
|
||||
b |= ((uint64_t)ni[3]) << 24;
|
||||
/* FALLTHRU */
|
||||
case 3:
|
||||
b |= ((uint64_t)ni[2]) << 16;
|
||||
/* FALLTHRU */
|
||||
case 2:
|
||||
b |= ((uint64_t)ni[1]) << 8;
|
||||
/* FALLTHRU */
|
||||
case 1:
|
||||
b |= ((uint64_t)ni[0]);
|
||||
break;
|
||||
case 0:
|
||||
break;
|
||||
}
|
||||
|
||||
v3 ^= b;
|
||||
|
||||
TRACE;
|
||||
for (i = 0; i < cROUNDS; ++i)
|
||||
SIPROUND;
|
||||
|
||||
v0 ^= b;
|
||||
|
||||
if (outlen == 16)
|
||||
v2 ^= 0xee;
|
||||
else
|
||||
v2 ^= 0xff;
|
||||
|
||||
TRACE;
|
||||
for (i = 0; i < dROUNDS; ++i)
|
||||
SIPROUND;
|
||||
|
||||
b = v0 ^ v1 ^ v2 ^ v3;
|
||||
U64TO8_LE(out, b);
|
||||
|
||||
if (outlen == 8)
|
||||
return 0;
|
||||
|
||||
v1 ^= 0xdd;
|
||||
|
||||
TRACE;
|
||||
for (i = 0; i < dROUNDS; ++i)
|
||||
SIPROUND;
|
||||
|
||||
b = v0 ^ v1 ^ v2 ^ v3;
|
||||
U64TO8_LE(out + 8, b);
|
||||
|
||||
return 0;
|
||||
}
|
||||
34
3rd/SipHash/siphash.h
Normal file
34
3rd/SipHash/siphash.h
Normal file
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
SipHash reference C implementation
|
||||
|
||||
Copyright (c) 2012-2021 Jean-Philippe Aumasson
|
||||
<jeanphilippe.aumasson@gmail.com>
|
||||
Copyright (c) 2012-2014 Daniel J. Bernstein <djb@cr.yp.to>
|
||||
|
||||
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.
|
||||
|
||||
You should have received a copy of the CC0 Public Domain Dedication along
|
||||
with
|
||||
this software. If not, see
|
||||
<http://creativecommons.org/publicdomain/zero/1.0/>.
|
||||
*/
|
||||
|
||||
#ifndef SIPHASH_H
|
||||
#define SIPHASH_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#if defined(__cplusplus)
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
int siphash(const void * in, const size_t inlen, const void * k, uint8_t * out, const size_t outlen);
|
||||
|
||||
#if defined(__cplusplus)
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
2826
3rd/SipHash/vectors.h
Normal file
2826
3rd/SipHash/vectors.h
Normal file
@@ -0,0 +1,2826 @@
|
||||
#include <stdint.h>
|
||||
|
||||
const uint8_t vectors_sip64[64][8] = {
|
||||
{
|
||||
0x31,
|
||||
0x0e,
|
||||
0x0e,
|
||||
0xdd,
|
||||
0x47,
|
||||
0xdb,
|
||||
0x6f,
|
||||
0x72,
|
||||
},
|
||||
{
|
||||
0xfd,
|
||||
0x67,
|
||||
0xdc,
|
||||
0x93,
|
||||
0xc5,
|
||||
0x39,
|
||||
0xf8,
|
||||
0x74,
|
||||
},
|
||||
{
|
||||
0x5a,
|
||||
0x4f,
|
||||
0xa9,
|
||||
0xd9,
|
||||
0x09,
|
||||
0x80,
|
||||
0x6c,
|
||||
0x0d,
|
||||
},
|
||||
{
|
||||
0x2d,
|
||||
0x7e,
|
||||
0xfb,
|
||||
0xd7,
|
||||
0x96,
|
||||
0x66,
|
||||
0x67,
|
||||
0x85,
|
||||
},
|
||||
{
|
||||
0xb7,
|
||||
0x87,
|
||||
0x71,
|
||||
0x27,
|
||||
0xe0,
|
||||
0x94,
|
||||
0x27,
|
||||
0xcf,
|
||||
},
|
||||
{
|
||||
0x8d,
|
||||
0xa6,
|
||||
0x99,
|
||||
0xcd,
|
||||
0x64,
|
||||
0x55,
|
||||
0x76,
|
||||
0x18,
|
||||
},
|
||||
{
|
||||
0xce,
|
||||
0xe3,
|
||||
0xfe,
|
||||
0x58,
|
||||
0x6e,
|
||||
0x46,
|
||||
0xc9,
|
||||
0xcb,
|
||||
},
|
||||
{
|
||||
0x37,
|
||||
0xd1,
|
||||
0x01,
|
||||
0x8b,
|
||||
0xf5,
|
||||
0x00,
|
||||
0x02,
|
||||
0xab,
|
||||
},
|
||||
{
|
||||
0x62,
|
||||
0x24,
|
||||
0x93,
|
||||
0x9a,
|
||||
0x79,
|
||||
0xf5,
|
||||
0xf5,
|
||||
0x93,
|
||||
},
|
||||
{
|
||||
0xb0,
|
||||
0xe4,
|
||||
0xa9,
|
||||
0x0b,
|
||||
0xdf,
|
||||
0x82,
|
||||
0x00,
|
||||
0x9e,
|
||||
},
|
||||
{
|
||||
0xf3,
|
||||
0xb9,
|
||||
0xdd,
|
||||
0x94,
|
||||
0xc5,
|
||||
0xbb,
|
||||
0x5d,
|
||||
0x7a,
|
||||
},
|
||||
{
|
||||
0xa7,
|
||||
0xad,
|
||||
0x6b,
|
||||
0x22,
|
||||
0x46,
|
||||
0x2f,
|
||||
0xb3,
|
||||
0xf4,
|
||||
},
|
||||
{
|
||||
0xfb,
|
||||
0xe5,
|
||||
0x0e,
|
||||
0x86,
|
||||
0xbc,
|
||||
0x8f,
|
||||
0x1e,
|
||||
0x75,
|
||||
},
|
||||
{
|
||||
0x90,
|
||||
0x3d,
|
||||
0x84,
|
||||
0xc0,
|
||||
0x27,
|
||||
0x56,
|
||||
0xea,
|
||||
0x14,
|
||||
},
|
||||
{
|
||||
0xee,
|
||||
0xf2,
|
||||
0x7a,
|
||||
0x8e,
|
||||
0x90,
|
||||
0xca,
|
||||
0x23,
|
||||
0xf7,
|
||||
},
|
||||
{
|
||||
0xe5,
|
||||
0x45,
|
||||
0xbe,
|
||||
0x49,
|
||||
0x61,
|
||||
0xca,
|
||||
0x29,
|
||||
0xa1,
|
||||
},
|
||||
{
|
||||
0xdb,
|
||||
0x9b,
|
||||
0xc2,
|
||||
0x57,
|
||||
0x7f,
|
||||
0xcc,
|
||||
0x2a,
|
||||
0x3f,
|
||||
},
|
||||
{
|
||||
0x94,
|
||||
0x47,
|
||||
0xbe,
|
||||
0x2c,
|
||||
0xf5,
|
||||
0xe9,
|
||||
0x9a,
|
||||
0x69,
|
||||
},
|
||||
{
|
||||
0x9c,
|
||||
0xd3,
|
||||
0x8d,
|
||||
0x96,
|
||||
0xf0,
|
||||
0xb3,
|
||||
0xc1,
|
||||
0x4b,
|
||||
},
|
||||
{
|
||||
0xbd,
|
||||
0x61,
|
||||
0x79,
|
||||
0xa7,
|
||||
0x1d,
|
||||
0xc9,
|
||||
0x6d,
|
||||
0xbb,
|
||||
},
|
||||
{
|
||||
0x98,
|
||||
0xee,
|
||||
0xa2,
|
||||
0x1a,
|
||||
0xf2,
|
||||
0x5c,
|
||||
0xd6,
|
||||
0xbe,
|
||||
},
|
||||
{
|
||||
0xc7,
|
||||
0x67,
|
||||
0x3b,
|
||||
0x2e,
|
||||
0xb0,
|
||||
0xcb,
|
||||
0xf2,
|
||||
0xd0,
|
||||
},
|
||||
{
|
||||
0x88,
|
||||
0x3e,
|
||||
0xa3,
|
||||
0xe3,
|
||||
0x95,
|
||||
0x67,
|
||||
0x53,
|
||||
0x93,
|
||||
},
|
||||
{
|
||||
0xc8,
|
||||
0xce,
|
||||
0x5c,
|
||||
0xcd,
|
||||
0x8c,
|
||||
0x03,
|
||||
0x0c,
|
||||
0xa8,
|
||||
},
|
||||
{
|
||||
0x94,
|
||||
0xaf,
|
||||
0x49,
|
||||
0xf6,
|
||||
0xc6,
|
||||
0x50,
|
||||
0xad,
|
||||
0xb8,
|
||||
},
|
||||
{
|
||||
0xea,
|
||||
0xb8,
|
||||
0x85,
|
||||
0x8a,
|
||||
0xde,
|
||||
0x92,
|
||||
0xe1,
|
||||
0xbc,
|
||||
},
|
||||
{
|
||||
0xf3,
|
||||
0x15,
|
||||
0xbb,
|
||||
0x5b,
|
||||
0xb8,
|
||||
0x35,
|
||||
0xd8,
|
||||
0x17,
|
||||
},
|
||||
{
|
||||
0xad,
|
||||
0xcf,
|
||||
0x6b,
|
||||
0x07,
|
||||
0x63,
|
||||
0x61,
|
||||
0x2e,
|
||||
0x2f,
|
||||
},
|
||||
{
|
||||
0xa5,
|
||||
0xc9,
|
||||
0x1d,
|
||||
0xa7,
|
||||
0xac,
|
||||
0xaa,
|
||||
0x4d,
|
||||
0xde,
|
||||
},
|
||||
{
|
||||
0x71,
|
||||
0x65,
|
||||
0x95,
|
||||
0x87,
|
||||
0x66,
|
||||
0x50,
|
||||
0xa2,
|
||||
0xa6,
|
||||
},
|
||||
{
|
||||
0x28,
|
||||
0xef,
|
||||
0x49,
|
||||
0x5c,
|
||||
0x53,
|
||||
0xa3,
|
||||
0x87,
|
||||
0xad,
|
||||
},
|
||||
{
|
||||
0x42,
|
||||
0xc3,
|
||||
0x41,
|
||||
0xd8,
|
||||
0xfa,
|
||||
0x92,
|
||||
0xd8,
|
||||
0x32,
|
||||
},
|
||||
{
|
||||
0xce,
|
||||
0x7c,
|
||||
0xf2,
|
||||
0x72,
|
||||
0x2f,
|
||||
0x51,
|
||||
0x27,
|
||||
0x71,
|
||||
},
|
||||
{
|
||||
0xe3,
|
||||
0x78,
|
||||
0x59,
|
||||
0xf9,
|
||||
0x46,
|
||||
0x23,
|
||||
0xf3,
|
||||
0xa7,
|
||||
},
|
||||
{
|
||||
0x38,
|
||||
0x12,
|
||||
0x05,
|
||||
0xbb,
|
||||
0x1a,
|
||||
0xb0,
|
||||
0xe0,
|
||||
0x12,
|
||||
},
|
||||
{
|
||||
0xae,
|
||||
0x97,
|
||||
0xa1,
|
||||
0x0f,
|
||||
0xd4,
|
||||
0x34,
|
||||
0xe0,
|
||||
0x15,
|
||||
},
|
||||
{
|
||||
0xb4,
|
||||
0xa3,
|
||||
0x15,
|
||||
0x08,
|
||||
0xbe,
|
||||
0xff,
|
||||
0x4d,
|
||||
0x31,
|
||||
},
|
||||
{
|
||||
0x81,
|
||||
0x39,
|
||||
0x62,
|
||||
0x29,
|
||||
0xf0,
|
||||
0x90,
|
||||
0x79,
|
||||
0x02,
|
||||
},
|
||||
{
|
||||
0x4d,
|
||||
0x0c,
|
||||
0xf4,
|
||||
0x9e,
|
||||
0xe5,
|
||||
0xd4,
|
||||
0xdc,
|
||||
0xca,
|
||||
},
|
||||
{
|
||||
0x5c,
|
||||
0x73,
|
||||
0x33,
|
||||
0x6a,
|
||||
0x76,
|
||||
0xd8,
|
||||
0xbf,
|
||||
0x9a,
|
||||
},
|
||||
{
|
||||
0xd0,
|
||||
0xa7,
|
||||
0x04,
|
||||
0x53,
|
||||
0x6b,
|
||||
0xa9,
|
||||
0x3e,
|
||||
0x0e,
|
||||
},
|
||||
{
|
||||
0x92,
|
||||
0x59,
|
||||
0x58,
|
||||
0xfc,
|
||||
0xd6,
|
||||
0x42,
|
||||
0x0c,
|
||||
0xad,
|
||||
},
|
||||
{
|
||||
0xa9,
|
||||
0x15,
|
||||
0xc2,
|
||||
0x9b,
|
||||
0xc8,
|
||||
0x06,
|
||||
0x73,
|
||||
0x18,
|
||||
},
|
||||
{
|
||||
0x95,
|
||||
0x2b,
|
||||
0x79,
|
||||
0xf3,
|
||||
0xbc,
|
||||
0x0a,
|
||||
0xa6,
|
||||
0xd4,
|
||||
},
|
||||
{
|
||||
0xf2,
|
||||
0x1d,
|
||||
0xf2,
|
||||
0xe4,
|
||||
0x1d,
|
||||
0x45,
|
||||
0x35,
|
||||
0xf9,
|
||||
},
|
||||
{
|
||||
0x87,
|
||||
0x57,
|
||||
0x75,
|
||||
0x19,
|
||||
0x04,
|
||||
0x8f,
|
||||
0x53,
|
||||
0xa9,
|
||||
},
|
||||
{
|
||||
0x10,
|
||||
0xa5,
|
||||
0x6c,
|
||||
0xf5,
|
||||
0xdf,
|
||||
0xcd,
|
||||
0x9a,
|
||||
0xdb,
|
||||
},
|
||||
{
|
||||
0xeb,
|
||||
0x75,
|
||||
0x09,
|
||||
0x5c,
|
||||
0xcd,
|
||||
0x98,
|
||||
0x6c,
|
||||
0xd0,
|
||||
},
|
||||
{
|
||||
0x51,
|
||||
0xa9,
|
||||
0xcb,
|
||||
0x9e,
|
||||
0xcb,
|
||||
0xa3,
|
||||
0x12,
|
||||
0xe6,
|
||||
},
|
||||
{
|
||||
0x96,
|
||||
0xaf,
|
||||
0xad,
|
||||
0xfc,
|
||||
0x2c,
|
||||
0xe6,
|
||||
0x66,
|
||||
0xc7,
|
||||
},
|
||||
{
|
||||
0x72,
|
||||
0xfe,
|
||||
0x52,
|
||||
0x97,
|
||||
0x5a,
|
||||
0x43,
|
||||
0x64,
|
||||
0xee,
|
||||
},
|
||||
{
|
||||
0x5a,
|
||||
0x16,
|
||||
0x45,
|
||||
0xb2,
|
||||
0x76,
|
||||
0xd5,
|
||||
0x92,
|
||||
0xa1,
|
||||
},
|
||||
{
|
||||
0xb2,
|
||||
0x74,
|
||||
0xcb,
|
||||
0x8e,
|
||||
0xbf,
|
||||
0x87,
|
||||
0x87,
|
||||
0x0a,
|
||||
},
|
||||
{
|
||||
0x6f,
|
||||
0x9b,
|
||||
0xb4,
|
||||
0x20,
|
||||
0x3d,
|
||||
0xe7,
|
||||
0xb3,
|
||||
0x81,
|
||||
},
|
||||
{
|
||||
0xea,
|
||||
0xec,
|
||||
0xb2,
|
||||
0xa3,
|
||||
0x0b,
|
||||
0x22,
|
||||
0xa8,
|
||||
0x7f,
|
||||
},
|
||||
{
|
||||
0x99,
|
||||
0x24,
|
||||
0xa4,
|
||||
0x3c,
|
||||
0xc1,
|
||||
0x31,
|
||||
0x57,
|
||||
0x24,
|
||||
},
|
||||
{
|
||||
0xbd,
|
||||
0x83,
|
||||
0x8d,
|
||||
0x3a,
|
||||
0xaf,
|
||||
0xbf,
|
||||
0x8d,
|
||||
0xb7,
|
||||
},
|
||||
{
|
||||
0x0b,
|
||||
0x1a,
|
||||
0x2a,
|
||||
0x32,
|
||||
0x65,
|
||||
0xd5,
|
||||
0x1a,
|
||||
0xea,
|
||||
},
|
||||
{
|
||||
0x13,
|
||||
0x50,
|
||||
0x79,
|
||||
0xa3,
|
||||
0x23,
|
||||
0x1c,
|
||||
0xe6,
|
||||
0x60,
|
||||
},
|
||||
{
|
||||
0x93,
|
||||
0x2b,
|
||||
0x28,
|
||||
0x46,
|
||||
0xe4,
|
||||
0xd7,
|
||||
0x06,
|
||||
0x66,
|
||||
},
|
||||
{
|
||||
0xe1,
|
||||
0x91,
|
||||
0x5f,
|
||||
0x5c,
|
||||
0xb1,
|
||||
0xec,
|
||||
0xa4,
|
||||
0x6c,
|
||||
},
|
||||
{
|
||||
0xf3,
|
||||
0x25,
|
||||
0x96,
|
||||
0x5c,
|
||||
0xa1,
|
||||
0x6d,
|
||||
0x62,
|
||||
0x9f,
|
||||
},
|
||||
{
|
||||
0x57,
|
||||
0x5f,
|
||||
0xf2,
|
||||
0x8e,
|
||||
0x60,
|
||||
0x38,
|
||||
0x1b,
|
||||
0xe5,
|
||||
},
|
||||
{
|
||||
0x72,
|
||||
0x45,
|
||||
0x06,
|
||||
0xeb,
|
||||
0x4c,
|
||||
0x32,
|
||||
0x8a,
|
||||
0x95,
|
||||
},
|
||||
};
|
||||
const uint8_t vectors_sip128[64][16] = {
|
||||
{
|
||||
0xa3,
|
||||
0x81,
|
||||
0x7f,
|
||||
0x04,
|
||||
0xba,
|
||||
0x25,
|
||||
0xa8,
|
||||
0xe6,
|
||||
0x6d,
|
||||
0xf6,
|
||||
0x72,
|
||||
0x14,
|
||||
0xc7,
|
||||
0x55,
|
||||
0x02,
|
||||
0x93,
|
||||
},
|
||||
{
|
||||
0xda,
|
||||
0x87,
|
||||
0xc1,
|
||||
0xd8,
|
||||
0x6b,
|
||||
0x99,
|
||||
0xaf,
|
||||
0x44,
|
||||
0x34,
|
||||
0x76,
|
||||
0x59,
|
||||
0x11,
|
||||
0x9b,
|
||||
0x22,
|
||||
0xfc,
|
||||
0x45,
|
||||
},
|
||||
{
|
||||
0x81,
|
||||
0x77,
|
||||
0x22,
|
||||
0x8d,
|
||||
0xa4,
|
||||
0xa4,
|
||||
0x5d,
|
||||
0xc7,
|
||||
0xfc,
|
||||
0xa3,
|
||||
0x8b,
|
||||
0xde,
|
||||
0xf6,
|
||||
0x0a,
|
||||
0xff,
|
||||
0xe4,
|
||||
},
|
||||
{
|
||||
0x9c,
|
||||
0x70,
|
||||
0xb6,
|
||||
0x0c,
|
||||
0x52,
|
||||
0x67,
|
||||
0xa9,
|
||||
0x4e,
|
||||
0x5f,
|
||||
0x33,
|
||||
0xb6,
|
||||
0xb0,
|
||||
0x29,
|
||||
0x85,
|
||||
0xed,
|
||||
0x51,
|
||||
},
|
||||
{
|
||||
0xf8,
|
||||
0x81,
|
||||
0x64,
|
||||
0xc1,
|
||||
0x2d,
|
||||
0x9c,
|
||||
0x8f,
|
||||
0xaf,
|
||||
0x7d,
|
||||
0x0f,
|
||||
0x6e,
|
||||
0x7c,
|
||||
0x7b,
|
||||
0xcd,
|
||||
0x55,
|
||||
0x79,
|
||||
},
|
||||
{
|
||||
0x13,
|
||||
0x68,
|
||||
0x87,
|
||||
0x59,
|
||||
0x80,
|
||||
0x77,
|
||||
0x6f,
|
||||
0x88,
|
||||
0x54,
|
||||
0x52,
|
||||
0x7a,
|
||||
0x07,
|
||||
0x69,
|
||||
0x0e,
|
||||
0x96,
|
||||
0x27,
|
||||
},
|
||||
{
|
||||
0x14,
|
||||
0xee,
|
||||
0xca,
|
||||
0x33,
|
||||
0x8b,
|
||||
0x20,
|
||||
0x86,
|
||||
0x13,
|
||||
0x48,
|
||||
0x5e,
|
||||
0xa0,
|
||||
0x30,
|
||||
0x8f,
|
||||
0xd7,
|
||||
0xa1,
|
||||
0x5e,
|
||||
},
|
||||
{
|
||||
0xa1,
|
||||
0xf1,
|
||||
0xeb,
|
||||
0xbe,
|
||||
0xd8,
|
||||
0xdb,
|
||||
0xc1,
|
||||
0x53,
|
||||
0xc0,
|
||||
0xb8,
|
||||
0x4a,
|
||||
0xa6,
|
||||
0x1f,
|
||||
0xf0,
|
||||
0x82,
|
||||
0x39,
|
||||
},
|
||||
{
|
||||
0x3b,
|
||||
0x62,
|
||||
0xa9,
|
||||
0xba,
|
||||
0x62,
|
||||
0x58,
|
||||
0xf5,
|
||||
0x61,
|
||||
0x0f,
|
||||
0x83,
|
||||
0xe2,
|
||||
0x64,
|
||||
0xf3,
|
||||
0x14,
|
||||
0x97,
|
||||
0xb4,
|
||||
},
|
||||
{
|
||||
0x26,
|
||||
0x44,
|
||||
0x99,
|
||||
0x06,
|
||||
0x0a,
|
||||
0xd9,
|
||||
0xba,
|
||||
0xab,
|
||||
0xc4,
|
||||
0x7f,
|
||||
0x8b,
|
||||
0x02,
|
||||
0xbb,
|
||||
0x6d,
|
||||
0x71,
|
||||
0xed,
|
||||
},
|
||||
{
|
||||
0x00,
|
||||
0x11,
|
||||
0x0d,
|
||||
0xc3,
|
||||
0x78,
|
||||
0x14,
|
||||
0x69,
|
||||
0x56,
|
||||
0xc9,
|
||||
0x54,
|
||||
0x47,
|
||||
0xd3,
|
||||
0xf3,
|
||||
0xd0,
|
||||
0xfb,
|
||||
0xba,
|
||||
},
|
||||
{
|
||||
0x01,
|
||||
0x51,
|
||||
0xc5,
|
||||
0x68,
|
||||
0x38,
|
||||
0x6b,
|
||||
0x66,
|
||||
0x77,
|
||||
0xa2,
|
||||
0xb4,
|
||||
0xdc,
|
||||
0x6f,
|
||||
0x81,
|
||||
0xe5,
|
||||
0xdc,
|
||||
0x18,
|
||||
},
|
||||
{
|
||||
0xd6,
|
||||
0x26,
|
||||
0xb2,
|
||||
0x66,
|
||||
0x90,
|
||||
0x5e,
|
||||
0xf3,
|
||||
0x58,
|
||||
0x82,
|
||||
0x63,
|
||||
0x4d,
|
||||
0xf6,
|
||||
0x85,
|
||||
0x32,
|
||||
0xc1,
|
||||
0x25,
|
||||
},
|
||||
{
|
||||
0x98,
|
||||
0x69,
|
||||
0xe2,
|
||||
0x47,
|
||||
0xe9,
|
||||
0xc0,
|
||||
0x8b,
|
||||
0x10,
|
||||
0xd0,
|
||||
0x29,
|
||||
0x93,
|
||||
0x4f,
|
||||
0xc4,
|
||||
0xb9,
|
||||
0x52,
|
||||
0xf7,
|
||||
},
|
||||
{
|
||||
0x31,
|
||||
0xfc,
|
||||
0xef,
|
||||
0xac,
|
||||
0x66,
|
||||
0xd7,
|
||||
0xde,
|
||||
0x9c,
|
||||
0x7e,
|
||||
0xc7,
|
||||
0x48,
|
||||
0x5f,
|
||||
0xe4,
|
||||
0x49,
|
||||
0x49,
|
||||
0x02,
|
||||
},
|
||||
{
|
||||
0x54,
|
||||
0x93,
|
||||
0xe9,
|
||||
0x99,
|
||||
0x33,
|
||||
0xb0,
|
||||
0xa8,
|
||||
0x11,
|
||||
0x7e,
|
||||
0x08,
|
||||
0xec,
|
||||
0x0f,
|
||||
0x97,
|
||||
0xcf,
|
||||
0xc3,
|
||||
0xd9,
|
||||
},
|
||||
{
|
||||
0x6e,
|
||||
0xe2,
|
||||
0xa4,
|
||||
0xca,
|
||||
0x67,
|
||||
0xb0,
|
||||
0x54,
|
||||
0xbb,
|
||||
0xfd,
|
||||
0x33,
|
||||
0x15,
|
||||
0xbf,
|
||||
0x85,
|
||||
0x23,
|
||||
0x05,
|
||||
0x77,
|
||||
},
|
||||
{
|
||||
0x47,
|
||||
0x3d,
|
||||
0x06,
|
||||
0xe8,
|
||||
0x73,
|
||||
0x8d,
|
||||
0xb8,
|
||||
0x98,
|
||||
0x54,
|
||||
0xc0,
|
||||
0x66,
|
||||
0xc4,
|
||||
0x7a,
|
||||
0xe4,
|
||||
0x77,
|
||||
0x40,
|
||||
},
|
||||
{
|
||||
0xa4,
|
||||
0x26,
|
||||
0xe5,
|
||||
0xe4,
|
||||
0x23,
|
||||
0xbf,
|
||||
0x48,
|
||||
0x85,
|
||||
0x29,
|
||||
0x4d,
|
||||
0xa4,
|
||||
0x81,
|
||||
0xfe,
|
||||
0xae,
|
||||
0xf7,
|
||||
0x23,
|
||||
},
|
||||
{
|
||||
0x78,
|
||||
0x01,
|
||||
0x77,
|
||||
0x31,
|
||||
0xcf,
|
||||
0x65,
|
||||
0xfa,
|
||||
0xb0,
|
||||
0x74,
|
||||
0xd5,
|
||||
0x20,
|
||||
0x89,
|
||||
0x52,
|
||||
0x51,
|
||||
0x2e,
|
||||
0xb1,
|
||||
},
|
||||
{
|
||||
0x9e,
|
||||
0x25,
|
||||
0xfc,
|
||||
0x83,
|
||||
0x3f,
|
||||
0x22,
|
||||
0x90,
|
||||
0x73,
|
||||
0x3e,
|
||||
0x93,
|
||||
0x44,
|
||||
0xa5,
|
||||
0xe8,
|
||||
0x38,
|
||||
0x39,
|
||||
0xeb,
|
||||
},
|
||||
{
|
||||
0x56,
|
||||
0x8e,
|
||||
0x49,
|
||||
0x5a,
|
||||
0xbe,
|
||||
0x52,
|
||||
0x5a,
|
||||
0x21,
|
||||
0x8a,
|
||||
0x22,
|
||||
0x14,
|
||||
0xcd,
|
||||
0x3e,
|
||||
0x07,
|
||||
0x1d,
|
||||
0x12,
|
||||
},
|
||||
{
|
||||
0x4a,
|
||||
0x29,
|
||||
0xb5,
|
||||
0x45,
|
||||
0x52,
|
||||
0xd1,
|
||||
0x6b,
|
||||
0x9a,
|
||||
0x46,
|
||||
0x9c,
|
||||
0x10,
|
||||
0x52,
|
||||
0x8e,
|
||||
0xff,
|
||||
0x0a,
|
||||
0xae,
|
||||
},
|
||||
{
|
||||
0xc9,
|
||||
0xd1,
|
||||
0x84,
|
||||
0xdd,
|
||||
0xd5,
|
||||
0xa9,
|
||||
0xf5,
|
||||
0xe0,
|
||||
0xcf,
|
||||
0x8c,
|
||||
0xe2,
|
||||
0x9a,
|
||||
0x9a,
|
||||
0xbf,
|
||||
0x69,
|
||||
0x1c,
|
||||
},
|
||||
{
|
||||
0x2d,
|
||||
0xb4,
|
||||
0x79,
|
||||
0xae,
|
||||
0x78,
|
||||
0xbd,
|
||||
0x50,
|
||||
0xd8,
|
||||
0x88,
|
||||
0x2a,
|
||||
0x8a,
|
||||
0x17,
|
||||
0x8a,
|
||||
0x61,
|
||||
0x32,
|
||||
0xad,
|
||||
},
|
||||
{
|
||||
0x8e,
|
||||
0xce,
|
||||
0x5f,
|
||||
0x04,
|
||||
0x2d,
|
||||
0x5e,
|
||||
0x44,
|
||||
0x7b,
|
||||
0x50,
|
||||
0x51,
|
||||
0xb9,
|
||||
0xea,
|
||||
0xcb,
|
||||
0x8d,
|
||||
0x8f,
|
||||
0x6f,
|
||||
},
|
||||
{
|
||||
0x9c,
|
||||
0x0b,
|
||||
0x53,
|
||||
0xb4,
|
||||
0xb3,
|
||||
0xc3,
|
||||
0x07,
|
||||
0xe8,
|
||||
0x7e,
|
||||
0xae,
|
||||
0xe0,
|
||||
0x86,
|
||||
0x78,
|
||||
0x14,
|
||||
0x1f,
|
||||
0x66,
|
||||
},
|
||||
{
|
||||
0xab,
|
||||
0xf2,
|
||||
0x48,
|
||||
0xaf,
|
||||
0x69,
|
||||
0xa6,
|
||||
0xea,
|
||||
0xe4,
|
||||
0xbf,
|
||||
0xd3,
|
||||
0xeb,
|
||||
0x2f,
|
||||
0x12,
|
||||
0x9e,
|
||||
0xeb,
|
||||
0x94,
|
||||
},
|
||||
{
|
||||
0x06,
|
||||
0x64,
|
||||
0xda,
|
||||
0x16,
|
||||
0x68,
|
||||
0x57,
|
||||
0x4b,
|
||||
0x88,
|
||||
0xb9,
|
||||
0x35,
|
||||
0xf3,
|
||||
0x02,
|
||||
0x73,
|
||||
0x58,
|
||||
0xae,
|
||||
0xf4,
|
||||
},
|
||||
{
|
||||
0xaa,
|
||||
0x4b,
|
||||
0x9d,
|
||||
0xc4,
|
||||
0xbf,
|
||||
0x33,
|
||||
0x7d,
|
||||
0xe9,
|
||||
0x0c,
|
||||
0xd4,
|
||||
0xfd,
|
||||
0x3c,
|
||||
0x46,
|
||||
0x7c,
|
||||
0x6a,
|
||||
0xb7,
|
||||
},
|
||||
{
|
||||
0xea,
|
||||
0x5c,
|
||||
0x7f,
|
||||
0x47,
|
||||
0x1f,
|
||||
0xaf,
|
||||
0x6b,
|
||||
0xde,
|
||||
0x2b,
|
||||
0x1a,
|
||||
0xd7,
|
||||
0xd4,
|
||||
0x68,
|
||||
0x6d,
|
||||
0x22,
|
||||
0x87,
|
||||
},
|
||||
{
|
||||
0x29,
|
||||
0x39,
|
||||
0xb0,
|
||||
0x18,
|
||||
0x32,
|
||||
0x23,
|
||||
0xfa,
|
||||
0xfc,
|
||||
0x17,
|
||||
0x23,
|
||||
0xde,
|
||||
0x4f,
|
||||
0x52,
|
||||
0xc4,
|
||||
0x3d,
|
||||
0x35,
|
||||
},
|
||||
{
|
||||
0x7c,
|
||||
0x39,
|
||||
0x56,
|
||||
0xca,
|
||||
0x5e,
|
||||
0xea,
|
||||
0xfc,
|
||||
0x3e,
|
||||
0x36,
|
||||
0x3e,
|
||||
0x9d,
|
||||
0x55,
|
||||
0x65,
|
||||
0x46,
|
||||
0xeb,
|
||||
0x68,
|
||||
},
|
||||
{
|
||||
0x77,
|
||||
0xc6,
|
||||
0x07,
|
||||
0x71,
|
||||
0x46,
|
||||
0xf0,
|
||||
0x1c,
|
||||
0x32,
|
||||
0xb6,
|
||||
0xb6,
|
||||
0x9d,
|
||||
0x5f,
|
||||
0x4e,
|
||||
0xa9,
|
||||
0xff,
|
||||
0xcf,
|
||||
},
|
||||
{
|
||||
0x37,
|
||||
0xa6,
|
||||
0x98,
|
||||
0x6c,
|
||||
0xb8,
|
||||
0x84,
|
||||
0x7e,
|
||||
0xdf,
|
||||
0x09,
|
||||
0x25,
|
||||
0xf0,
|
||||
0xf1,
|
||||
0x30,
|
||||
0x9b,
|
||||
0x54,
|
||||
0xde,
|
||||
},
|
||||
{
|
||||
0xa7,
|
||||
0x05,
|
||||
0xf0,
|
||||
0xe6,
|
||||
0x9d,
|
||||
0xa9,
|
||||
0xa8,
|
||||
0xf9,
|
||||
0x07,
|
||||
0x24,
|
||||
0x1a,
|
||||
0x2e,
|
||||
0x92,
|
||||
0x3c,
|
||||
0x8c,
|
||||
0xc8,
|
||||
},
|
||||
{
|
||||
0x3d,
|
||||
0xc4,
|
||||
0x7d,
|
||||
0x1f,
|
||||
0x29,
|
||||
0xc4,
|
||||
0x48,
|
||||
0x46,
|
||||
0x1e,
|
||||
0x9e,
|
||||
0x76,
|
||||
0xed,
|
||||
0x90,
|
||||
0x4f,
|
||||
0x67,
|
||||
0x11,
|
||||
},
|
||||
{
|
||||
0x0d,
|
||||
0x62,
|
||||
0xbf,
|
||||
0x01,
|
||||
0xe6,
|
||||
0xfc,
|
||||
0x0e,
|
||||
0x1a,
|
||||
0x0d,
|
||||
0x3c,
|
||||
0x47,
|
||||
0x51,
|
||||
0xc5,
|
||||
0xd3,
|
||||
0x69,
|
||||
0x2b,
|
||||
},
|
||||
{
|
||||
0x8c,
|
||||
0x03,
|
||||
0x46,
|
||||
0x8b,
|
||||
0xca,
|
||||
0x7c,
|
||||
0x66,
|
||||
0x9e,
|
||||
0xe4,
|
||||
0xfd,
|
||||
0x5e,
|
||||
0x08,
|
||||
0x4b,
|
||||
0xbe,
|
||||
0xe7,
|
||||
0xb5,
|
||||
},
|
||||
{
|
||||
0x52,
|
||||
0x8a,
|
||||
0x5b,
|
||||
0xb9,
|
||||
0x3b,
|
||||
0xaf,
|
||||
0x2c,
|
||||
0x9c,
|
||||
0x44,
|
||||
0x73,
|
||||
0xcc,
|
||||
0xe5,
|
||||
0xd0,
|
||||
0xd2,
|
||||
0x2b,
|
||||
0xd9,
|
||||
},
|
||||
{
|
||||
0xdf,
|
||||
0x6a,
|
||||
0x30,
|
||||
0x1e,
|
||||
0x95,
|
||||
0xc9,
|
||||
0x5d,
|
||||
0xad,
|
||||
0x97,
|
||||
0xae,
|
||||
0x0c,
|
||||
0xc8,
|
||||
0xc6,
|
||||
0x91,
|
||||
0x3b,
|
||||
0xd8,
|
||||
},
|
||||
{
|
||||
0x80,
|
||||
0x11,
|
||||
0x89,
|
||||
0x90,
|
||||
0x2c,
|
||||
0x85,
|
||||
0x7f,
|
||||
0x39,
|
||||
0xe7,
|
||||
0x35,
|
||||
0x91,
|
||||
0x28,
|
||||
0x5e,
|
||||
0x70,
|
||||
0xb6,
|
||||
0xdb,
|
||||
},
|
||||
{
|
||||
0xe6,
|
||||
0x17,
|
||||
0x34,
|
||||
0x6a,
|
||||
0xc9,
|
||||
0xc2,
|
||||
0x31,
|
||||
0xbb,
|
||||
0x36,
|
||||
0x50,
|
||||
0xae,
|
||||
0x34,
|
||||
0xcc,
|
||||
0xca,
|
||||
0x0c,
|
||||
0x5b,
|
||||
},
|
||||
{
|
||||
0x27,
|
||||
0xd9,
|
||||
0x34,
|
||||
0x37,
|
||||
0xef,
|
||||
0xb7,
|
||||
0x21,
|
||||
0xaa,
|
||||
0x40,
|
||||
0x18,
|
||||
0x21,
|
||||
0xdc,
|
||||
0xec,
|
||||
0x5a,
|
||||
0xdf,
|
||||
0x89,
|
||||
},
|
||||
{
|
||||
0x89,
|
||||
0x23,
|
||||
0x7d,
|
||||
0x9d,
|
||||
0xed,
|
||||
0x9c,
|
||||
0x5e,
|
||||
0x78,
|
||||
0xd8,
|
||||
0xb1,
|
||||
0xc9,
|
||||
0xb1,
|
||||
0x66,
|
||||
0xcc,
|
||||
0x73,
|
||||
0x42,
|
||||
},
|
||||
{
|
||||
0x4a,
|
||||
0x6d,
|
||||
0x80,
|
||||
0x91,
|
||||
0xbf,
|
||||
0x5e,
|
||||
0x7d,
|
||||
0x65,
|
||||
0x11,
|
||||
0x89,
|
||||
0xfa,
|
||||
0x94,
|
||||
0xa2,
|
||||
0x50,
|
||||
0xb1,
|
||||
0x4c,
|
||||
},
|
||||
{
|
||||
0x0e,
|
||||
0x33,
|
||||
0xf9,
|
||||
0x60,
|
||||
0x55,
|
||||
0xe7,
|
||||
0xae,
|
||||
0x89,
|
||||
0x3f,
|
||||
0xfc,
|
||||
0x0e,
|
||||
0x3d,
|
||||
0xcf,
|
||||
0x49,
|
||||
0x29,
|
||||
0x02,
|
||||
},
|
||||
{
|
||||
0xe6,
|
||||
0x1c,
|
||||
0x43,
|
||||
0x2b,
|
||||
0x72,
|
||||
0x0b,
|
||||
0x19,
|
||||
0xd1,
|
||||
0x8e,
|
||||
0xc8,
|
||||
0xd8,
|
||||
0x4b,
|
||||
0xdc,
|
||||
0x63,
|
||||
0x15,
|
||||
0x1b,
|
||||
},
|
||||
{
|
||||
0xf7,
|
||||
0xe5,
|
||||
0xae,
|
||||
0xf5,
|
||||
0x49,
|
||||
0xf7,
|
||||
0x82,
|
||||
0xcf,
|
||||
0x37,
|
||||
0x90,
|
||||
0x55,
|
||||
0xa6,
|
||||
0x08,
|
||||
0x26,
|
||||
0x9b,
|
||||
0x16,
|
||||
},
|
||||
{
|
||||
0x43,
|
||||
0x8d,
|
||||
0x03,
|
||||
0x0f,
|
||||
0xd0,
|
||||
0xb7,
|
||||
0xa5,
|
||||
0x4f,
|
||||
0xa8,
|
||||
0x37,
|
||||
0xf2,
|
||||
0xad,
|
||||
0x20,
|
||||
0x1a,
|
||||
0x64,
|
||||
0x03,
|
||||
},
|
||||
{
|
||||
0xa5,
|
||||
0x90,
|
||||
0xd3,
|
||||
0xee,
|
||||
0x4f,
|
||||
0xbf,
|
||||
0x04,
|
||||
0xe3,
|
||||
0x24,
|
||||
0x7e,
|
||||
0x0d,
|
||||
0x27,
|
||||
0xf2,
|
||||
0x86,
|
||||
0x42,
|
||||
0x3f,
|
||||
},
|
||||
{
|
||||
0x5f,
|
||||
0xe2,
|
||||
0xc1,
|
||||
0xa1,
|
||||
0x72,
|
||||
0xfe,
|
||||
0x93,
|
||||
0xc4,
|
||||
0xb1,
|
||||
0x5c,
|
||||
0xd3,
|
||||
0x7c,
|
||||
0xae,
|
||||
0xf9,
|
||||
0xf5,
|
||||
0x38,
|
||||
},
|
||||
{
|
||||
0x2c,
|
||||
0x97,
|
||||
0x32,
|
||||
0x5c,
|
||||
0xbd,
|
||||
0x06,
|
||||
0xb3,
|
||||
0x6e,
|
||||
0xb2,
|
||||
0x13,
|
||||
0x3d,
|
||||
0xd0,
|
||||
0x8b,
|
||||
0x3a,
|
||||
0x01,
|
||||
0x7c,
|
||||
},
|
||||
{
|
||||
0x92,
|
||||
0xc8,
|
||||
0x14,
|
||||
0x22,
|
||||
0x7a,
|
||||
0x6b,
|
||||
0xca,
|
||||
0x94,
|
||||
0x9f,
|
||||
0xf0,
|
||||
0x65,
|
||||
0x9f,
|
||||
0x00,
|
||||
0x2a,
|
||||
0xd3,
|
||||
0x9e,
|
||||
},
|
||||
{
|
||||
0xdc,
|
||||
0xe8,
|
||||
0x50,
|
||||
0x11,
|
||||
0x0b,
|
||||
0xd8,
|
||||
0x32,
|
||||
0x8c,
|
||||
0xfb,
|
||||
0xd5,
|
||||
0x08,
|
||||
0x41,
|
||||
0xd6,
|
||||
0x91,
|
||||
0x1d,
|
||||
0x87,
|
||||
},
|
||||
{
|
||||
0x67,
|
||||
0xf1,
|
||||
0x49,
|
||||
0x84,
|
||||
0xc7,
|
||||
0xda,
|
||||
0x79,
|
||||
0x12,
|
||||
0x48,
|
||||
0xe3,
|
||||
0x2b,
|
||||
0xb5,
|
||||
0x92,
|
||||
0x25,
|
||||
0x83,
|
||||
0xda,
|
||||
},
|
||||
{
|
||||
0x19,
|
||||
0x38,
|
||||
0xf2,
|
||||
0xcf,
|
||||
0x72,
|
||||
0xd5,
|
||||
0x4e,
|
||||
0xe9,
|
||||
0x7e,
|
||||
0x94,
|
||||
0x16,
|
||||
0x6f,
|
||||
0xa9,
|
||||
0x1d,
|
||||
0x2a,
|
||||
0x36,
|
||||
},
|
||||
{
|
||||
0x74,
|
||||
0x48,
|
||||
0x1e,
|
||||
0x96,
|
||||
0x46,
|
||||
0xed,
|
||||
0x49,
|
||||
0xfe,
|
||||
0x0f,
|
||||
0x62,
|
||||
0x24,
|
||||
0x30,
|
||||
0x16,
|
||||
0x04,
|
||||
0x69,
|
||||
0x8e,
|
||||
},
|
||||
{
|
||||
0x57,
|
||||
0xfc,
|
||||
0xa5,
|
||||
0xde,
|
||||
0x98,
|
||||
0xa9,
|
||||
0xd6,
|
||||
0xd8,
|
||||
0x00,
|
||||
0x64,
|
||||
0x38,
|
||||
0xd0,
|
||||
0x58,
|
||||
0x3d,
|
||||
0x8a,
|
||||
0x1d,
|
||||
},
|
||||
{
|
||||
0x9f,
|
||||
0xec,
|
||||
0xde,
|
||||
0x1c,
|
||||
0xef,
|
||||
0xdc,
|
||||
0x1c,
|
||||
0xbe,
|
||||
0xd4,
|
||||
0x76,
|
||||
0x36,
|
||||
0x74,
|
||||
0xd9,
|
||||
0x57,
|
||||
0x53,
|
||||
0x59,
|
||||
},
|
||||
{
|
||||
0xe3,
|
||||
0x04,
|
||||
0x0c,
|
||||
0x00,
|
||||
0xeb,
|
||||
0x28,
|
||||
0xf1,
|
||||
0x53,
|
||||
0x66,
|
||||
0xca,
|
||||
0x73,
|
||||
0xcb,
|
||||
0xd8,
|
||||
0x72,
|
||||
0xe7,
|
||||
0x40,
|
||||
},
|
||||
{
|
||||
0x76,
|
||||
0x97,
|
||||
0x00,
|
||||
0x9a,
|
||||
0x6a,
|
||||
0x83,
|
||||
0x1d,
|
||||
0xfe,
|
||||
0xcc,
|
||||
0xa9,
|
||||
0x1c,
|
||||
0x59,
|
||||
0x93,
|
||||
0x67,
|
||||
0x0f,
|
||||
0x7a,
|
||||
},
|
||||
{
|
||||
0x58,
|
||||
0x53,
|
||||
0x54,
|
||||
0x23,
|
||||
0x21,
|
||||
0xf5,
|
||||
0x67,
|
||||
0xa0,
|
||||
0x05,
|
||||
0xd5,
|
||||
0x47,
|
||||
0xa4,
|
||||
0xf0,
|
||||
0x47,
|
||||
0x59,
|
||||
0xbd,
|
||||
},
|
||||
{
|
||||
0x51,
|
||||
0x50,
|
||||
0xd1,
|
||||
0x77,
|
||||
0x2f,
|
||||
0x50,
|
||||
0x83,
|
||||
0x4a,
|
||||
0x50,
|
||||
0x3e,
|
||||
0x06,
|
||||
0x9a,
|
||||
0x97,
|
||||
0x3f,
|
||||
0xbd,
|
||||
0x7c,
|
||||
},
|
||||
};
|
||||
const uint8_t vectors_hsip32[64][4] = {
|
||||
{
|
||||
0xa9,
|
||||
0x35,
|
||||
0x9f,
|
||||
0x5b,
|
||||
},
|
||||
{
|
||||
0x27,
|
||||
0x47,
|
||||
0x5a,
|
||||
0xb8,
|
||||
},
|
||||
{
|
||||
0xfa,
|
||||
0x62,
|
||||
0xa6,
|
||||
0x03,
|
||||
},
|
||||
{
|
||||
0x8a,
|
||||
0xfe,
|
||||
0xe7,
|
||||
0x04,
|
||||
},
|
||||
{
|
||||
0x2a,
|
||||
0x6e,
|
||||
0x46,
|
||||
0x89,
|
||||
},
|
||||
{
|
||||
0xc5,
|
||||
0xfa,
|
||||
0xb6,
|
||||
0x69,
|
||||
},
|
||||
{
|
||||
0x58,
|
||||
0x63,
|
||||
0xfc,
|
||||
0x23,
|
||||
},
|
||||
{
|
||||
0x8b,
|
||||
0xcf,
|
||||
0x63,
|
||||
0xc5,
|
||||
},
|
||||
{
|
||||
0xd0,
|
||||
0xb8,
|
||||
0x84,
|
||||
0x8f,
|
||||
},
|
||||
{
|
||||
0xf8,
|
||||
0x06,
|
||||
0xe7,
|
||||
0x79,
|
||||
},
|
||||
{
|
||||
0x94,
|
||||
0xb0,
|
||||
0x79,
|
||||
0x34,
|
||||
},
|
||||
{
|
||||
0x08,
|
||||
0x08,
|
||||
0x30,
|
||||
0x50,
|
||||
},
|
||||
{
|
||||
0x57,
|
||||
0xf0,
|
||||
0x87,
|
||||
0x2f,
|
||||
},
|
||||
{
|
||||
0x77,
|
||||
0xe6,
|
||||
0x63,
|
||||
0xff,
|
||||
},
|
||||
{
|
||||
0xd6,
|
||||
0xff,
|
||||
0xf8,
|
||||
0x7c,
|
||||
},
|
||||
{
|
||||
0x74,
|
||||
0xfe,
|
||||
0x2b,
|
||||
0x97,
|
||||
},
|
||||
{
|
||||
0xd9,
|
||||
0xb5,
|
||||
0xac,
|
||||
0x84,
|
||||
},
|
||||
{
|
||||
0xc4,
|
||||
0x74,
|
||||
0x64,
|
||||
0x5b,
|
||||
},
|
||||
{
|
||||
0x46,
|
||||
0x5b,
|
||||
0x8d,
|
||||
0x9b,
|
||||
},
|
||||
{
|
||||
0x7b,
|
||||
0xef,
|
||||
0xe3,
|
||||
0x87,
|
||||
},
|
||||
{
|
||||
0xe3,
|
||||
0x4d,
|
||||
0x10,
|
||||
0x45,
|
||||
},
|
||||
{
|
||||
0x61,
|
||||
0x3f,
|
||||
0x62,
|
||||
0xb3,
|
||||
},
|
||||
{
|
||||
0x70,
|
||||
0xf3,
|
||||
0x67,
|
||||
0xfe,
|
||||
},
|
||||
{
|
||||
0xe6,
|
||||
0xad,
|
||||
0xb8,
|
||||
0xbd,
|
||||
},
|
||||
{
|
||||
0x27,
|
||||
0x40,
|
||||
0x0c,
|
||||
0x63,
|
||||
},
|
||||
{
|
||||
0x26,
|
||||
0x78,
|
||||
0x78,
|
||||
0x75,
|
||||
},
|
||||
{
|
||||
0x4f,
|
||||
0x56,
|
||||
0x7b,
|
||||
0x5f,
|
||||
},
|
||||
{
|
||||
0x3a,
|
||||
0xb0,
|
||||
0xe6,
|
||||
0x69,
|
||||
},
|
||||
{
|
||||
0xb0,
|
||||
0x64,
|
||||
0x40,
|
||||
0x00,
|
||||
},
|
||||
{
|
||||
0xff,
|
||||
0x67,
|
||||
0x0f,
|
||||
0xb4,
|
||||
},
|
||||
{
|
||||
0x50,
|
||||
0x9e,
|
||||
0x33,
|
||||
0x8b,
|
||||
},
|
||||
{
|
||||
0x5d,
|
||||
0x58,
|
||||
0x9f,
|
||||
0x1a,
|
||||
},
|
||||
{
|
||||
0xfe,
|
||||
0xe7,
|
||||
0x21,
|
||||
0x12,
|
||||
},
|
||||
{
|
||||
0x33,
|
||||
0x75,
|
||||
0x32,
|
||||
0x59,
|
||||
},
|
||||
{
|
||||
0x6a,
|
||||
0x43,
|
||||
0x4f,
|
||||
0x8c,
|
||||
},
|
||||
{
|
||||
0xfe,
|
||||
0x28,
|
||||
0xb7,
|
||||
0x29,
|
||||
},
|
||||
{
|
||||
0xe7,
|
||||
0x5c,
|
||||
0xc6,
|
||||
0xec,
|
||||
},
|
||||
{
|
||||
0x69,
|
||||
0x7e,
|
||||
0x8d,
|
||||
0x54,
|
||||
},
|
||||
{
|
||||
0x63,
|
||||
0x68,
|
||||
0x8b,
|
||||
0x0f,
|
||||
},
|
||||
{
|
||||
0x65,
|
||||
0x0b,
|
||||
0x62,
|
||||
0xb4,
|
||||
},
|
||||
{
|
||||
0xb6,
|
||||
0xbc,
|
||||
0x18,
|
||||
0x40,
|
||||
},
|
||||
{
|
||||
0x5d,
|
||||
0x07,
|
||||
0x45,
|
||||
0x05,
|
||||
},
|
||||
{
|
||||
0x24,
|
||||
0x42,
|
||||
0xfd,
|
||||
0x2e,
|
||||
},
|
||||
{
|
||||
0x7b,
|
||||
0xb7,
|
||||
0x86,
|
||||
0x3a,
|
||||
},
|
||||
{
|
||||
0x77,
|
||||
0x05,
|
||||
0xd5,
|
||||
0x48,
|
||||
},
|
||||
{
|
||||
0xd7,
|
||||
0x52,
|
||||
0x08,
|
||||
0xb1,
|
||||
},
|
||||
{
|
||||
0xb6,
|
||||
0xd4,
|
||||
0x99,
|
||||
0xc8,
|
||||
},
|
||||
{
|
||||
0x08,
|
||||
0x92,
|
||||
0x20,
|
||||
0x2e,
|
||||
},
|
||||
{
|
||||
0x69,
|
||||
0xe1,
|
||||
0x2c,
|
||||
0xe3,
|
||||
},
|
||||
{
|
||||
0x8d,
|
||||
0xb5,
|
||||
0x80,
|
||||
0xe5,
|
||||
},
|
||||
{
|
||||
0x36,
|
||||
0x97,
|
||||
0x64,
|
||||
0xc6,
|
||||
},
|
||||
{
|
||||
0x01,
|
||||
0x6e,
|
||||
0x02,
|
||||
0x04,
|
||||
},
|
||||
{
|
||||
0x3b,
|
||||
0x85,
|
||||
0xf3,
|
||||
0xd4,
|
||||
},
|
||||
{
|
||||
0xfe,
|
||||
0xdb,
|
||||
0x66,
|
||||
0xbe,
|
||||
},
|
||||
{
|
||||
0x1e,
|
||||
0x69,
|
||||
0x2a,
|
||||
0x3a,
|
||||
},
|
||||
{
|
||||
0xc6,
|
||||
0x89,
|
||||
0x84,
|
||||
0xc0,
|
||||
},
|
||||
{
|
||||
0xa5,
|
||||
0xc5,
|
||||
0xb9,
|
||||
0x40,
|
||||
},
|
||||
{
|
||||
0x9b,
|
||||
0xe9,
|
||||
0xe8,
|
||||
0x8c,
|
||||
},
|
||||
{
|
||||
0x7d,
|
||||
0xbc,
|
||||
0x81,
|
||||
0x40,
|
||||
},
|
||||
{
|
||||
0x7c,
|
||||
0x07,
|
||||
0x8e,
|
||||
0xc5,
|
||||
},
|
||||
{
|
||||
0xd4,
|
||||
0xe7,
|
||||
0x6c,
|
||||
0x73,
|
||||
},
|
||||
{
|
||||
0x42,
|
||||
0x8f,
|
||||
0xcb,
|
||||
0xb9,
|
||||
},
|
||||
{
|
||||
0xbd,
|
||||
0x83,
|
||||
0x99,
|
||||
0x7a,
|
||||
},
|
||||
{
|
||||
0x59,
|
||||
0xea,
|
||||
0x4a,
|
||||
0x74,
|
||||
},
|
||||
};
|
||||
const uint8_t vectors_hsip64[64][8] = {
|
||||
{
|
||||
0x21,
|
||||
0x8d,
|
||||
0x1f,
|
||||
0x59,
|
||||
0xb9,
|
||||
0xb8,
|
||||
0x3c,
|
||||
0xc8,
|
||||
},
|
||||
{
|
||||
0xbe,
|
||||
0x55,
|
||||
0x24,
|
||||
0x12,
|
||||
0xf8,
|
||||
0x38,
|
||||
0x73,
|
||||
0x15,
|
||||
},
|
||||
{
|
||||
0x06,
|
||||
0x4f,
|
||||
0x39,
|
||||
0xef,
|
||||
0x7c,
|
||||
0x50,
|
||||
0xeb,
|
||||
0x57,
|
||||
},
|
||||
{
|
||||
0xce,
|
||||
0x0f,
|
||||
0x1a,
|
||||
0x45,
|
||||
0xf7,
|
||||
0x06,
|
||||
0x06,
|
||||
0x79,
|
||||
},
|
||||
{
|
||||
0xd5,
|
||||
0xe7,
|
||||
0x8a,
|
||||
0x17,
|
||||
0x5b,
|
||||
0xe5,
|
||||
0x2e,
|
||||
0xa1,
|
||||
},
|
||||
{
|
||||
0xcb,
|
||||
0x9d,
|
||||
0x7c,
|
||||
0x3f,
|
||||
0x2f,
|
||||
0x3d,
|
||||
0xb5,
|
||||
0x80,
|
||||
},
|
||||
{
|
||||
0xce,
|
||||
0x3e,
|
||||
0x91,
|
||||
0x35,
|
||||
0x8a,
|
||||
0xa2,
|
||||
0xbc,
|
||||
0x25,
|
||||
},
|
||||
{
|
||||
0xff,
|
||||
0x20,
|
||||
0x27,
|
||||
0x28,
|
||||
0xb0,
|
||||
0x7b,
|
||||
0xc6,
|
||||
0x84,
|
||||
},
|
||||
{
|
||||
0xed,
|
||||
0xfe,
|
||||
0xe8,
|
||||
0x20,
|
||||
0xbc,
|
||||
0xe4,
|
||||
0x85,
|
||||
0x8c,
|
||||
},
|
||||
{
|
||||
0x5b,
|
||||
0x51,
|
||||
0xcc,
|
||||
0xcc,
|
||||
0x13,
|
||||
0x88,
|
||||
0x83,
|
||||
0x07,
|
||||
},
|
||||
{
|
||||
0x95,
|
||||
0xb0,
|
||||
0x46,
|
||||
0x9f,
|
||||
0x06,
|
||||
0xa6,
|
||||
0xf2,
|
||||
0xee,
|
||||
},
|
||||
{
|
||||
0xae,
|
||||
0x26,
|
||||
0x33,
|
||||
0x39,
|
||||
0x94,
|
||||
0xdd,
|
||||
0xcd,
|
||||
0x48,
|
||||
},
|
||||
{
|
||||
0x7b,
|
||||
0xc7,
|
||||
0x1f,
|
||||
0x9f,
|
||||
0xae,
|
||||
0xf5,
|
||||
0xc7,
|
||||
0x99,
|
||||
},
|
||||
{
|
||||
0x5a,
|
||||
0x23,
|
||||
0x52,
|
||||
0xd7,
|
||||
0x5a,
|
||||
0x0c,
|
||||
0x37,
|
||||
0x44,
|
||||
},
|
||||
{
|
||||
0x3b,
|
||||
0xb1,
|
||||
0xa8,
|
||||
0x70,
|
||||
0xea,
|
||||
0xe8,
|
||||
0xe6,
|
||||
0x58,
|
||||
},
|
||||
{
|
||||
0x21,
|
||||
0x7d,
|
||||
0x0b,
|
||||
0xcb,
|
||||
0x4e,
|
||||
0x81,
|
||||
0xc9,
|
||||
0x02,
|
||||
},
|
||||
{
|
||||
0x73,
|
||||
0x36,
|
||||
0xaa,
|
||||
0xd2,
|
||||
0x5f,
|
||||
0x7b,
|
||||
0xf3,
|
||||
0xb5,
|
||||
},
|
||||
{
|
||||
0x37,
|
||||
0xad,
|
||||
0xc0,
|
||||
0x64,
|
||||
0x1c,
|
||||
0x4c,
|
||||
0x4f,
|
||||
0x6a,
|
||||
},
|
||||
{
|
||||
0xc9,
|
||||
0xb2,
|
||||
0xdb,
|
||||
0x2b,
|
||||
0x9a,
|
||||
0x3e,
|
||||
0x42,
|
||||
0xf9,
|
||||
},
|
||||
{
|
||||
0xf9,
|
||||
0x10,
|
||||
0xe4,
|
||||
0x80,
|
||||
0x20,
|
||||
0xab,
|
||||
0x36,
|
||||
0x3c,
|
||||
},
|
||||
{
|
||||
0x1b,
|
||||
0xf5,
|
||||
0x2b,
|
||||
0x0a,
|
||||
0x6f,
|
||||
0xee,
|
||||
0xa7,
|
||||
0xdb,
|
||||
},
|
||||
{
|
||||
0x00,
|
||||
0x74,
|
||||
0x1d,
|
||||
0xc2,
|
||||
0x69,
|
||||
0xe8,
|
||||
0xb3,
|
||||
0xef,
|
||||
},
|
||||
{
|
||||
0xe2,
|
||||
0x01,
|
||||
0x03,
|
||||
0xfa,
|
||||
0x1b,
|
||||
0xa7,
|
||||
0x76,
|
||||
0xef,
|
||||
},
|
||||
{
|
||||
0x4c,
|
||||
0x22,
|
||||
0x10,
|
||||
0xe5,
|
||||
0x4b,
|
||||
0x68,
|
||||
0x1d,
|
||||
0x73,
|
||||
},
|
||||
{
|
||||
0x70,
|
||||
0x74,
|
||||
0x10,
|
||||
0x45,
|
||||
0xae,
|
||||
0x3f,
|
||||
0xa6,
|
||||
0xf1,
|
||||
},
|
||||
{
|
||||
0x0c,
|
||||
0x86,
|
||||
0x40,
|
||||
0x37,
|
||||
0x39,
|
||||
0x71,
|
||||
0x40,
|
||||
0x38,
|
||||
},
|
||||
{
|
||||
0x0d,
|
||||
0x89,
|
||||
0x9e,
|
||||
0xd8,
|
||||
0x11,
|
||||
0x29,
|
||||
0x23,
|
||||
0xf0,
|
||||
},
|
||||
{
|
||||
0x22,
|
||||
0x6b,
|
||||
0xf5,
|
||||
0xfa,
|
||||
0xb8,
|
||||
0x1e,
|
||||
0xe1,
|
||||
0xb8,
|
||||
},
|
||||
{
|
||||
0x2d,
|
||||
0x92,
|
||||
0x5f,
|
||||
0xfb,
|
||||
0x1e,
|
||||
0x00,
|
||||
0x16,
|
||||
0xb5,
|
||||
},
|
||||
{
|
||||
0x36,
|
||||
0x19,
|
||||
0x58,
|
||||
0xd5,
|
||||
0x2c,
|
||||
0xee,
|
||||
0x10,
|
||||
0xf1,
|
||||
},
|
||||
{
|
||||
0x29,
|
||||
0x1a,
|
||||
0xaf,
|
||||
0x86,
|
||||
0x48,
|
||||
0x98,
|
||||
0x17,
|
||||
0x9d,
|
||||
},
|
||||
{
|
||||
0x86,
|
||||
0x3c,
|
||||
0x7f,
|
||||
0x15,
|
||||
0x5c,
|
||||
0x34,
|
||||
0x11,
|
||||
0x7c,
|
||||
},
|
||||
{
|
||||
0x28,
|
||||
0x70,
|
||||
0x9d,
|
||||
0x46,
|
||||
0xd8,
|
||||
0x11,
|
||||
0x62,
|
||||
0x6c,
|
||||
},
|
||||
{
|
||||
0x24,
|
||||
0x84,
|
||||
0x77,
|
||||
0x68,
|
||||
0x1d,
|
||||
0x28,
|
||||
0xf8,
|
||||
0x9c,
|
||||
},
|
||||
{
|
||||
0x83,
|
||||
0x24,
|
||||
0xe4,
|
||||
0xd7,
|
||||
0x52,
|
||||
0x8f,
|
||||
0x98,
|
||||
0x30,
|
||||
},
|
||||
{
|
||||
0xf9,
|
||||
0xef,
|
||||
0xd4,
|
||||
0xe1,
|
||||
0x3a,
|
||||
0xea,
|
||||
0x6b,
|
||||
0xd8,
|
||||
},
|
||||
{
|
||||
0x86,
|
||||
0xd6,
|
||||
0x7a,
|
||||
0x40,
|
||||
0xec,
|
||||
0x42,
|
||||
0x76,
|
||||
0xdc,
|
||||
},
|
||||
{
|
||||
0x3f,
|
||||
0x62,
|
||||
0x92,
|
||||
0xec,
|
||||
0xcc,
|
||||
0xa9,
|
||||
0x7e,
|
||||
0x35,
|
||||
},
|
||||
{
|
||||
0xcb,
|
||||
0xd9,
|
||||
0x2e,
|
||||
0xe7,
|
||||
0x24,
|
||||
0xd4,
|
||||
0x21,
|
||||
0x09,
|
||||
},
|
||||
{
|
||||
0x36,
|
||||
0x8d,
|
||||
0xf6,
|
||||
0x80,
|
||||
0x8d,
|
||||
0x40,
|
||||
0x3d,
|
||||
0x79,
|
||||
},
|
||||
{
|
||||
0x5b,
|
||||
0x38,
|
||||
0xc8,
|
||||
0x1c,
|
||||
0x67,
|
||||
0xc8,
|
||||
0xae,
|
||||
0x4c,
|
||||
},
|
||||
{
|
||||
0x95,
|
||||
0xab,
|
||||
0x71,
|
||||
0x89,
|
||||
0xd4,
|
||||
0x39,
|
||||
0xac,
|
||||
0xb3,
|
||||
},
|
||||
{
|
||||
0xa9,
|
||||
0x1a,
|
||||
0x52,
|
||||
0xc0,
|
||||
0x25,
|
||||
0x32,
|
||||
0x70,
|
||||
0x24,
|
||||
},
|
||||
{
|
||||
0x5b,
|
||||
0x00,
|
||||
0x87,
|
||||
0xc6,
|
||||
0x95,
|
||||
0x28,
|
||||
0xac,
|
||||
0xea,
|
||||
},
|
||||
{
|
||||
0x1e,
|
||||
0x30,
|
||||
0xf3,
|
||||
0xad,
|
||||
0x27,
|
||||
0xdc,
|
||||
0xb1,
|
||||
0x5a,
|
||||
},
|
||||
{
|
||||
0x69,
|
||||
0x7f,
|
||||
0x5c,
|
||||
0x9a,
|
||||
0x90,
|
||||
0x32,
|
||||
0x4e,
|
||||
0xd4,
|
||||
},
|
||||
{
|
||||
0x49,
|
||||
0x5c,
|
||||
0x0f,
|
||||
0x99,
|
||||
0x55,
|
||||
0x57,
|
||||
0xdc,
|
||||
0x38,
|
||||
},
|
||||
{
|
||||
0x94,
|
||||
0x27,
|
||||
0x20,
|
||||
0x2a,
|
||||
0x3c,
|
||||
0x29,
|
||||
0xf9,
|
||||
0x4d,
|
||||
},
|
||||
{
|
||||
0xa9,
|
||||
0xea,
|
||||
0xa8,
|
||||
0xc0,
|
||||
0x4b,
|
||||
0xa9,
|
||||
0x3e,
|
||||
0x3e,
|
||||
},
|
||||
{
|
||||
0xee,
|
||||
0xa4,
|
||||
0xc1,
|
||||
0x73,
|
||||
0x7d,
|
||||
0x01,
|
||||
0x12,
|
||||
0x18,
|
||||
},
|
||||
{
|
||||
0x91,
|
||||
0x2d,
|
||||
0x56,
|
||||
0x8f,
|
||||
0xd8,
|
||||
0xf6,
|
||||
0x5a,
|
||||
0x49,
|
||||
},
|
||||
{
|
||||
0x56,
|
||||
0x91,
|
||||
0x95,
|
||||
0x96,
|
||||
0xb0,
|
||||
0xff,
|
||||
0x5c,
|
||||
0x97,
|
||||
},
|
||||
{
|
||||
0x02,
|
||||
0x44,
|
||||
0x5a,
|
||||
0x79,
|
||||
0x98,
|
||||
0xf5,
|
||||
0x50,
|
||||
0xe1,
|
||||
},
|
||||
{
|
||||
0x86,
|
||||
0xec,
|
||||
0x46,
|
||||
0x6c,
|
||||
0xe7,
|
||||
0x1d,
|
||||
0x1f,
|
||||
0xb2,
|
||||
},
|
||||
{
|
||||
0x35,
|
||||
0x95,
|
||||
0x69,
|
||||
0xe7,
|
||||
0xd2,
|
||||
0x89,
|
||||
0xe3,
|
||||
0xbc,
|
||||
},
|
||||
{
|
||||
0x87,
|
||||
0x1b,
|
||||
0x05,
|
||||
0xca,
|
||||
0x62,
|
||||
0xbb,
|
||||
0x7c,
|
||||
0x96,
|
||||
},
|
||||
{
|
||||
0xa1,
|
||||
0xa4,
|
||||
0x92,
|
||||
0xf9,
|
||||
0x42,
|
||||
0xf1,
|
||||
0x5f,
|
||||
0x1d,
|
||||
},
|
||||
{
|
||||
0x12,
|
||||
0xec,
|
||||
0x26,
|
||||
0x7f,
|
||||
0xf6,
|
||||
0x09,
|
||||
0x5b,
|
||||
0x6e,
|
||||
},
|
||||
{
|
||||
0x5d,
|
||||
0x1b,
|
||||
0x5e,
|
||||
0xa1,
|
||||
0xb2,
|
||||
0x31,
|
||||
0xd8,
|
||||
0x9d,
|
||||
},
|
||||
{
|
||||
0xd8,
|
||||
0xcf,
|
||||
0xb4,
|
||||
0x45,
|
||||
0x3f,
|
||||
0x92,
|
||||
0xee,
|
||||
0x54,
|
||||
},
|
||||
{
|
||||
0xd6,
|
||||
0x76,
|
||||
0x28,
|
||||
0x90,
|
||||
0xbf,
|
||||
0x26,
|
||||
0xe4,
|
||||
0x60,
|
||||
},
|
||||
{
|
||||
0x31,
|
||||
0x35,
|
||||
0x63,
|
||||
0xa4,
|
||||
0xb7,
|
||||
0xed,
|
||||
0x5c,
|
||||
0xf3,
|
||||
},
|
||||
{
|
||||
0xf9,
|
||||
0x0b,
|
||||
0x3a,
|
||||
0xb5,
|
||||
0x72,
|
||||
0xd4,
|
||||
0x66,
|
||||
0x93,
|
||||
},
|
||||
{
|
||||
0x2e,
|
||||
0xa6,
|
||||
0x3c,
|
||||
0x71,
|
||||
0xbf,
|
||||
0x32,
|
||||
0x60,
|
||||
0x87,
|
||||
},
|
||||
};
|
||||
103
3rd/pcre2/LICENCE.md
Normal file
103
3rd/pcre2/LICENCE.md
Normal file
@@ -0,0 +1,103 @@
|
||||
PCRE2 License
|
||||
=============
|
||||
|
||||
| SPDX-License-Identifier: | BSD-3-Clause WITH PCRE2-exception |
|
||||
|---------|-------|
|
||||
|
||||
PCRE2 is a library of functions to support regular expressions whose syntax
|
||||
and semantics are as close as possible to those of the Perl 5 language.
|
||||
|
||||
Releases 10.00 and above of PCRE2 are distributed under the terms of the "BSD"
|
||||
licence, as specified below, with one exemption for certain binary
|
||||
redistributions. The documentation for PCRE2, supplied in the "doc" directory,
|
||||
is distributed under the same terms as the software itself. The data in the
|
||||
testdata directory is not copyrighted and is in the public domain.
|
||||
|
||||
The basic library functions are written in C and are freestanding. Also
|
||||
included in the distribution is a just-in-time compiler that can be used to
|
||||
optimize pattern matching. This is an optional feature that can be omitted when
|
||||
the library is built.
|
||||
|
||||
|
||||
COPYRIGHT
|
||||
---------
|
||||
|
||||
### The basic library functions
|
||||
|
||||
Written by: Philip Hazel
|
||||
Email local part: Philip.Hazel
|
||||
Email domain: gmail.com
|
||||
|
||||
Retired from University of Cambridge Computing Service,
|
||||
Cambridge, England.
|
||||
|
||||
Copyright (c) 1997-2007 University of Cambridge
|
||||
Copyright (c) 2007-2024 Philip Hazel
|
||||
All rights reserved.
|
||||
|
||||
### PCRE2 Just-In-Time compilation support
|
||||
|
||||
Written by: Zoltan Herczeg
|
||||
Email local part: hzmester
|
||||
Email domain: freemail.hu
|
||||
|
||||
Copyright (c) 2010-2024 Zoltan Herczeg
|
||||
All rights reserved.
|
||||
|
||||
### Stack-less Just-In-Time compiler
|
||||
|
||||
Written by: Zoltan Herczeg
|
||||
Email local part: hzmester
|
||||
Email domain: freemail.hu
|
||||
|
||||
Copyright (c) 2009-2024 Zoltan Herczeg
|
||||
All rights reserved.
|
||||
|
||||
### All other contributions
|
||||
|
||||
Many other contributors have participated in the authorship of PCRE2. As PCRE2
|
||||
has never required a Contributor Licensing Agreement, or other copyright
|
||||
assignment agreement, all contributions have copyright retained by each
|
||||
original contributor or their employer.
|
||||
|
||||
|
||||
THE "BSD" LICENCE
|
||||
-----------------
|
||||
|
||||
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 notices,
|
||||
this list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright
|
||||
notices, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
|
||||
* Neither the name of the University of Cambridge nor the names of any
|
||||
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 THE COPYRIGHT OWNER OR 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.
|
||||
|
||||
|
||||
EXEMPTION FOR BINARY LIBRARY-LIKE PACKAGES
|
||||
------------------------------------------
|
||||
|
||||
The second condition in the BSD licence (covering binary redistributions) does
|
||||
not apply all the way down a chain of software. If binary package A includes
|
||||
PCRE2, it must respect the condition, but if package B is software that
|
||||
includes package A, the condition is not imposed on package B unless it uses
|
||||
PCRE2 independently.
|
||||
|
||||
End
|
||||
@@ -5,7 +5,7 @@ if (POLICY CMP0177)
|
||||
endif()
|
||||
project(PIP)
|
||||
set(PIP_MAJOR 5)
|
||||
set(PIP_MINOR 2)
|
||||
set(PIP_MINOR 6)
|
||||
set(PIP_REVISION 1)
|
||||
set(PIP_SUFFIX )
|
||||
set(PIP_COMPANY SHS)
|
||||
@@ -67,8 +67,13 @@ set(PIP_DLL_DIR "${CMAKE_CURRENT_BINARY_DIR}" CACHE STRING "")
|
||||
option(ICU "ICU support for convert codepages" ${_ICU_DEFAULT})
|
||||
option(STD_IOSTREAM "Building with std iostream operators support" OFF)
|
||||
option(INTROSPECTION "Build with introspection" OFF)
|
||||
option(TESTS "Build tests and perform their before install step" OFF)
|
||||
option(TESTS "Build tests" OFF)
|
||||
option(TESTS_RUN "Run tests before install step" OFF)
|
||||
option(COVERAGE "Build project with coverage info" OFF)
|
||||
option(PIP_FFTW_F "Support fftw module for float" ON)
|
||||
option(PIP_FFTW_L "Support fftw module for long double" ON)
|
||||
option(PIP_FFTW_Q "Support fftw module for quad double" OFF)
|
||||
option(PIP_MANUAL_TEST "Build dev test (main.cpp)" OFF)
|
||||
set(PIP_UTILS 1)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED TRUE)
|
||||
set(CMAKE_CXX_STANDARD 11)
|
||||
@@ -113,8 +118,10 @@ macro(pip_module NAME LIBS LABEL INCLUDES SOURCES MSG)
|
||||
list(REMOVE_ITEM HS ${PHS})
|
||||
endif()
|
||||
if (NOT "x${SOURCES}" STREQUAL "x")
|
||||
file(GLOB_RECURSE ASRC "${SOURCES}/*.cpp" "${SOURCES}/*.c")
|
||||
foreach (_s ${SOURCES})
|
||||
file(GLOB_RECURSE ASRC "${_s}/*.cpp" "${_s}/*.c")
|
||||
list(APPEND CPPS ${ASRC})
|
||||
endforeach()
|
||||
endif()
|
||||
list(APPEND HDRS ${HS})
|
||||
list(APPEND PHDRS ${PHS})
|
||||
@@ -355,10 +362,13 @@ endif()
|
||||
if(WIN32)
|
||||
add_definitions(-DPSAPI_VERSION=1)
|
||||
if(${C_COMPILER} STREQUAL "cl.exe")
|
||||
set(CMAKE_CXX_FLAGS "/O2 /Ob2 /Ot /W0")
|
||||
set(CMAKE_CXX_FLAGS "/O2 /Ob2 /Ot /W0 /EH-")
|
||||
endif()
|
||||
else()
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC")
|
||||
if (NOT DEFINED ANDROID_PLATFORM)
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-exceptions")
|
||||
endif()
|
||||
if(DEFINED ENV{QNX_HOST} OR PIP_FREERTOS)
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ftemplate-depth-32")
|
||||
endif()
|
||||
@@ -377,7 +387,7 @@ endif()
|
||||
add_subdirectory("3rd/pcre2" EXCLUDE_FROM_ALL)
|
||||
list(APPEND LIBS_MAIN pcre2-16-static)
|
||||
|
||||
pip_module(main "${LIBS_MAIN}" "PIP main library" "" "${PIP_3PL_DIR}/BLAKE2" "")
|
||||
pip_module(main "${LIBS_MAIN}" "PIP main library" "" "${PIP_3PL_DIR}/BLAKE2;${PIP_3PL_DIR}/SipHash" "")
|
||||
|
||||
generate_export_header(pip)
|
||||
list(APPEND HDRS "${CMAKE_CURRENT_BINARY_DIR}/pip_export.h")
|
||||
@@ -436,8 +446,23 @@ if (NOT CROSSTOOLS)
|
||||
if (PIP_BUILD_FFTW)
|
||||
# Check if PIP support fftw3 for PIFFT using in math module
|
||||
set(FFTW_LIB_NAME fftw3)
|
||||
set(FFTW_LIB_SUFFIXES "" "f" "l" "q")
|
||||
set(FFTW_LIB_SUFFIXES "")
|
||||
if (PIP_FFTW_F)
|
||||
list(APPEND FFTW_LIB_SUFFIXES "f")
|
||||
endif()
|
||||
if (PIP_FFTW_L)
|
||||
list(APPEND FFTW_LIB_SUFFIXES "l")
|
||||
endif()
|
||||
if (PIP_FFTW_Q)
|
||||
list(APPEND FFTW_LIB_SUFFIXES "q")
|
||||
endif()
|
||||
if (NOT "${FFTW_LIB_SUFFIXES}" STREQUAL "")
|
||||
set(FFTW_LIB_SUFFIXES ";${FFTW_LIB_SUFFIXES}")
|
||||
else()
|
||||
list(APPEND FFTW_LIB_SUFFIXES "" "_")
|
||||
endif()
|
||||
set(FFTW_LIB_SUFFIXES2 "" "-3")
|
||||
set(FFTW_MSG "")
|
||||
set(FFTW_LIBS)
|
||||
set(FFTW_ABS_LIBS)
|
||||
set(CMAKE_REQUIRED_INCLUDES fftw3.h)
|
||||
@@ -452,6 +477,10 @@ if (NOT CROSSTOOLS)
|
||||
set(${FFTW_CLN}_FOUND FALSE)
|
||||
set(${FFTW_CLNT}_FOUND FALSE)
|
||||
if(${FFTW_CLN}_LIBRARIES)
|
||||
if (NOT "${FFTW_MSG}" STREQUAL "")
|
||||
set(FFTW_MSG "${FFTW_MSG}, ")
|
||||
endif()
|
||||
set(FFTW_MSG "${FFTW_MSG}${FFTW_CLN}")
|
||||
set(${FFTW_CLN}_FOUND TRUE)
|
||||
list(APPEND FFTW_LIBS "${FFTW_CLN}")
|
||||
list(APPEND FFTW_ABS_LIBS "${${FFTW_CLN}_LIBRARIES}")
|
||||
@@ -475,7 +504,7 @@ if (NOT CROSSTOOLS)
|
||||
endforeach()
|
||||
endforeach()
|
||||
if(FFTW_LIBS)
|
||||
pip_module(fftw "${FFTW_LIBS}" "PIP FFTW support" "" "" "")
|
||||
pip_module(fftw "${FFTW_LIBS}" "PIP FFTW support" "" "" " (${FFTW_MSG})")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
@@ -568,6 +597,7 @@ if (NOT CROSSTOOLS)
|
||||
#target_link_libraries(pip_plugin pip)
|
||||
|
||||
if (NOT DEFINED ANDROID_PLATFORM)
|
||||
if (PIP_MANUAL_TEST)
|
||||
if(microhttpd_FOUND AND curl_FOUND)
|
||||
add_executable(pip_test "main.cpp")
|
||||
target_link_libraries(pip_test pip pip_io_utils pip_client_server pip_http_server pip_http_client)
|
||||
@@ -578,6 +608,7 @@ if (NOT CROSSTOOLS)
|
||||
endif()
|
||||
endif()
|
||||
endif()
|
||||
endif()
|
||||
|
||||
else()
|
||||
|
||||
@@ -799,6 +830,9 @@ if (PIP_TESTS_LIST)
|
||||
foreach(_test ${PIP_TESTS_LIST})
|
||||
message(" * ${_test}")
|
||||
endforeach()
|
||||
if (TESTS_RUN)
|
||||
message("TESTS_RUN ON -> Run tests before install step")
|
||||
endif()
|
||||
else()
|
||||
message(" Tests: skip (tests off)")
|
||||
endif()
|
||||
|
||||
115
README.md
115
README.md
@@ -40,3 +40,118 @@ You should add ${<out_var>} to your target.
|
||||
[🇷🇺 Онлайн документация](https://shstk.ru/pip/html/ru/index.html)
|
||||
|
||||
[🇷🇺 Qt-help](https://shstk.ru/pip/pip_ru.qch)
|
||||
|
||||
## Основные опции сборки
|
||||
|
||||
### Стандартные опции (option())
|
||||
| Опция | Описание | По умолчанию |
|
||||
|-------|----------|--------------|
|
||||
| `ICU` | ICU support для конвертации кодовых страниц | ON (кроме Win/Android/Apple) |
|
||||
| `STD_IOSTREAM` | Поддержка std::iostream операторов | OFF |
|
||||
| `INTROSPECTION` | Сборка с интроспекцией | OFF |
|
||||
| `TESTS` | Сборка тестов | OFF |
|
||||
| `COVERAGE` | Сборка с информацией о покрытии | OFF |
|
||||
| `PIP_FFTW_F` | Поддержка FFTW для float | ON |
|
||||
| `PIP_FFTW_L` | Поддержка FFTW для long double | ON |
|
||||
| `PIP_FFTW_Q` | Поддержка FFTW для quad double | OFF |
|
||||
|
||||
### Опции модулей (PIP_BUILD_*)
|
||||
| Опция | Модуль |
|
||||
|-------|--------|
|
||||
| `PIP_BUILD_CONSOLE` | console |
|
||||
| `PIP_BUILD_CRYPT` | crypt (требует libsodium) |
|
||||
| `PIP_BUILD_COMPRESS` | compress (требует zlib) |
|
||||
| `PIP_BUILD_USB` | usb |
|
||||
| `PIP_BUILD_FFTW` | fftw |
|
||||
| `PIP_BUILD_OPENCL` | opencl |
|
||||
| `PIP_BUILD_IO_UTILS` | io_utils |
|
||||
| `PIP_BUILD_CLIENT_SERVER` | client_server |
|
||||
| `PIP_BUILD_CLOUD` | cloud |
|
||||
| `PIP_BUILD_LUA` | lua |
|
||||
| `PIP_BUILD_HTTP_CLIENT` | http_client (требует libcurl) |
|
||||
| `PIP_BUILD_HTTP_SERVER` | http_server (требует libmicrohttpd) |
|
||||
|
||||
### Дополнительные переменные
|
||||
| Переменная | Описание |
|
||||
|------------|----------|
|
||||
| `PIP_BUILD_DEBUG` | Сборка debug версии |
|
||||
| `PIP_FREERTOS` | Режим сборки для FreeRTOS |
|
||||
| `CROSSTOOLS` | Собрать инструменты кросс-сборки под хостовую систему (pip_cmg, pip_rc, ...) |
|
||||
| `LOCAL` | Локальная установка (bin/lib/include) |
|
||||
| `PIP_CONTAINERS_MIN_ALLOC` | Переопределить минимальный размер аллокации контейнеров |
|
||||
| `PIP_CONTAINERS_MAX_POT_ALLOC` | Переопределить максимальный размер дополнительной аллокации (поддерживает X_KiB, X_MiB) |
|
||||
|
||||
### Примеры использования
|
||||
```bash
|
||||
# Базовая сборка с тестами
|
||||
cmake -B build -DTESTS=ON
|
||||
|
||||
# Сборка с покрытием и ICU
|
||||
cmake -B build -DTESTS=ON -DCOVERAGE=ON -DICU=ON
|
||||
|
||||
# Отключение отдельных модулей
|
||||
cmake -B build -DPIP_BUILD_CRYPT=OFF -DPIP_BUILD_OPENCL=OFF
|
||||
|
||||
# Переопределение параметров контейнеров
|
||||
cmake -B build -DPIP_CONTAINERS_MIN_ALLOC=64
|
||||
|
||||
# Локальная установка
|
||||
cmake -B build -DLOCAL=ON
|
||||
```
|
||||
|
||||
## PIP Dependencies
|
||||
|
||||
### Встроенные (included in 3rd/)
|
||||
|
||||
| Библиотека | Назначение | Модуль PIP |
|
||||
|------------|------------|------------|
|
||||
| **PCRE2** | Регулярные выражения | main (internal) |
|
||||
| **BLAKE2** | Хеширование | main (internal) |
|
||||
| **SipHash** | Хеширование | main (internal) |
|
||||
| **Lua** | Lua scripting | lua |
|
||||
| **LuaBridge** | Lua bindings | lua |
|
||||
|
||||
### Внешние (системные)
|
||||
|
||||
| Библиотека | Опция | Модуль PIP |
|
||||
|------------|-------|------------|
|
||||
| **ICU** | `-DICU=ON` | main (string conversion) |
|
||||
| **zlib** | `PIP_BUILD_COMPRESS` | compress |
|
||||
| **libsodium** | `PIP_BUILD_CRYPT` | crypt, io_utils, cloud |
|
||||
| **libusb** | `PIP_BUILD_USB` | usb |
|
||||
| **FFTW3** (+ threads) | `PIP_BUILD_FFTW` | fftw |
|
||||
| **OpenCL** | `PIP_BUILD_OPENCL` | opencl |
|
||||
| **libmicrohttpd** | `PIP_BUILD_HTTP_SERVER` | http_server |
|
||||
| **libcurl** | `PIP_BUILD_HTTP_CLIENT` | http_client |
|
||||
|
||||
### Опциональные (тесты/документация)
|
||||
|
||||
| Инструмент | Назначение |
|
||||
|------------|------------|
|
||||
| **Google Test** | Тестирование (fetched automatically) |
|
||||
| **Doxygen** | Генерация документации |
|
||||
|
||||
|
||||
### Схема зависимостей модулей
|
||||
|
||||
```
|
||||
main (core)
|
||||
├── PCRE2 (встроен)
|
||||
├── BLAKE2 (встроен)
|
||||
├── SipHash (встроен)
|
||||
└── ICU (опционально)
|
||||
|
||||
console → main
|
||||
compress → zlib
|
||||
crypt → libsodium
|
||||
usb → libusb
|
||||
fftw → FFTW3
|
||||
opencl → OpenCL
|
||||
io_utils → [crypt, если доступен]
|
||||
client_server → io_utils
|
||||
cloud → io_utils, crypt
|
||||
lua → Lua (встроен), LuaBridge (встроен)
|
||||
http_server → libmicrohttpd
|
||||
http_client → libcurl
|
||||
```
|
||||
|
||||
|
||||
26
doc/pages/application.md
Normal file
26
doc/pages/application.md
Normal file
@@ -0,0 +1,26 @@
|
||||
\~english \page application Application-level tools
|
||||
\~russian \page application Инструменты уровня приложения
|
||||
|
||||
\~english
|
||||
|
||||
The Application module provides classes commonly needed at program startup and runtime:
|
||||
|
||||
* **PICLI** — command-line argument parser. Add named arguments (e.g. \c addArgument("debug") for \c -d / \c --debug), check presence with \a hasArgument(), optionally read values. Used in \ref using_basic for console and debug flags.
|
||||
* **PILog** — high-level logging with categories and levels. Configure sinks and severity; write log lines from anywhere in the process.
|
||||
* **PISystemMonitor** — snapshot of system resources (CPU, memory, etc.). Query current stats or subscribe to periodic updates.
|
||||
* **PISingleApplication** — ensure only one instance of the application runs; optional inter-process messaging when a second instance is started.
|
||||
* **PITranslator** — translation support: load catalogs, select language, translate strings at runtime.
|
||||
|
||||
All are included via the main PIP library or the Application umbrella (\a piapplicationmodule.h). For CLI and logging, see \ref using_basic; for full API details see the headers \a picli.h, \a pilog.h, \a pisystemmonitor.h, \a pisingleapplication.h, \a pitranslator.h.
|
||||
|
||||
\~russian
|
||||
|
||||
Модуль Application предоставляет классы, часто нужные при запуске и работе приложения:
|
||||
|
||||
* **PICLI** — разбор аргументов командной строки. Добавление именованных аргументов (\c addArgument("debug") для \c -d / \c --debug), проверка наличия \a hasArgument(), при необходимости чтение значений. Используется в \ref using_basic для флагов консоли и отладки.
|
||||
* **PILog** — логирование с категориями и уровнями. Настройка приёмников и уровня детализации; запись строк лога из любой части процесса.
|
||||
* **PISystemMonitor** — снимок ресурсов системы (CPU, память и т.д.). Запрос текущей статистики или подписка на периодические обновления.
|
||||
* **PISingleApplication** — гарантия единственного экземпляра приложения; при необходимости обмен сообщениями между процессами при запуске второго экземпляра.
|
||||
* **PITranslator** — поддержка перевода: загрузка каталогов, выбор языка, перевод строк в runtime.
|
||||
|
||||
Всё подключается через основную библиотеку PIP или зонтичный заголовок (\a piapplicationmodule.h). Для CLI и лога см. \ref using_basic; детали API — в заголовках \a picli.h, \a pilog.h, \a pisystemmonitor.h, \a pisingleapplication.h, \a pitranslator.h.
|
||||
56
doc/pages/chunk_stream.md
Normal file
56
doc/pages/chunk_stream.md
Normal file
@@ -0,0 +1,56 @@
|
||||
\~english \page chunk_stream Chunk stream and versioned serialization
|
||||
\~russian \page chunk_stream Поток чанков и версионная сериализация
|
||||
|
||||
\~english
|
||||
|
||||
\a PIChunkStream is a binary stream where data is stored as **chunks**: each chunk has an integer \e id and a value. Reading is id-based, so you can add or reorder fields over time and stay backward compatible: old readers ignore unknown ids, new readers can skip optional ids.
|
||||
|
||||
Two format versions exist (\a PIChunkStream::Version_1 and \a Version_2); the writer chooses the version, the reader detects it automatically. By default new data is written in Version_2.
|
||||
|
||||
# When to use
|
||||
|
||||
Use chunk streams when:
|
||||
* You need to extend structures without breaking existing stored data (add new fields with new ids).
|
||||
* You want optional or reordered fields in a single stream.
|
||||
* You use \ref code_model to generate serialization: with default (chunk) mode, \c pip_cmg emits operators that read/write via \a PIChunkStream and field ids (see \ref code_model "code_model" for PIMETA \c id and \c simple-stream / \c no-stream).
|
||||
|
||||
For fixed, non-extensible layouts, plain \a PIBinaryStream operators (see \ref iostream) are enough.
|
||||
|
||||
# Usage
|
||||
|
||||
Build a \a PIChunkStream from a \a PIByteArray (read or read-write). Write with \c cs << cs.chunk(id, value) or \c add(id, value); read with \c read() to get the next id, then \c get(value). Call \c data() to get the byte buffer for storing or sending. Example (conceptually as in code_model output):
|
||||
|
||||
\code{.cpp}
|
||||
PIByteArray buf;
|
||||
PIChunkStream cs(&buf);
|
||||
cs << cs.chunk(1, i) << cs.chunk(2, s);
|
||||
// later:
|
||||
PIChunkStream reader(buf);
|
||||
while (!reader.atEnd()) {
|
||||
switch (reader.read()) {
|
||||
case 1: reader.get(i); break;
|
||||
case 2: reader.get(s); break;
|
||||
}
|
||||
}
|
||||
\endcode
|
||||
|
||||
Generated operators for structs use the same pattern; see \ref code_model.
|
||||
|
||||
\~russian
|
||||
|
||||
\a PIChunkStream — бинарный поток, в котором данные хранятся **чанками**: у каждого чанка целочисленный \e id и значение. Чтение идёт по id, поэтому можно добавлять или менять порядок полей с сохранением обратной совместимости: старые читатели игнорируют неизвестные id, новые могут пропускать необязательные.
|
||||
|
||||
Есть две версии формата (\a PIChunkStream::Version_1 и \a Version_2); версию выбирает запись, при чтении она определяется автоматически. По умолчанию запись идёт в Version_2.
|
||||
|
||||
# Когда использовать
|
||||
|
||||
Имеет смысл использовать поток чанков, когда:
|
||||
* Нужно расширять структуры без поломки уже сохранённых данных (новые поля — новые id).
|
||||
* Нужны необязательные или переставляемые поля в одном потоке.
|
||||
* Используется \ref code_model для генерации сериализации: в режиме по умолчанию (chunk) \c pip_cmg выдаёт операторы через \a PIChunkStream и id полей (см. \ref code_model по PIMETA \c id и \c simple-stream / \c no-stream).
|
||||
|
||||
Для фиксированных неизменяемых форматов достаточно обычных операторов \a PIBinaryStream (см. \ref iostream).
|
||||
|
||||
# Использование
|
||||
|
||||
Создают \a PIChunkStream из \a PIByteArray (чтение или чтение/запись). Запись: \c cs << cs.chunk(id, value) или \c add(id, value); чтение: \c read() — следующий id, затем \c get(value). \c data() возвращает буфер для сохранения или передачи. Примеры генерации операторов — в \ref code_model.
|
||||
46
doc/pages/client_server.md
Normal file
46
doc/pages/client_server.md
Normal file
@@ -0,0 +1,46 @@
|
||||
\~english \page client_server TCP client-server
|
||||
\~russian \page client_server TCP клиент-сервер
|
||||
|
||||
\~english
|
||||
|
||||
The ClientServer module provides a TCP server that accepts connections and manages per-client objects, and an active client that connects to a server. All in the \a PIClientServer namespace.
|
||||
|
||||
# Server
|
||||
|
||||
\a PIClientServer::Server listens on an address (e.g. \a listenAll(port) for all interfaces). For each accepted connection the server creates a \a PIClientServer::ServerClient. You can override the client type and handle client lifecycle (e.g. data received, disconnected). Use \a getMaxClients() / \a setMaxClients() to limit simultaneous connections. \a listen(addr) starts listening, \a stopServer() stops the server, \a closeAll() closes all current clients.
|
||||
|
||||
# ServerClient
|
||||
|
||||
\a PIClientServer::ServerClient is the server-side representation of one connected client. The server creates and owns these objects. Override \a aboutDelete() if you need cleanup before the client is removed. Use the base API (\a ClientBase) to send and receive data on the connection.
|
||||
|
||||
# Client
|
||||
|
||||
\a PIClientServer::Client is the active client: it connects to a remote server (address/port). After connecting you use the same send/receive API as on the server side. Connect, exchange data, then disconnect when done.
|
||||
|
||||
# Typical flow
|
||||
|
||||
Server: construct \a Server, optionally set max clients and callbacks, call \a listen() or \a listenAll(port). Handle client events (new client, data, disconnect) in your overrides or via the provided hooks. Client: construct \a Client, connect to server address, send/receive, disconnect.
|
||||
|
||||
See \a piclientserver_server.h, \a piclientserver_client.h, \a piclientserver_client_base.h for the full API.
|
||||
|
||||
\~russian
|
||||
|
||||
Модуль ClientServer предоставляет TCP-сервер, принимающий соединения и управляющий объектами клиентов, и активный клиент, подключающийся к серверу. Всё в пространстве имён \a PIClientServer.
|
||||
|
||||
# Сервер
|
||||
|
||||
\a PIClientServer::Server слушает адрес (например \a listenAll(port) на всех интерфейсах). Для каждого принятого соединения создаётся \a PIClientServer::ServerClient. Можно подменить тип клиента и обрабатывать жизненный цикл (данные, отключение). \a getMaxClients() / \a setMaxClients() ограничивают число одновременных соединений. \a listen(addr) — запуск, \a stopServer() — остановка, \a closeAll() — закрытие всех клиентов.
|
||||
|
||||
# Серверный клиент
|
||||
|
||||
\a PIClientServer::ServerClient — серверное представление одного подключённого клиента. Объекты создаёт и владеет сервер. Переопределите \a aboutDelete() при необходимости очистки перед удалением. Отправка и приём данных — через базовый API (\a ClientBase).
|
||||
|
||||
# Клиент
|
||||
|
||||
\a PIClientServer::Client — активный клиент: подключается к удалённому серверу (адрес/порт). После подключения используется тот же API отправки/приёма. Подключение, обмен, отключение.
|
||||
|
||||
# Типичный сценарий
|
||||
|
||||
Сервер: создать \a Server, при необходимости задать лимит клиентов и обработчики, вызвать \a listen() или \a listenAll(port). Обрабатывать события клиентов в переопределениях или через хуки. Клиент: создать \a Client, подключиться к адресу сервера, обмен данными, отключиться.
|
||||
|
||||
Полный API: \a piclientserver_server.h, \a piclientserver_client.h, \a piclientserver_client_base.h.
|
||||
@@ -3,6 +3,26 @@
|
||||
|
||||
\~english
|
||||
|
||||
# Introduction
|
||||
|
||||
Code generation helps when you need string representation of entities (classes, enums, etc.) or automated serialization/deserialization of structures and classes. For example, you may need a list of "name" = "value" pairs from an enumeration for a UI, or to traverse nested structures with metadata. You can describe a structure of any complexity, assign field IDs, and get ready-made operators for \a PIBinaryStream with versioning and backward compatibility.
|
||||
|
||||
# pip_cmg
|
||||
|
||||
PIP provides the \c pip_cmg utility: it takes source files, include paths, and options, and produces a .h/.cpp pair. Depending on options, the output may include: entity metadata; serialization operators; and the ability to get a \a PIVariant for any member by name.
|
||||
|
||||
Processing options: \c -s (do not follow #include); \c -I<include_dir> (add include path); \c -D<define> (add macro; \c PICODE is always defined).
|
||||
|
||||
Creation options: \c -A (create all); \c -M (metadata); \c -E (enums); \c -S (serialization operators); \c -G (get value by name); \c -o <output_file> (output base name without extension).
|
||||
|
||||
# CMake
|
||||
|
||||
The \c pip_code_model CMake macro invokes \c pip_cmg and keeps the model up to date. Call format: \c pip_code_model(<out_var> file0 [file1 ...] [OPTIONS ...] [NAME name]). Parameters: \c out_var receives generated file paths; \c file... are sources; \c OPTIONS are passed to \c pip_cmg (e.g. \c "-Es"); \c NAME sets the model file base (default \c "ccm_${PROJECT_NAME}"). The macro adds PIP include paths. Run \c pip_cmg -v for current options.
|
||||
|
||||
# Details
|
||||
|
||||
Metadata: attach \c PIMETA(...) to types, members or enums; read at runtime via \a PICODEINFO::classes() and \a PICODEINFO::enums(). Serialization: struct-level \c PIMETA(simple-stream) or \c PIMETA(no-stream), or per-member chunk ids (default); see \ref chunk_stream. Add the generated .h/.cpp to your target and \c #include the generated header; metadata loads before \c main().
|
||||
|
||||
\~russian
|
||||
|
||||
# Введение
|
||||
|
||||
14
doc/pages/config.md
Normal file
14
doc/pages/config.md
Normal file
@@ -0,0 +1,14 @@
|
||||
\~english \page config Configuration from file
|
||||
\~russian \page config Конфигурация из файла
|
||||
|
||||
\~english
|
||||
|
||||
\a PIConfig parses and writes configuration from files, strings, or any \a PIIODevice. The internal model is a tree of entries; each node is \a PIConfig::Entry, and a list of entries is \a PIConfig::Branch. Use dotted paths to get values, e.g. \c getValue("section.key.subkey"). Supports INI-style \c [section] prefixes, multiline values, and \c include directives resolved at parse time.
|
||||
|
||||
Typical use: open a file or device, then call \c getValue(name) or \c getValue(name, default) on the root or on a \a PIConfig::Branch. Overloads exist for string, numeric, and bool defaults. To configure an I/O device from config, pass \a PIConfig::Entry pointers to \a PIIODevice::configure(); see \a PIIODevice and device-specific headers.
|
||||
|
||||
\~russian
|
||||
|
||||
\a PIConfig разбирает и записывает конфигурацию из файлов, строк или любого \a PIIODevice. Внутренняя модель — дерево записей; узел — \a PIConfig::Entry, список узлов — \a PIConfig::Branch. Доступ по точечным путям, например \c getValue("section.key.subkey"). Поддерживаются префиксы секций в стиле INI (\c [section]), многострочные значения и директивы \c include, разрешаемые при разборе.
|
||||
|
||||
Типичное использование: открыть файл или устройство, затем вызывать \c getValue(name) или \c getValue(name, default) от корня или от \a PIConfig::Branch. Есть перегрузки для строковых, числовых и булевых значений по умолчанию. Для настройки устройства ввода-вывода из конфига в \a PIIODevice::configure() передают указатели на \a PIConfig::Entry; см. \a PIIODevice и заголовки конкретных устройств.
|
||||
50
doc/pages/connection.md
Normal file
50
doc/pages/connection.md
Normal file
@@ -0,0 +1,50 @@
|
||||
\~english \page connection Complex I/O (PIConnection)
|
||||
\~russian \page connection Сложный ввод-вывод (PIConnection)
|
||||
|
||||
\~english
|
||||
|
||||
\a PIConnection is an abstract layer over physical I/O devices: it manages a **device pool**, **filters** (packet extraction), **senders** (timed output), and **diagnostics**. Several connections can share one physical device through the pool; each device has an associated read thread that you start/stop with \a startThreadedRead() and \a stopThreadedRead().
|
||||
|
||||
# Device pool
|
||||
|
||||
The device pool is a single per-application container of unique devices. Each \a PIConnection talks to real hardware through this pool, so one serial port or socket can feed multiple logical connections.
|
||||
|
||||
# Filters
|
||||
|
||||
A filter is a \a PIPacketExtractor plus a set of bound devices or other filters. When the read thread gets data from a device, that data can be passed to one or more filters. Filters have unique names; use \a filter(name) to get the \a PIPacketExtractor*, and \a filterBoundedDevices() for the list of bound devices/filters. One filter can receive from several sources and be bound to several others.
|
||||
|
||||
# Senders
|
||||
|
||||
Senders are named timers that periodically send data to bound devices. Create a sender or add a device to a sender with \a addSender(). Each sender runs a timer and calls the virtual \a senderData(); the returned value is sent to bound devices. Alternatively use \a setSenderFixedData() to send fixed data without calling \a senderData().
|
||||
|
||||
# Diagnostics
|
||||
|
||||
\a PIConnection creates a \a PIDiagnostics for each device or filter. Access them with \a diagnostic().
|
||||
|
||||
# Configuration
|
||||
|
||||
You can build a \a PIConnection from a config file section or configure it later with \a configureFromConfig() (see \ref config). Devices are described by full paths (see \a PIIODevice documentation). \a makeConfig() produces a string you can insert into a config file.
|
||||
|
||||
\~russian
|
||||
|
||||
\a PIConnection — абстрактный слой над физическими устройствами ввода-вывода: **пул устройств**, **фильтры** (извлечение пакетов), **отправители** (периодическая отправка) и **диагностика**. Несколько соединений могут использовать одно физическое устройство через пул; у каждого устройства есть поток чтения, запуск и остановка — \a startThreadedRead() и \a stopThreadedRead().
|
||||
|
||||
# Пул устройств
|
||||
|
||||
Пул устройств — единственный на приложение набор уникальных устройств. \a PIConnection обращается к железу через этот пул, поэтому один порт или сокет может обслуживать несколько логических соединений.
|
||||
|
||||
# Фильтры
|
||||
|
||||
Фильтр — это \a PIPacketExtractor и набор привязанных устройств или других фильтров. Когда поток чтения получает данные с устройства, они могут передаваться в один или несколько фильтров. У фильтров уникальные имена; \a filter(name) возвращает \a PIPacketExtractor*, \a filterBoundedDevices() — список привязанных устройств и фильтров. Один фильтр может получать данные из нескольких источников и быть привязан к нескольким.
|
||||
|
||||
# Отправители (senders)
|
||||
|
||||
Отправители — именованные таймеры, периодически отправляющие данные на привязанные устройства. Создание или добавление устройства — \a addSender(). У каждого отправителя свой таймер и вызов виртуального \a senderData(); возвращённое значение отправляется на устройства. Либо \a setSenderFixedData() — отправка фиксированных данных без вызова \a senderData().
|
||||
|
||||
# Диагностика
|
||||
|
||||
Для каждого устройства или фильтра создаётся \a PIDiagnostics. Доступ — \a diagnostic().
|
||||
|
||||
# Конфигурация
|
||||
|
||||
\a PIConnection можно собрать из секции конфига или настроить позже через \a configureFromConfig() (см. \ref config). Устройства задаются полными путями (см. документацию \a PIIODevice). \a makeConfig() формирует строку для вставки в конфиг.
|
||||
42
doc/pages/console.md
Normal file
42
doc/pages/console.md
Normal file
@@ -0,0 +1,42 @@
|
||||
\~english \page console Tiling console (PIScreen)
|
||||
\~russian \page console Тайлинговая консоль (PIScreen)
|
||||
|
||||
\~english
|
||||
|
||||
\a PIScreen is the console screen manager: it runs a drawing thread, hosts **tiles** (layout regions), and routes keyboard and optionally mouse input to the focused tile. Tiles can contain widgets: text rows, scroll bars, lists, buttons, button groups, check boxes, progress bars, \a PICout output, text input, etc.
|
||||
|
||||
# Basic use
|
||||
|
||||
Create a \a PIScreen (optionally with \c startNow = false and a key callback). Call \a enableExitCapture() so that a key (e.g. 'Q') triggers \a waitForFinish(). Add tiles and attach widgets to them; set focus and layout as needed. \a PIScreen inherits \a PIThread and runs the redraw loop; start it before \a waitForFinish() if you did not use \c startNow.
|
||||
|
||||
# Tiles and layout
|
||||
|
||||
Tiles (\a PIScreenTile) are attached to the screen and arranged in a layout. Each tile can hold widgets. Focus determines which tile receives keyboard input. See \a piscreentile.h, \a piscreentiles.h for composed tile widgets and layout types.
|
||||
|
||||
# Widgets
|
||||
|
||||
Widget types are declared in the console headers: list, button, buttons group, check box, progress bar, text input, terminal (PICout output), etc. Add them to a tile; they draw and react to input within the tile. Details and behavior per widget: \a piscreenconsole.h, \a piscreentiles.h, \a piterminal.h, \a piscreendrawer.h.
|
||||
|
||||
# Notes
|
||||
|
||||
Some widget options or behaviors may be refined in the implementation; when in doubt, check the header and example usage.
|
||||
|
||||
\~russian
|
||||
|
||||
\a PIScreen — менеджер консольного экрана: поток отрисовки, **тайлы** (области раскладки), маршрутизация клавиатуры и при необходимости мыши в активный тайл. В тайлах размещают виджеты: строки текста, скроллбары, списки, кнопки, группы кнопок, галочки, прогрессбары, вывод \a PICout, текстовый ввод и др.
|
||||
|
||||
# Базовое использование
|
||||
|
||||
Создать \a PIScreen (при необходимости \c startNow = false и callback клавиш). Вызвать \a enableExitCapture(), чтобы клавиша (например 'Q') вызывала \a waitForFinish(). Добавлять тайлы и виджеты, настраивать фокус и раскладку. \a PIScreen наследует \a PIThread и выполняет цикл перерисовки; запустить до \a waitForFinish(), если не использовали \c startNow.
|
||||
|
||||
# Тайлы и раскладка
|
||||
|
||||
Тайлы (\a PIScreenTile) присоединяются к экрану и располагаются в раскладке. В каждом тайле — виджеты. Фокус определяет получателя ввода с клавиатуры. Составные виджеты и типы раскладки: \a piscreentile.h, \a piscreentiles.h.
|
||||
|
||||
# Виджеты
|
||||
|
||||
Типы виджетов объявлены в заголовках консоли: список, кнопка, группа кнопок, галочка, прогрессбар, текстовый ввод, терминал (вывод PICout) и др. Их добавляют в тайл; отрисовка и реакция на ввод — внутри тайла. Подробности по виджетам: \a piscreenconsole.h, \a piscreentiles.h, \a piterminal.h, \a piscreendrawer.h.
|
||||
|
||||
# Замечания
|
||||
|
||||
Часть опций или поведения виджетов может уточняться в реализации; при сомнениях смотрите заголовки и примеры.
|
||||
52
doc/pages/examples.md
Normal file
52
doc/pages/examples.md
Normal file
@@ -0,0 +1,52 @@
|
||||
\~english \page examples Examples
|
||||
\~russian \page examples Примеры
|
||||
|
||||
\~english
|
||||
|
||||
The \c doc/examples directory contains sample code that can be built and run. Below, each file is listed with a short description and a pointer to related documentation where applicable.
|
||||
|
||||
| File | Description | See also |
|
||||
|------|-------------|----------|
|
||||
| pibytearray.cpp | \a PIByteArray and binary stream usage | \ref iostream |
|
||||
| pichunkstream.cpp | \a PIChunkStream read/write | \ref chunk_stream |
|
||||
| picollection.cpp | Collection helpers | — |
|
||||
| picontainers.cpp | Containers (\a PIVector, \a PIMap, etc.) | \ref summary |
|
||||
| piconfig.cpp | \a PIConfig, \a PIConfig::Entry, dotted paths | \ref config |
|
||||
| picli.cpp | \a PICLI (stub) | \ref application |
|
||||
| picout.cpp | \a PICout, console output | \ref using_basic |
|
||||
| pievaluator.cpp | \a PIEvaluator, expression evaluation | \ref summary (Mathematics) |
|
||||
| piincludes.cpp | Include paths and module discovery | — |
|
||||
| piiodevice.cpp | \a PIIODevice, custom device and \a PIConfig | \ref config, \ref connection |
|
||||
| pikbdlistener.cpp | \a PIKbdListener, keyboard input | \ref console |
|
||||
| pimutex.cpp | \a PIMutex (minimal) | \ref threading |
|
||||
| piobject.cpp | \a PIObject, events and handlers | \ref PIObject_sec0 |
|
||||
| piparsehelper.cpp | Parse utilities | — |
|
||||
| pistatemachine.cpp | \a PIStateMachine, states and transitions | \ref state_machine |
|
||||
| pitimer.cpp | \a PITimer, periodic callbacks | \ref threading |
|
||||
|
||||
Examples are referenced from the main PIP build when documentation is enabled; paths and build integration may vary by project configuration.
|
||||
|
||||
\~russian
|
||||
|
||||
В каталоге \c doc/examples находятся примеры кода, которые можно собирать и запускать. Ниже перечислены файлы с кратким описанием и ссылкой на связанную документацию.
|
||||
|
||||
| Файл | Описание | См. также |
|
||||
|------|----------|-----------|
|
||||
| pibytearray.cpp | \a PIByteArray и бинарный поток | \ref iostream |
|
||||
| pichunkstream.cpp | Чтение/запись \a PIChunkStream | \ref chunk_stream |
|
||||
| picollection.cpp | Вспомогательные типы коллекций | — |
|
||||
| picontainers.cpp | Контейнеры (\a PIVector, \a PIMap и др.) | \ref summary |
|
||||
| piconfig.cpp | \a PIConfig, \a PIConfig::Entry, точечные пути | \ref config |
|
||||
| picli.cpp | \a PICLI (заглушка) | \ref application |
|
||||
| picout.cpp | \a PICout, вывод в консоль | \ref using_basic |
|
||||
| pievaluator.cpp | \a PIEvaluator, вычисление выражений | \ref summary (Математика) |
|
||||
| piincludes.cpp | Пути включения и поиск модулей | — |
|
||||
| piiodevice.cpp | \a PIIODevice, своё устройство и \a PIConfig | \ref config, \ref connection |
|
||||
| pikbdlistener.cpp | \a PIKbdListener, ввод с клавиатуры | \ref console |
|
||||
| pimutex.cpp | \a PIMutex (минимальный пример) | \ref threading |
|
||||
| piobject.cpp | \a PIObject, события и обработчики | \ref PIObject_sec0 |
|
||||
| piparsehelper.cpp | Утилиты разбора | — |
|
||||
| pistatemachine.cpp | \a PIStateMachine, состояния и переходы | \ref state_machine |
|
||||
| pitimer.cpp | \a PITimer, периодические вызовы | \ref threading |
|
||||
|
||||
Примеры подключаются к сборке PIP при включённой документации; пути и способ интеграции зависят от конфигурации проекта.
|
||||
@@ -3,8 +3,10 @@
|
||||
|
||||
\~english
|
||||
|
||||
\a PIBinaryStream is the binary serialization interface. For versioned, extensible formats with chunk ids see \ref chunk_stream. It is not used standalone; only as a mixin or via concrete classes such as \a PIByteArray and \a PIIOBinaryStream. Use it to save or load any data. Trivial types are read/written as memory blocks unless custom operators are defined; non-trivial types must have stream operators or the code will not compile. Containers are supported under the same rules. Enums are treated as int, bool as one byte. Write operators append to the stream; read operators consume from the beginning. Macros: \c BINARY_STREAM_FRIEND(T), \c BINARY_STREAM_WRITE(T), \c BINARY_STREAM_READ(T) (inside them \c s is the stream, \c v is the value).
|
||||
|
||||
\~russian
|
||||
%PIBinaryStream представляет собой интерфейс бинарной сериализации.
|
||||
%PIBinaryStream представляет собой интерфейс бинарной сериализации. Для версионных расширяемых форматов с id чанков см. \ref chunk_stream.
|
||||
Не может быть использован в чистом виде, только в виде миксина или
|
||||
готовых классов: PIByteArray и PIIOBinaryStream.
|
||||
|
||||
@@ -28,7 +30,7 @@
|
||||
* BINARY_STREAM_READ(T) - чтение из потока, "s" - объект потока, "v" - объект типа T.
|
||||
|
||||
Пример:
|
||||
\~\code{.cpp}
|
||||
\code{.cpp}
|
||||
#include <pibytearray.h>
|
||||
|
||||
class MyType {
|
||||
@@ -69,7 +71,7 @@ int main(int argc, char * argv[]) {
|
||||
|
||||
\~english Result:
|
||||
\~russian Результат:
|
||||
\~\code{.cpp}
|
||||
\code{.cpp}
|
||||
0a000000040000007400650078007400
|
||||
10 text
|
||||
|
||||
@@ -84,7 +86,7 @@ operators of this class simply store/restore data block to/from stream:
|
||||
Для сохранения/извлечения блоков произвольных данных используется класс PIMemoryBlock.
|
||||
Потоковые операторы для него просто сохраняют/извлекают блоки байтов в/из потока:
|
||||
|
||||
\~\code{.cpp}
|
||||
\code{.cpp}
|
||||
float a_read[10], a_write[10];
|
||||
for (int i = 0; i < 10; ++i) {
|
||||
a_read [i] = 0.f;
|
||||
@@ -103,7 +105,7 @@ for (int i = 0; i < 10; ++i)
|
||||
|
||||
\~english Result:
|
||||
\~russian Результат:
|
||||
\~\code{.cpp}
|
||||
\code{.cpp}
|
||||
00000000cdcccc3dcdcc4c3e9a99993ecdcccc3e0000003f9a99193f3333333fcdcc4c3f6666663f
|
||||
0
|
||||
0.1
|
||||
@@ -119,7 +121,9 @@ for (int i = 0; i < 10; ++i)
|
||||
|
||||
\~english
|
||||
|
||||
If a read runs out of data (e.g. end of array or file), the stream's \c wasReadError() returns \c true. Check it after reads to handle errors correctly.
|
||||
|
||||
\~russian
|
||||
Если при чтении из потока не хватило данных (например, закончился массив или файл), то проверка
|
||||
объекта потока на wasReadError() вернёт true. Рекомендуется делать эту проверку после чтения
|
||||
объекта потока на \c wasReadError() вернёт \c true. Рекомендуется делать эту проверку после чтения
|
||||
данных для корректной обработки ошибки.
|
||||
|
||||
@@ -8,19 +8,19 @@ PIP - Platform-Independent Primitives - is crossplatform library for C++ develop
|
||||
This library can help developers write non-GUI projects much more quickly, efficiently
|
||||
and customizable than on pure C++.
|
||||
|
||||
Application written on PIP works the same on any system. One can read and write
|
||||
Applications written on PIP work the same on any system. One can read and write
|
||||
any data types, serialize any types to device channels between any systems.
|
||||
|
||||
Many common data types, system primitives and devices implemented in this library.
|
||||
|
||||
PIP also tightly integrates with [CMake](https://cmake.org/) build system, providing handly search
|
||||
main library, additional modules of PIP and several utilites. With
|
||||
CMake with PIP one can easily generate and use code metainformation or
|
||||
serialize custom types with it versions back-compatability.
|
||||
PIP also tightly integrates with [CMake](https://cmake.org/) build system, providing handy search for the
|
||||
main library, additional modules of PIP and several utilities. With
|
||||
CMake and PIP one can easily generate and use code metainformation or
|
||||
serialize custom types with version back-compatibility.
|
||||
|
||||
Summary one can find at \ref summary page.
|
||||
|
||||
Basic using of PIP described at \ref using_basic page.
|
||||
Basic using — \ref using_basic. Further topics — \ref using_advanced. Configuration — \ref config. Code generation — \ref code_model. Streams: \ref iostream, \ref chunk_stream. State machine — \ref state_machine. Complex I/O — \ref connection. TCP client-server — \ref client_server. Tiling console — \ref console. Application tools — \ref application. Threading — \ref threading. Examples — \ref examples.
|
||||
|
||||
|
||||
\~russian
|
||||
@@ -41,4 +41,4 @@ PIP также тесно интегрируется с системой сбо
|
||||
|
||||
Сводку можно найти на странице \ref summary.
|
||||
|
||||
Базовое использование PIP описано на странице \ref using_basic.
|
||||
Базовое использование — \ref using_basic. Дополнительные темы — \ref using_advanced. Конфигурация — \ref config. Кодогенерация — \ref code_model. Потоки: \ref iostream, \ref chunk_stream. Машина состояний — \ref state_machine. Сложный ввод-вывод — \ref connection. TCP клиент-сервер — \ref client_server. Тайлинговая консоль — \ref console. Инструменты приложения — \ref application. Многопоточность — \ref threading. Примеры — \ref examples.
|
||||
|
||||
714
doc/pages/state_machine.md
Normal file
714
doc/pages/state_machine.md
Normal file
@@ -0,0 +1,714 @@
|
||||
\~english \page state_machine State machine
|
||||
\~russian \page state_machine Машина состояний
|
||||
|
||||
\~english
|
||||
|
||||
# State Machine
|
||||
|
||||
## State Machine Description
|
||||
|
||||
State machine is a behavioral design pattern that allows an object to change its behavior when its internal state changes.
|
||||
Implementation in PIP is based on the **SCXML** (State Chart XML) standard.
|
||||
|
||||
### SCXML Concepts
|
||||
|
||||
- **State** — a node in the state tree, can be atomic or compound
|
||||
- **Transition** — a connection between states that triggers on an event
|
||||
- **Event** — a trigger that causes a transition
|
||||
- **Guard** — a condition that must be true for a transition to execute
|
||||
- **Action** — an operation executed during a transition
|
||||
- **Parallel** — a state where all substates are activated simultaneously
|
||||
|
||||
### PIP State Machine Features
|
||||
|
||||
- **Cannot create state, event, transition on stack** — all objects are created via `new` and managed via pointers
|
||||
- **State machine is the root state** — `PIStateMachine` inherits from `PIStateBase`
|
||||
- **All transitions and states are automatically deleted** — when the parent object is destroyed
|
||||
|
||||
### State Types
|
||||
|
||||
- **Atomic state** — a state without nested substates
|
||||
- **Compound state** — a state containing nested substates
|
||||
- **Final state** — a terminating state indicating the end of machine execution
|
||||
- **Parallel state** — a state where all substates are activated simultaneously
|
||||
|
||||
### Transition Types
|
||||
|
||||
- **Normal transition** — triggers on receiving a specific event
|
||||
- **Timeout transition** — triggers automatically after a specified time interval
|
||||
- **Guarded transition** — triggers only when a specific condition is met
|
||||
|
||||
## State Machine API
|
||||
|
||||
### Main Classes
|
||||
|
||||
#### PIStateMachine
|
||||
|
||||
Main state machine class.
|
||||
|
||||
**Key methods:**
|
||||
|
||||
- `bool start()` — starts state machine execution
|
||||
- `bool isRunning()` — checks if state machine is running
|
||||
- `void setOnFinish(std::function<void()> f)` — sets finish callback
|
||||
- `bool postEvent(int event_id, Args... args)` — posts event to state machine
|
||||
|
||||
#### PIStateBase
|
||||
|
||||
Base class for all states.
|
||||
|
||||
**Key methods:**
|
||||
|
||||
- `virtual void onEnter()` — called when state is entered
|
||||
- `virtual void onExit()` — called when state is exited
|
||||
- `void addState(PIStateBase *s)` — adds child state
|
||||
- `PITransitionBase *addTransition(PIStateBase *target, int event_id)` — adds transition
|
||||
- `PITransitionTimeout *addTimeoutTransition(PIStateBase *target, PISystemTime timeout)` — adds timeout transition
|
||||
- `void setParallel(bool yes)` — sets parallel mode
|
||||
|
||||
#### PIStateLambda
|
||||
|
||||
State with lambda callbacks.
|
||||
|
||||
\code{.cpp}
|
||||
PIStateLambda(std::function<void()> on_enter, std::function<void()> on_exit = nullptr, const PIString &n = {})
|
||||
\endcode
|
||||
|
||||
#### PIStateFinal
|
||||
|
||||
Final state of state machine.
|
||||
|
||||
\code{.cpp}
|
||||
PIStateFinal(std::function<void()> on_finish = nullptr, const PIString &n = {})
|
||||
\endcode
|
||||
|
||||
#### PITransitionBase
|
||||
|
||||
Base class for transitions.
|
||||
|
||||
**Key methods:**
|
||||
|
||||
- `PITransitionBase *addGuard(std::function<R(Args...)> f)` — adds guard function
|
||||
- `PITransitionBase *addAction(std::function<void()> a)` — adds action
|
||||
- `void trigger()` — triggers transition
|
||||
|
||||
#### PITransitionTimeout
|
||||
|
||||
Transition that triggers after a specified timeout.
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Simple State Machine
|
||||
|
||||
\code{.cpp}
|
||||
#include "pistatemachine.h"
|
||||
#include "pisystemtime.h"
|
||||
|
||||
// Create state machine
|
||||
PIStateMachine *machine = new PIStateMachine("Main");
|
||||
|
||||
// Create states
|
||||
PIStateLambda *idle = new PIStateLambda(
|
||||
[]() { piCout << "Entering Idle state\n"; },
|
||||
[]() { piCout << "Exiting Idle state\n"; },
|
||||
"Idle"
|
||||
);
|
||||
PIStateLambda *running = new PIStateLambda(
|
||||
[]() { piCout << "Entering Running state\n"; },
|
||||
[]() { piCout << "Exiting Running state\n"; },
|
||||
"Running"
|
||||
);
|
||||
PIStateFinal *finish = new PIStateFinal(
|
||||
[]() { piCout << "Machine finished\n"; },
|
||||
"Finish"
|
||||
);
|
||||
|
||||
// Add states
|
||||
machine->addState(idle);
|
||||
machine->addState(running);
|
||||
machine->addState(finish);
|
||||
|
||||
// Set initial state
|
||||
idle->setInitialState(idle);
|
||||
running->setInitialState(running);
|
||||
machine->setInitialState(idle);
|
||||
|
||||
// Add transitions
|
||||
idle->addTransition(running, 1);
|
||||
running->addTransition(finish, 2);
|
||||
|
||||
// Set finish callback
|
||||
machine->setOnFinish([]() { piCout << "Machine execution completed\n"; });
|
||||
|
||||
// Start machine
|
||||
machine->start();
|
||||
|
||||
// Post events
|
||||
machine->postEvent(1); // Transition to Running
|
||||
machine->postEvent(2); // Transition to Finish
|
||||
\endcode
|
||||
|
||||
### Guarded Transitions
|
||||
|
||||
\code{.cpp}
|
||||
PIStateMachine *machine = new PIStateMachine("With Guards");
|
||||
|
||||
PIStateLambda *stateA = new PIStateLambda([]() { piCout << "State A\n"; }, nullptr, "A");
|
||||
PIStateLambda *stateB = new PIStateLambda([]() { piCout << "State B\n"; }, nullptr, "B");
|
||||
PIStateLambda *stateC = new PIStateLambda([]() { piCout << "State C\n"; }, nullptr, "C");
|
||||
|
||||
machine->addState(stateA);
|
||||
machine->addState(stateB);
|
||||
machine->addState(stateC);
|
||||
|
||||
stateA->setInitialState(stateA);
|
||||
machine->setInitialState(stateA);
|
||||
|
||||
// Transition with guard function
|
||||
auto *t1 = stateA->addTransition(stateB, 1);
|
||||
t1->addGuard([](int value) -> bool {
|
||||
return value > 10;
|
||||
});
|
||||
|
||||
// Transition with another guard function
|
||||
auto *t2 = stateB->addTransition(stateC, 2);
|
||||
t2->addGuard([](const PIString &msg) -> bool {
|
||||
return msg == "allowed";
|
||||
});
|
||||
|
||||
machine->start();
|
||||
|
||||
// First call will not execute (value <= 10)
|
||||
machine->postEvent(1, 5);
|
||||
|
||||
// Second call will execute (value > 10)
|
||||
machine->postEvent(1, 15);
|
||||
|
||||
// First call will not execute (msg != "allowed")
|
||||
machine->postEvent(2, "test");
|
||||
|
||||
// Second call will execute (msg == "allowed")
|
||||
machine->postEvent(2, "allowed");
|
||||
\endcode
|
||||
|
||||
### Timeout Transitions
|
||||
|
||||
\code{.cpp}
|
||||
PIStateMachine *machine = new PIStateMachine("With Timeout");
|
||||
|
||||
PIStateLambda *working = new PIStateLambda(
|
||||
[]() { piCout << "Working...\n"; },
|
||||
[]() { piCout << "Stop working\n"; },
|
||||
"Working"
|
||||
);
|
||||
PIStateLambda *timeoutState = new PIStateLambda([]() { piCout << "Timeout occurred\n"; }, nullptr, "Timeout");
|
||||
PIStateFinal *finish = new PIStateFinal([]() { piCout << "Done\n"; }, "Finish");
|
||||
|
||||
machine->addState(working);
|
||||
machine->addState(timeoutState);
|
||||
machine->addState(finish);
|
||||
|
||||
working->setInitialState(working);
|
||||
machine->setInitialState(working);
|
||||
|
||||
// Add timeout transition (after 5 seconds)
|
||||
working->addTimeoutTransition(timeoutState, PISystemTime::fromSeconds(5));
|
||||
|
||||
// Add transition from timeoutState to finish
|
||||
timeoutState->addTransition(finish, 1);
|
||||
|
||||
machine->start();
|
||||
\endcode
|
||||
|
||||
### Compound States
|
||||
|
||||
\code{.cpp}
|
||||
PIStateMachine *machine = new PIStateMachine("Compound States");
|
||||
|
||||
// Root state (machine)
|
||||
PIStateLambda *root = new PIStateLambda([]() { piCout << "Root state\n"; }, nullptr, "Root");
|
||||
|
||||
// Compound state with substates
|
||||
PIStateLambda *parent = new PIStateLambda([]() { piCout << "Parent state\n"; }, nullptr, "Parent");
|
||||
PIStateLambda *child1 = new PIStateLambda([]() { piCout << "Child 1\n"; }, nullptr, "Child1");
|
||||
PIStateLambda *child2 = new PIStateLambda([]() { piCout << "Child 2\n"; }, nullptr, "Child2");
|
||||
|
||||
parent->setInitialState(child1);
|
||||
parent->addState(child1);
|
||||
parent->addState(child2);
|
||||
root->addState(parent);
|
||||
|
||||
machine->addState(root);
|
||||
machine->setInitialState(root);
|
||||
|
||||
// Add transitions
|
||||
root->addTransition(parent, 1);
|
||||
parent->addTransition(root, 2);
|
||||
|
||||
machine->start();
|
||||
|
||||
// Transition to parent
|
||||
machine->postEvent(1);
|
||||
|
||||
// Transition back
|
||||
machine->postEvent(2);
|
||||
\endcode
|
||||
|
||||
### Parallel States
|
||||
|
||||
\code{.cpp}
|
||||
PIStateMachine *machine = new PIStateMachine("Parallel States");
|
||||
|
||||
PIStateLambda *root = new PIStateLambda([]() { piCout << "Root\n"; }, nullptr, "Root");
|
||||
PIStateLambda *parallel = new PIStateLambda([]() { piCout << "Parallel\n"; }, nullptr, "Parallel");
|
||||
PIStateLambda *sub1 = new PIStateLambda([]() { piCout << "Substate 1\n"; }, nullptr, "Sub1");
|
||||
PIStateLambda *sub2 = new PIStateLambda([]() { piCout << "Substate 2\n"; }, nullptr, "Sub2");
|
||||
|
||||
// Enable parallel mode
|
||||
parallel->setParallel(true);
|
||||
parallel->addState(sub1);
|
||||
parallel->addState(sub2);
|
||||
parallel->setInitialState(sub1);
|
||||
root->addState(parallel);
|
||||
|
||||
machine->addState(root);
|
||||
machine->setInitialState(root);
|
||||
|
||||
machine->start();
|
||||
|
||||
// When entering parallel, both substates are activated simultaneously
|
||||
\endcode
|
||||
|
||||
### Transitions with Actions
|
||||
|
||||
\code{.cpp}
|
||||
PIStateMachine *machine = new PIStateMachine("With Actions");
|
||||
|
||||
PIStateLambda *stateA = new PIStateLambda([]() { piCout << "State A\n"; }, nullptr, "A");
|
||||
PIStateLambda *stateB = new PIStateLambda([]() { piCout << "State B\n"; }, nullptr, "B");
|
||||
|
||||
machine->addState(stateA);
|
||||
machine->addState(stateB);
|
||||
|
||||
machine->setInitialState(stateA);
|
||||
|
||||
// Add transition with action
|
||||
auto *t = stateA->addTransition(stateB, 1);
|
||||
t->addAction([]() { piCout << "Action during transition\n"; });
|
||||
|
||||
machine->start();
|
||||
machine->postEvent(1);
|
||||
\endcode
|
||||
|
||||
## Thread Safety
|
||||
|
||||
State machine is thread-safe. The `postEvent` method uses a queue to handle nested calls, allowing safe event posting from
|
||||
different threads.
|
||||
|
||||
## Usage Rules
|
||||
|
||||
### Cannot Create on Stack
|
||||
|
||||
\code{.cpp}
|
||||
// ❌ WRONG
|
||||
PIStateLambda state([]() {}, nullptr, "State");
|
||||
|
||||
// ✅ CORRECT
|
||||
PIStateLambda *state = new PIStateLambda([]() {}, nullptr, "State");
|
||||
\endcode
|
||||
|
||||
### Proper Object Hierarchy
|
||||
|
||||
\code{.cpp}
|
||||
PIStateMachine *machine = new PIStateMachine("Main");
|
||||
|
||||
// States are created via new and added to machine or another state
|
||||
PIStateLambda *state1 = new PIStateLambda([]() {}, nullptr, "State1");
|
||||
PIStateLambda *state2 = new PIStateLambda([]() {}, nullptr, "State2");
|
||||
|
||||
machine->addState(state1);
|
||||
machine->addState(state2);
|
||||
|
||||
// Transitions are added to states via addTransition
|
||||
state1->addTransition(state2, 1);
|
||||
|
||||
// Machine is started
|
||||
machine->start();
|
||||
\endcode
|
||||
|
||||
### Memory Cleanup
|
||||
|
||||
All objects (states, transitions) are automatically deleted when the parent object is destroyed:
|
||||
|
||||
- When `PIStateMachine` is destroyed, all states and transitions are deleted
|
||||
- When `PIStateBase` is destroyed, all child states and transitions are deleted
|
||||
|
||||
## Debugging
|
||||
|
||||
For debugging, you can use the `print()` method to output the state tree:
|
||||
|
||||
\code{.cpp}
|
||||
machine->print();
|
||||
\endcode
|
||||
|
||||
Also, you can use `activeAtomics()` to get a list of active states.
|
||||
|
||||
## Related Modules
|
||||
|
||||
- \ref DateTime module for `PISystemTime` used in timeout transitions
|
||||
|
||||
\~russian
|
||||
|
||||
# Машина состояний
|
||||
|
||||
## Описание машины состояний
|
||||
|
||||
Машина состояний — это поведенческий паттерн проектирования, который позволяет объекту изменять свое поведение при изменении
|
||||
внутреннего состояния. Реализация в PIP основана на стандарте **SCXML** (State Chart XML).
|
||||
|
||||
### Основные концепции SCXML
|
||||
|
||||
- **State (Состояние)** — узел в дереве состояний, может быть атомарным или составным
|
||||
- **Transition (Переход)** — связь между состояниями, срабатывает при событии
|
||||
- **Event (Событие)** — триггер, вызывающий переход
|
||||
- **Guard (Сторожевая функция)** — условие, которое должно быть истинным для выполнения перехода
|
||||
- **Action (Действие)** — операция, выполняемая при переходе
|
||||
- **Parallel (Параллельное состояние)** — состояние, в котором все подсостояния активируются одновременно
|
||||
|
||||
### Особенности реализации PIP
|
||||
|
||||
- **Нельзя создавать state, event, transition в стеке** — все объекты создаются через `new` и управляются через указатели
|
||||
- **Машина состояний — это корневой state** — `PIStateMachine` наследуется от `PIStateBase`
|
||||
- **Все переходы и состояния удаляются автоматически** — при уничтожении родительского объекта
|
||||
|
||||
### Основные типы состояний
|
||||
|
||||
- **Атомарное состояние** — состояние без вложенных подсостояний
|
||||
- **Составное состояние** — состояние, содержащее вложенные подсостояния
|
||||
- **Финальное состояние** — завершающее состояние, указывающее на окончание работы машины
|
||||
- **Параллельное состояние** — состояние, в котором все подсостояния активируются одновременно
|
||||
|
||||
### Виды переходов
|
||||
|
||||
- **Обычный переход** — срабатывает при получении определенного события
|
||||
- **Переход по таймауту** — срабатывает автоматически через заданный промежуток времени
|
||||
- **Переход с guard** — срабатывает только при выполнении определенного условия
|
||||
|
||||
## PIP State Machine API
|
||||
|
||||
### Основные классы
|
||||
|
||||
#### PIStateMachine
|
||||
|
||||
Основной класс машины состояний.
|
||||
|
||||
**Ключевые методы:**
|
||||
|
||||
- `bool start()` — запускает выполнение машины состояний
|
||||
- `bool isRunning()` — проверяет, запущена ли машина
|
||||
- `void setOnFinish(std::function<void()> f)` — устанавливает коллбэк завершения
|
||||
- `bool postEvent(int event_id, Args... args)` — отправляет событие в машину состояний
|
||||
|
||||
#### PIStateBase
|
||||
|
||||
Базовый класс для всех состояний.
|
||||
|
||||
**Ключевые методы:**
|
||||
|
||||
- `virtual void onEnter()` — вызывается при входе в состояние
|
||||
- `virtual void onExit()` — вызывается при выходе из состояния
|
||||
- `void addState(PIStateBase *s)` — добавляет дочернее состояние
|
||||
- `PITransitionBase *addTransition(PIStateBase *target, int event_id)` — добавляет переход
|
||||
- `PITransitionTimeout *addTimeoutTransition(PIStateBase *target, PISystemTime timeout)` — добавляет переход по таймауту
|
||||
- `void setParallel(bool yes)` — устанавливает параллельный режим
|
||||
|
||||
#### PIStateLambda
|
||||
|
||||
Состояние с lambda-коллбэками.
|
||||
|
||||
\code{.cpp}
|
||||
PIStateLambda(std::function<void()> on_enter, std::function<void()> on_exit = nullptr, const PIString &n = {})
|
||||
\endcode
|
||||
|
||||
#### PIStateFinal
|
||||
|
||||
Финальное состояние машины состояний.
|
||||
|
||||
\code{.cpp}
|
||||
PIStateFinal(std::function<void()> on_finish = nullptr, const PIString &n = {})
|
||||
\endcode
|
||||
|
||||
#### PITransitionBase
|
||||
|
||||
Базовый класс для переходов.
|
||||
|
||||
**Ключевые методы:**
|
||||
|
||||
- `PITransitionBase *addGuard(std::function<R(Args...)> f)` — добавляет сторожевую функцию
|
||||
- `PITransitionBase *addAction(std::function<void()> a)` — добавляет действие
|
||||
- `void trigger()` — запускает переход
|
||||
|
||||
#### PITransitionTimeout
|
||||
|
||||
Переход, срабатывающий через заданный промежуток времени.
|
||||
|
||||
## Примеры использования
|
||||
|
||||
### Простая машина состояний
|
||||
|
||||
\code{.cpp}
|
||||
#include "pistatemachine.h"
|
||||
#include "pisystemtime.h"
|
||||
|
||||
// Создаем машину состояний
|
||||
PIStateMachine *machine = new PIStateMachine("Main");
|
||||
|
||||
// Создаем состояния
|
||||
PIStateLambda *idle = new PIStateLambda(
|
||||
[]() { piCout << "Entering Idle state\n"; },
|
||||
[]() { piCout << "Exiting Idle state\n"; },
|
||||
"Idle"
|
||||
);
|
||||
PIStateLambda *running = new PIStateLambda(
|
||||
[]() { piCout << "Entering Running state\n"; },
|
||||
[]() { piCout << "Exiting Running state\n"; },
|
||||
"Running"
|
||||
);
|
||||
PIStateFinal *finish = new PIStateFinal(
|
||||
[]() { piCout << "Machine finished\n"; },
|
||||
"Finish"
|
||||
);
|
||||
|
||||
// Добавляем состояния
|
||||
machine->addState(idle);
|
||||
machine->addState(running);
|
||||
machine->addState(finish);
|
||||
|
||||
// Устанавливаем начальное состояние
|
||||
idle->setInitialState(idle);
|
||||
running->setInitialState(running);
|
||||
machine->setInitialState(idle);
|
||||
|
||||
// Добавляем переходы
|
||||
idle->addTransition(running, 1);
|
||||
running->addTransition(finish, 2);
|
||||
|
||||
// Устанавливаем коллбэк завершения
|
||||
machine->setOnFinish([]() { piCout << "Machine execution completed\n"; });
|
||||
|
||||
// Запускаем машину
|
||||
machine->start();
|
||||
|
||||
// Отправляем события
|
||||
machine->postEvent(1); // Перейти в Running
|
||||
machine->postEvent(2); // Перейти в Finish
|
||||
\endcode
|
||||
|
||||
### Машина состояний с guard-функциями
|
||||
|
||||
\code{.cpp}
|
||||
PIStateMachine *machine = new PIStateMachine("With Guards");
|
||||
|
||||
PIStateLambda *stateA = new PIStateLambda([]() { piCout << "State A\n"; }, nullptr, "A");
|
||||
PIStateLambda *stateB = new PIStateLambda([]() { piCout << "State B\n"; }, nullptr, "B");
|
||||
PIStateLambda *stateC = new PIStateLambda([]() { piCout << "State C\n"; }, nullptr, "C");
|
||||
|
||||
machine->addState(stateA);
|
||||
machine->addState(stateB);
|
||||
machine->addState(stateC);
|
||||
|
||||
stateA->setInitialState(stateA);
|
||||
machine->setInitialState(stateA);
|
||||
|
||||
// Переход с guard-функцией
|
||||
auto *t1 = stateA->addTransition(stateB, 1);
|
||||
t1->addGuard([](int value) -> bool {
|
||||
return value > 10;
|
||||
});
|
||||
|
||||
// Переход с другой guard-функцией
|
||||
auto *t2 = stateB->addTransition(stateC, 2);
|
||||
t2->addGuard([](const PIString &msg) -> bool {
|
||||
return msg == "allowed";
|
||||
});
|
||||
|
||||
machine->start();
|
||||
|
||||
// Первый вызов не выполнится (value <= 10)
|
||||
machine->postEvent(1, 5);
|
||||
|
||||
// Второй вызов выполнится (value > 10)
|
||||
machine->postEvent(1, 15);
|
||||
|
||||
// Первый вызов не выполнится (msg != "allowed")
|
||||
machine->postEvent(2, "test");
|
||||
|
||||
// Второй вызов выполнится (msg == "allowed")
|
||||
machine->postEvent(2, "allowed");
|
||||
\endcode
|
||||
|
||||
### Машина состояний с таймаутами
|
||||
|
||||
\code{.cpp}
|
||||
PIStateMachine *machine = new PIStateMachine("With Timeout");
|
||||
|
||||
PIStateLambda *working = new PIStateLambda(
|
||||
[]() { piCout << "Working...\n"; },
|
||||
[]() { piCout << "Stop working\n"; },
|
||||
"Working"
|
||||
);
|
||||
PIStateLambda *timeoutState = new PIStateLambda([]() { piCout << "Timeout occurred\n"; }, nullptr, "Timeout");
|
||||
PIStateFinal *finish = new PIStateFinal([]() { piCout << "Done\n"; }, "Finish");
|
||||
|
||||
machine->addState(working);
|
||||
machine->addState(timeoutState);
|
||||
machine->addState(finish);
|
||||
|
||||
working->setInitialState(working);
|
||||
machine->setInitialState(working);
|
||||
|
||||
// Добавляем переход по таймауту (через 5 секунд)
|
||||
working->addTimeoutTransition(timeoutState, PISystemTime::fromSeconds(5));
|
||||
|
||||
// Добавляем переход из timeoutState в finish
|
||||
timeoutState->addTransition(finish, 1);
|
||||
|
||||
machine->start();
|
||||
\endcode
|
||||
|
||||
### Составные состояния
|
||||
|
||||
\code{.cpp}
|
||||
PIStateMachine *machine = new PIStateMachine("Compound States");
|
||||
|
||||
// Корневое состояние (машина)
|
||||
PIStateLambda *root = new PIStateLambda([]() { piCout << "Root state\n"; }, nullptr, "Root");
|
||||
|
||||
// Составное состояние с подсостояниями
|
||||
PIStateLambda *parent = new PIStateLambda([]() { piCout << "Parent state\n"; }, nullptr, "Parent");
|
||||
PIStateLambda *child1 = new PIStateLambda([]() { piCout << "Child 1\n"; }, nullptr, "Child1");
|
||||
PIStateLambda *child2 = new PIStateLambda([]() { piCout << "Child 2\n"; }, nullptr, "Child2");
|
||||
|
||||
parent->setInitialState(child1);
|
||||
parent->addState(child1);
|
||||
parent->addState(child2);
|
||||
root->addState(parent);
|
||||
|
||||
machine->addState(root);
|
||||
machine->setInitialState(root);
|
||||
|
||||
// Добавляем переходы
|
||||
root->addTransition(parent, 1);
|
||||
parent->addTransition(root, 2);
|
||||
|
||||
machine->start();
|
||||
|
||||
// Переход в parent
|
||||
machine->postEvent(1);
|
||||
|
||||
// Переход обратно
|
||||
machine->postEvent(2);
|
||||
\endcode
|
||||
|
||||
### Параллельные состояния
|
||||
|
||||
\code{.cpp}
|
||||
PIStateMachine *machine = new PIStateMachine("Parallel States");
|
||||
|
||||
PIStateLambda *root = new PIStateLambda([]() { piCout << "Root\n"; }, nullptr, "Root");
|
||||
PIStateLambda *parallel = new PIStateLambda([]() { piCout << "Parallel\n"; }, nullptr, "Parallel");
|
||||
PIStateLambda *sub1 = new PIStateLambda([]() { piCout << "Substate 1\n"; }, nullptr, "Sub1");
|
||||
PIStateLambda *sub2 = new PIStateLambda([]() { piCout << "Substate 2\n"; }, nullptr, "Sub2");
|
||||
|
||||
// Включаем параллельный режим
|
||||
parallel->setParallel(true);
|
||||
parallel->addState(sub1);
|
||||
parallel->addState(sub2);
|
||||
parallel->setInitialState(sub1);
|
||||
root->addState(parallel);
|
||||
|
||||
machine->addState(root);
|
||||
machine->setInitialState(root);
|
||||
|
||||
machine->start();
|
||||
|
||||
// При входе в parallel оба подсостояния активируются одновременно
|
||||
\endcode
|
||||
|
||||
### Машина состояний с действиями
|
||||
|
||||
\code{.cpp}
|
||||
PIStateMachine *machine = new PIStateMachine("With Actions");
|
||||
|
||||
PIStateLambda *stateA = new PIStateLambda([]() { piCout << "State A\n"; }, nullptr, "A");
|
||||
PIStateLambda *stateB = new PIStateLambda([]() { piCout << "State B\n"; }, nullptr, "B");
|
||||
|
||||
machine->addState(stateA);
|
||||
machine->addState(stateB);
|
||||
|
||||
machine->setInitialState(stateA);
|
||||
|
||||
// Добавляем переход с действием
|
||||
auto *t = stateA->addTransition(stateB, 1);
|
||||
t->addAction([]() { piCout << "Action during transition\n"; });
|
||||
|
||||
machine->start();
|
||||
machine->postEvent(1);
|
||||
\endcode
|
||||
|
||||
## Потокобезопасность
|
||||
|
||||
Машина состояний PIP потокобезопасна. Метод `postEvent` использует очередь для обработки вложенных вызовов, что позволяет
|
||||
безопасно отправлять события из разных потоков.
|
||||
|
||||
## Правила использования
|
||||
|
||||
### Нельзя создавать в стеке
|
||||
|
||||
\code{.cpp}
|
||||
// ❌ НЕЛЬЗЯ
|
||||
PIStateLambda state([]() {}, nullptr, "State");
|
||||
|
||||
// ✅ ПРАВИЛЬНО
|
||||
PIStateLambda *state = new PIStateLambda([]() {}, nullptr, "State");
|
||||
\endcode
|
||||
|
||||
### Правильная иерархия объектов
|
||||
|
||||
\code{.cpp}
|
||||
PIStateMachine *machine = new PIStateMachine("Main");
|
||||
|
||||
// Состояния создаются через new и добавляются в машину или другое состояние
|
||||
PIStateLambda *state1 = new PIStateLambda([]() {}, nullptr, "State1");
|
||||
PIStateLambda *state2 = new PIStateLambda([]() {}, nullptr, "State2");
|
||||
|
||||
machine->addState(state1);
|
||||
machine->addState(state2);
|
||||
|
||||
// Переходы добавляются к состояниям через addTransition
|
||||
state1->addTransition(state2, 1);
|
||||
|
||||
// Машина запускается
|
||||
machine->start();
|
||||
\endcode
|
||||
|
||||
### Очистка памяти
|
||||
|
||||
Все объекты (состояния, переходы) автоматически удаляются при уничтожении родительского объекта:
|
||||
|
||||
- При уничтожении `PIStateMachine` удаляются все состояния и переходы
|
||||
- При уничтожении `PIStateBase` удаляются все дочерние состояния и переходы
|
||||
|
||||
## Отладка
|
||||
|
||||
Для отладки можно использовать метод `print()` для вывода дерева состояний:
|
||||
|
||||
\code{.cpp}
|
||||
machine->print();
|
||||
\endcode
|
||||
|
||||
Также можно использовать `activeAtomics()` для получения списка активных состояний.
|
||||
|
||||
## Связанные модули
|
||||
|
||||
- \ref DateTime модуль для `PISystemTime`, используемого в переходах по таймауту
|
||||
@@ -35,7 +35,7 @@
|
||||
* binary log (\a PIBinaryLog)
|
||||
* complex I/O point (\a PIConnection)
|
||||
* peering net node (\a PIPeer)
|
||||
* connection quality diagnotic (\a PIDiagnostics)
|
||||
* connection quality diagnostic (\a PIDiagnostics)
|
||||
* Run-time libraries
|
||||
* external process (\a PIProcess)
|
||||
* external library (\a PILibrary)
|
||||
@@ -56,11 +56,13 @@
|
||||
* single-instance application control (\a PISingleApplication)
|
||||
* high-level log (\a PILog)
|
||||
* translation support (\a PITranslator)
|
||||
* State machine ([By stantard](https://www.w3.org/TR/scxml/)) (\a PIStateMachine)
|
||||
* State machine ([By standard](https://www.w3.org/TR/scxml/)) (\a PIStateMachine)
|
||||
* High-level TCP client-server
|
||||
* server (\a PIClientServer::Server, \a PIClientServer::ServerClient)
|
||||
* client (\a PIClientServer::Client)
|
||||
* Crypt support (\a PICrypt, \a PIAuth)
|
||||
* Cloud (\a PICloudClient, \a PICloudServer) — named endpoints over ethernet
|
||||
* HTTP client and server (\a PIHTTPClient, \a PIHTTPServer, \a MicrohttpdServer)
|
||||
|
||||
\~russian
|
||||
|
||||
@@ -122,3 +124,5 @@
|
||||
* сервер (\a PIClientServer::Server, \a PIClientServer::ServerClient)
|
||||
* клиент (\a PIClientServer::Client)
|
||||
* Поддержка шифрования (\a PICrypt, \a PIAuth)
|
||||
* Облако (\a PICloudClient, \a PICloudServer) — именованные конечные точки поверх Ethernet
|
||||
* HTTP-клиент и сервер (\a PIHTTPClient, \a PIHTTPServer, \a MicrohttpdServer)
|
||||
|
||||
28
doc/pages/threading.md
Normal file
28
doc/pages/threading.md
Normal file
@@ -0,0 +1,28 @@
|
||||
\~english \page threading Multithreading
|
||||
\~russian \page threading Многопоточность
|
||||
|
||||
\~english
|
||||
|
||||
The Thread module provides threads, timers, synchronization primitives and task execution:
|
||||
|
||||
* **PIThread** — run a loop or one-off work in a separate thread. Override \a run() or use the default loop; start/stop with \a start() and \a stop(). Can act as the event performer for \a PIObject (see \ref using_advanced "Threading and events").
|
||||
* **PITimer** — periodic callbacks at a given frequency (e.g. Hz). Connect to a handler; start/stop the timer. Used in \ref using_basic and in state machine examples.
|
||||
* **Synchronization** — \a PIMutex, \a PISpinlock, \a PIConditionVariable, \a PISemaphore, \a PIReadWriteLock for protecting shared data and coordinating threads.
|
||||
* **PIThreadPoolExecutor** — submit tasks to a fixed pool of worker threads; wait for completion or shutdown.
|
||||
* **PIThreadPoolLoop** — run a function over a range in parallel (parallel-for style).
|
||||
* **PIBlockingDequeue** — blocking producer-consumer queue for passing work between threads.
|
||||
|
||||
Use \a PIMutexLocker (and similar guards) for exception-safe locking. Events from other threads can be queued and processed in the object's thread via \a callQueuedEvents() (see \ref PIObject_sec0). Full API: \a pithread.h, \a pitimer.h, \a pimutex.h, \a pithreadpoolexecutor.h, \a piblockingqueue.h, \a pithreadmodule.h.
|
||||
|
||||
\~russian
|
||||
|
||||
Модуль Thread предоставляет потоки, таймеры, примитивы синхронизации и выполнение задач:
|
||||
|
||||
* **PIThread** — выполнение цикла или разовой работы в отдельном потоке. Переопределение \a run() или использование цикла по умолчанию; запуск и остановка — \a start() и \a stop(). Может быть исполнителем событий для \a PIObject (см. \ref using_advanced "Потоки и события").
|
||||
* **PITimer** — периодические вызовы с заданной частотой (например в Гц). Подключение обработчика; запуск и остановка таймера. Используется в \ref using_basic и в примерах машины состояний.
|
||||
* **Синхронизация** — \a PIMutex, \a PISpinlock, \a PIConditionVariable, \a PISemaphore, \a PIReadWriteLock для защиты общих данных и согласования потоков.
|
||||
* **PIThreadPoolExecutor** — отправка задач в пул рабочих потоков; ожидание завершения или остановка пула.
|
||||
* **PIThreadPoolLoop** — параллельный запуск функции по диапазону (стиль parallel-for).
|
||||
* **PIBlockingDequeue** — блокирующая очередь производитель–потребитель для передачи работы между потоками.
|
||||
|
||||
Для исключений-безопасной блокировки используйте \a PIMutexLocker и аналогичные охранные классы. События из других потоков можно ставить в очередь и обрабатывать в потоке объекта через \a callQueuedEvents() (см. \ref PIObject_sec0). Полный API: \a pithread.h, \a pitimer.h, \a pimutex.h, \a pithreadpoolexecutor.h, \a piblockingqueue.h, \a pithreadmodule.h.
|
||||
64
doc/pages/using_advanced.md
Normal file
64
doc/pages/using_advanced.md
Normal file
@@ -0,0 +1,64 @@
|
||||
\~english \page using_advanced Further topics
|
||||
\~russian \page using_advanced Дополнительные темы
|
||||
|
||||
\~english
|
||||
|
||||
After \ref using_basic you may want to explore:
|
||||
|
||||
* \ref summary — full list of PIP modules and classes (containers, I/O, threading, math, state machine, etc.).
|
||||
* \ref config — reading and writing configuration with \a PIConfig (files, dotted paths, INI-style sections).
|
||||
* \ref code_model — code generation: metadata, serialization operators, PIMETA, \c pip_cmg and CMake integration.
|
||||
* \ref iostream — binary streams (\a PIBinaryStream, \a PIByteArray), operators and \a PIMemoryBlock.
|
||||
* \ref chunk_stream — versioned serialization with \a PIChunkStream (chunks by id, backward compatibility).
|
||||
* \ref state_machine — state machine concepts, states, transitions, conditions, \a PIStateMachine.
|
||||
* \ref connection — complex I/O: \a PIConnection, device pool, filters, senders, diagnostics.
|
||||
* \ref client_server — TCP server and client (\a PIClientServer::Server, \a PIClientServer::Client).
|
||||
* \ref console — tiling console \a PIScreen, tiles, widgets (list, button, progress, input, etc.).
|
||||
* \ref application — application-level: \a PICLI, \a PILog, \a PISystemMonitor, \a PISingleApplication, \a PITranslator.
|
||||
* \ref threading — multithreading: \a PIThread, \a PITimer, synchronization, executor, blocking queue.
|
||||
* \ref examples — index of sample code in doc/examples.
|
||||
|
||||
Events and handlers are documented on the \a PIObject reference page (\ref PIObject_sec0).
|
||||
|
||||
\par Threading and events
|
||||
|
||||
Many PIP classes inherit \a PIObject and use events: handlers can be invoked directly or queued. When events are queued (e.g. from another thread), they are dispatched in the object's thread; call \a callQueuedEvents() or \a maybeCallQueuedEvents() to drain the queue. \a PIThread can act as the performer for such objects. See \ref PIObject_sec0 and \a PIThread.
|
||||
|
||||
\par Introspection
|
||||
|
||||
With \c PIP_INTROSPECTION defined at build time, the introspection module provides macros and APIs to traverse objects and containers at runtime (e.g. for debugging or serialization). Build PIP with this option and link the introspection library; see the introspection headers in \a piintrospection_base.h and related files.
|
||||
|
||||
\par GPU / OpenCL
|
||||
|
||||
The OpenCL module wraps OpenCL for buffers and programs. See \a piopencl.h for the public API. Behavior and limitations may depend on the implementation; check the header and backend when integrating.
|
||||
|
||||
\~russian
|
||||
|
||||
После \ref using_basic имеет смысл перейти к:
|
||||
|
||||
* \ref summary — полный перечень модулей и классов PIP (контейнеры, ввод-вывод, потоки, математика, машина состояний и др.).
|
||||
* \ref config — чтение и запись конфигурации с помощью \a PIConfig (файлы, точечные пути, секции в стиле INI).
|
||||
* \ref code_model — кодогенерация: метаинформация, операторы сериализации, PIMETA, утилита \c pip_cmg и интеграция с CMake.
|
||||
* \ref iostream — бинарные потоки (\a PIBinaryStream, \a PIByteArray), операторы и \a PIMemoryBlock.
|
||||
* \ref chunk_stream — версионная сериализация с \a PIChunkStream (чанки по id, обратная совместимость).
|
||||
* \ref state_machine — машина состояний: концепции, состояния, переходы, условия, \a PIStateMachine.
|
||||
* \ref connection — сложный ввод-вывод: \a PIConnection, пул устройств, фильтры, отправители, диагностика.
|
||||
* \ref client_server — TCP-сервер и клиент (\a PIClientServer::Server, \a PIClientServer::Client).
|
||||
* \ref console — тайлинговая консоль \a PIScreen, тайлы, виджеты (список, кнопка, прогресс, ввод и др.).
|
||||
* \ref application — уровень приложения: \a PICLI, \a PILog, \a PISystemMonitor, \a PISingleApplication, \a PITranslator.
|
||||
* \ref threading — многопоточность: \a PIThread, \a PITimer, синхронизация, исполнитель, блокирующая очередь.
|
||||
* \ref examples — перечень примеров в doc/examples.
|
||||
|
||||
События и обработчики описаны на странице \a PIObject (\ref PIObject_sec0).
|
||||
|
||||
\par Потоки и события
|
||||
|
||||
Многие классы PIP наследуют \a PIObject и используют события: обработчики могут вызываться сразу или ставиться в очередь. При постановке в очередь (например из другого потока) они обрабатываются в потоке объекта; вызов \a callQueuedEvents() или \a maybeCallQueuedEvents() обрабатывает очередь. \a PIThread может выступать исполнителем для таких объектов. См. \ref PIObject_sec0 и \a PIThread.
|
||||
|
||||
\par Интроспекция
|
||||
|
||||
При сборке с макросом \c PIP_INTROSPECTION модуль интроспекции предоставляет макросы и API для обхода объектов и контейнеров в runtime (например для отладки или сериализации). Соберите PIP с этой опцией и подключите библиотеку интроспекции; см. заголовки \a piintrospection_base.h и связанные.
|
||||
|
||||
\par GPU / OpenCL
|
||||
|
||||
Модуль OpenCL — обёртка над OpenCL для буферов и программ. Публичный API: \a piopencl.h. Поведение и ограничения зависят от реализации; при интеграции смотрите заголовок и бэкенд.
|
||||
@@ -3,10 +3,10 @@
|
||||
|
||||
\~english
|
||||
|
||||
Many novice programmers are solved many common task with system integrity: output to console,
|
||||
keyboard buttons press detecting, working with serial ports, ethernet or files, and many other.
|
||||
These tasks can solve this library, and code, based only on PIP will be compile and work
|
||||
similar on many systems: Windows, any Linux, Red Hat, FreeBSD, MacOS X and QNX.
|
||||
Many novice programmers face common tasks when interacting with the system: output to console,
|
||||
detecting keyboard presses, working with serial ports, ethernet or files, and more.
|
||||
This library addresses these tasks; code based on PIP will compile and work
|
||||
similarly on many systems: Windows, any Linux, Red Hat, FreeBSD, MacOS X and QNX.
|
||||
Typical application on PIP looks like this: \n
|
||||
|
||||
\~russian
|
||||
@@ -112,17 +112,17 @@ int main(int argc, char * argv[]) {
|
||||
This code demonstrates simple interactive configurable program, which can be started with console
|
||||
display or not, and with debug or not. \b MainClass is central class that also can be inherited from
|
||||
\a PIThread and reimplement \a run() function.
|
||||
\n Many PIP classes has events and event handlers, which can be connected one to another.
|
||||
\n Many PIP classes have events and event handlers, which can be connected one to another.
|
||||
Details you can see at \a PIObject reference page (\ref PIObject_sec0).
|
||||
\n To configure your program from file use \a PIConfig.
|
||||
\n If you want more information see \ref using_advanced
|
||||
\n To configure your program from file use \a PIConfig (see \ref config).
|
||||
\n For more topics see \ref using_advanced.
|
||||
|
||||
\~russian
|
||||
|
||||
Этот код демонстрирует простую конфигурируемую программу, которая может быть запущена с
|
||||
This code demonstrates simple interactive configurable program, which can be started with console
|
||||
display or not, and with debug or not. \b MainClass is central class that also can be inherited from
|
||||
\a PIThread and reimplement \a run() function.
|
||||
\n Many PIP classes has events and event handlers, which can be connected one to another.
|
||||
Details you can see at \a PIObject reference page (\ref PIObject_sec0).
|
||||
\n To configure your program from file use \a PIConfig.
|
||||
консолью или без неё, с отладочным выводом или без. \b MainClass — центральный класс, который
|
||||
также может быть унаследован от \a PIThread с переопределением \a run().
|
||||
\n У многих классов PIP есть события и обработчики, которые можно связывать между собой.
|
||||
Подробности — на странице \a PIObject (\ref PIObject_sec0).
|
||||
\n Для настройки приложения из файла используйте \a PIConfig (см. \ref config).
|
||||
\n Дополнительные темы — на странице \ref using_advanced.
|
||||
|
||||
BIN
lang/pip_ru.btf
BIN
lang/pip_ru.btf
Binary file not shown.
512
lang/pip_ru.ts
512
lang/pip_ru.ts
@@ -20,7 +20,7 @@
|
||||
<context>
|
||||
<name>PIFile</name>
|
||||
<message>
|
||||
<location filename="../libs/main/io_devices/pifile.cpp" line="300"/>
|
||||
<location filename="../libs/main/io_devices/pifile.cpp" line="296"/>
|
||||
<source>Downsize is not supported yet :-(</source>
|
||||
<translation>Уменьшение размера не поддерживается</translation>
|
||||
</message>
|
||||
@@ -66,6 +66,239 @@
|
||||
<translation type="vanished">Предупреждение: PICrypt неактивен, для активации установите библиотеку sodium и пересоберите PIP</translation>
|
||||
</message>
|
||||
</context>
|
||||
<context>
|
||||
<name>PIUnits</name>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="88"/>
|
||||
<source>E</source>
|
||||
<translation>Э</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="85"/>
|
||||
<source>G</source>
|
||||
<translation>Г</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="84"/>
|
||||
<source>M</source>
|
||||
<translation>М</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="87"/>
|
||||
<source>P</source>
|
||||
<translation>П</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="92"/>
|
||||
<source>Q</source>
|
||||
<translation>Кв</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="91"/>
|
||||
<source>R</source>
|
||||
<translation>Рн</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="86"/>
|
||||
<source>T</source>
|
||||
<translation>Т</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="90"/>
|
||||
<source>Y</source>
|
||||
<translation>И</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="89"/>
|
||||
<source>Z</source>
|
||||
<translation>З</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="101"/>
|
||||
<source>a</source>
|
||||
<translation>а</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="95"/>
|
||||
<source>c</source>
|
||||
<translation>с</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="94"/>
|
||||
<source>d</source>
|
||||
<translation>д</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="100"/>
|
||||
<source>f</source>
|
||||
<translation>ф</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="82"/>
|
||||
<source>h</source>
|
||||
<translation>г</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="83"/>
|
||||
<source>k</source>
|
||||
<translation>к</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="96"/>
|
||||
<source>m</source>
|
||||
<translation>м</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="98"/>
|
||||
<source>n</source>
|
||||
<translation>н</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="99"/>
|
||||
<source>p</source>
|
||||
<translation>п</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="104"/>
|
||||
<source>r</source>
|
||||
<translation>рн</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="97"/>
|
||||
<source>u</source>
|
||||
<translation>мк</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="103"/>
|
||||
<source>y</source>
|
||||
<translation>и</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="102"/>
|
||||
<source>z</source>
|
||||
<translation>з</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="81"/>
|
||||
<source>da</source>
|
||||
<translation>да</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="88"/>
|
||||
<source>exa</source>
|
||||
<translation>экса</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="101"/>
|
||||
<source>atto</source>
|
||||
<translation>атто</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="81"/>
|
||||
<source>deca</source>
|
||||
<translation>дека</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="94"/>
|
||||
<source>deci</source>
|
||||
<translation>деци</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="85"/>
|
||||
<source>giga</source>
|
||||
<translation>гига</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="83"/>
|
||||
<source>kilo</source>
|
||||
<translation>кило</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="84"/>
|
||||
<source>mega</source>
|
||||
<translation>мега</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="98"/>
|
||||
<source>nano</source>
|
||||
<translation>нано</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="87"/>
|
||||
<source>peta</source>
|
||||
<translation>пета</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="99"/>
|
||||
<source>pico</source>
|
||||
<translation>пико</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="86"/>
|
||||
<source>tera</source>
|
||||
<translation>тера</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="95"/>
|
||||
<source>centi</source>
|
||||
<translation>санти</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="100"/>
|
||||
<source>femto</source>
|
||||
<translation>фемто</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="82"/>
|
||||
<source>hecto</source>
|
||||
<translation>гекто</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="97"/>
|
||||
<source>micro</source>
|
||||
<translation>микро</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="96"/>
|
||||
<source>milli</source>
|
||||
<translation>милли</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="91"/>
|
||||
<source>ronna</source>
|
||||
<translation>ронна</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="104"/>
|
||||
<source>ronto</source>
|
||||
<translation>ронто</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="103"/>
|
||||
<source>yocto</source>
|
||||
<translation>иокто</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="90"/>
|
||||
<source>yotta</source>
|
||||
<translation>иотта</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="102"/>
|
||||
<source>zepto</source>
|
||||
<translation>зепто</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="89"/>
|
||||
<source>zetta</source>
|
||||
<translation>зетта</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_prefix.cpp" line="92"/>
|
||||
<source>quetta</source>
|
||||
<translation>кветта</translation>
|
||||
</message>
|
||||
</context>
|
||||
<context>
|
||||
<name>PIBinLog</name>
|
||||
<message>
|
||||
@@ -253,47 +486,47 @@
|
||||
<context>
|
||||
<name>PIString</name>
|
||||
<message>
|
||||
<location filename="../libs/main/text/pistring.cpp" line="1787"/>
|
||||
<location filename="../libs/main/text/pistring.cpp" line="1807"/>
|
||||
<source>B</source>
|
||||
<translation>Б</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/text/pistring.cpp" line="1807"/>
|
||||
<location filename="../libs/main/text/pistring.cpp" line="1827"/>
|
||||
<source>EiB</source>
|
||||
<translation>ЭиБ</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/text/pistring.cpp" line="1804"/>
|
||||
<location filename="../libs/main/text/pistring.cpp" line="1824"/>
|
||||
<source>GiB</source>
|
||||
<translation>ГиБ</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/text/pistring.cpp" line="1802"/>
|
||||
<location filename="../libs/main/text/pistring.cpp" line="1822"/>
|
||||
<source>KiB</source>
|
||||
<translation>КиБ</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/text/pistring.cpp" line="1803"/>
|
||||
<location filename="../libs/main/text/pistring.cpp" line="1823"/>
|
||||
<source>MiB</source>
|
||||
<translation>МиБ</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/text/pistring.cpp" line="1806"/>
|
||||
<location filename="../libs/main/text/pistring.cpp" line="1826"/>
|
||||
<source>PiB</source>
|
||||
<translation>ПиБ</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/text/pistring.cpp" line="1805"/>
|
||||
<location filename="../libs/main/text/pistring.cpp" line="1825"/>
|
||||
<source>TiB</source>
|
||||
<translation>ТиБ</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/text/pistring.cpp" line="1809"/>
|
||||
<location filename="../libs/main/text/pistring.cpp" line="1829"/>
|
||||
<source>YiB</source>
|
||||
<translation>ЙиБ</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/text/pistring.cpp" line="1808"/>
|
||||
<location filename="../libs/main/text/pistring.cpp" line="1828"/>
|
||||
<source>ZiB</source>
|
||||
<translation>ЗиБ</translation>
|
||||
</message>
|
||||
@@ -319,7 +552,7 @@
|
||||
<context>
|
||||
<name>PIProcess</name>
|
||||
<message>
|
||||
<location filename="../libs/main/system/piprocess.cpp" line="200"/>
|
||||
<location filename="../libs/main/system/piprocess.cpp" line="316"/>
|
||||
<source>"CreateProcess" error: %1</source>
|
||||
<translation>Ошибка "CreateProcess": %1</translation>
|
||||
</message>
|
||||
@@ -327,12 +560,12 @@
|
||||
<context>
|
||||
<name>PIVariant</name>
|
||||
<message>
|
||||
<location filename="../libs/main/types/pivariant.cpp" line="415"/>
|
||||
<location filename="../libs/main/types/pivariant.cpp" line="418"/>
|
||||
<source>Can`t initialize PIVariant from unregistered type "%1"!</source>
|
||||
<translation>Невозможно инициализировать PIVariant из незарегистрированного типа "%1"!</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/types/pivariant.cpp" line="393"/>
|
||||
<location filename="../libs/main/types/pivariant.cpp" line="396"/>
|
||||
<source>Can`t initialize PIVariant from unregistered typeID "%1"!</source>
|
||||
<translation>Невозможно инициализировать PIVariant из незарегистрированного ID типа "%1"!</translation>
|
||||
</message>
|
||||
@@ -358,7 +591,7 @@
|
||||
<context>
|
||||
<name>PIEthernet</name>
|
||||
<message>
|
||||
<location filename="../libs/main/io_devices/piethernet.cpp" line="1272"/>
|
||||
<location filename="../libs/main/io_devices/piethernet.cpp" line="1275"/>
|
||||
<source>Can`t get interfaces: %1</source>
|
||||
<translation>Невозможно получить интерфейсы: %1</translation>
|
||||
</message>
|
||||
@@ -389,6 +622,67 @@
|
||||
<translation>Ошибка: Режим ReadWrite не поддерживается, используйте WriteOnly или ReadOnly</translation>
|
||||
</message>
|
||||
</context>
|
||||
<context>
|
||||
<name>PIUnitsMass</name>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_mass.cpp" line="35"/>
|
||||
<source>g</source>
|
||||
<translation>г</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_mass.cpp" line="37"/>
|
||||
<source>℥</source>
|
||||
<translation type="unfinished"></translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_mass.cpp" line="36"/>
|
||||
<source>lb</source>
|
||||
<translation type="unfinished"></translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_mass.cpp" line="25"/>
|
||||
<source>gram</source>
|
||||
<translation>грамм</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_mass.cpp" line="27"/>
|
||||
<source>ounce</source>
|
||||
<translation>унция</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_mass.cpp" line="26"/>
|
||||
<source>pound</source>
|
||||
<translation>фунт</translation>
|
||||
</message>
|
||||
</context>
|
||||
<context>
|
||||
<name>PIUnitsTime</name>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_time.cpp" line="34"/>
|
||||
<source>s</source>
|
||||
<translation>с</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_time.cpp" line="35"/>
|
||||
<source>Hz</source>
|
||||
<translation>Гц</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_time.cpp" line="26"/>
|
||||
<source>hertz</source>
|
||||
<translation>герц</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_time.cpp" line="25"/>
|
||||
<source>second</source>
|
||||
<translation>секунд</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_time.cpp" line="25"/>
|
||||
<source>secons</source>
|
||||
<translation type="vanished">секунд</translation>
|
||||
</message>
|
||||
</context>
|
||||
<context>
|
||||
<name>PIConnection</name>
|
||||
<message>
|
||||
@@ -455,6 +749,29 @@
|
||||
<translation>toSystemTime() Предупреждение: неверная частота: %1</translation>
|
||||
</message>
|
||||
</context>
|
||||
<context>
|
||||
<name>PIUnitsAngle</name>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_angle.cpp" line="36"/>
|
||||
<source>°</source>
|
||||
<translation type="unfinished"></translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_angle.cpp" line="37"/>
|
||||
<source>rad</source>
|
||||
<translation>рад</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_angle.cpp" line="27"/>
|
||||
<source>degree</source>
|
||||
<translation>градусы</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_angle.cpp" line="28"/>
|
||||
<source>radian</source>
|
||||
<translation>радиан</translation>
|
||||
</message>
|
||||
</context>
|
||||
<context>
|
||||
<name>PIEthUtilBase</name>
|
||||
<message>
|
||||
@@ -528,4 +845,171 @@
|
||||
<translation>Невозможно открыть процесс с ID = %1, %2!</translation>
|
||||
</message>
|
||||
</context>
|
||||
<context>
|
||||
<name>PIUnitsDistance</name>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_distance.cpp" line="40"/>
|
||||
<source>"</source>
|
||||
<translation type="unfinished"></translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_distance.cpp" line="44"/>
|
||||
<source>Å</source>
|
||||
<translation type="unfinished"></translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_distance.cpp" line="39"/>
|
||||
<source>m</source>
|
||||
<translation>м</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_distance.cpp" line="45"/>
|
||||
<source>au</source>
|
||||
<translation>а. е.</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_distance.cpp" line="42"/>
|
||||
<source>ft</source>
|
||||
<translation>фут</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_distance.cpp" line="43"/>
|
||||
<source>yd</source>
|
||||
<translation>ярд</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_distance.cpp" line="27"/>
|
||||
<source>mil</source>
|
||||
<translation>мил</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_distance.cpp" line="28"/>
|
||||
<source>foot</source>
|
||||
<translation>фут</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_distance.cpp" line="26"/>
|
||||
<source>inch</source>
|
||||
<translation>дюйм</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_distance.cpp" line="41"/>
|
||||
<source>thou</source>
|
||||
<translation>мил</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_distance.cpp" line="29"/>
|
||||
<source>yard</source>
|
||||
<translation>ярд</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_distance.cpp" line="25"/>
|
||||
<source>meter</source>
|
||||
<translation>метр</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_distance.cpp" line="30"/>
|
||||
<source>angstrom</source>
|
||||
<translation>ангстрем</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_distance.cpp" line="31"/>
|
||||
<source>astronomical unit</source>
|
||||
<translation>астрономическая единица</translation>
|
||||
</message>
|
||||
</context>
|
||||
<context>
|
||||
<name>PIUnitsPressure</name>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_pressure.cpp" line="36"/>
|
||||
<source>Pa</source>
|
||||
<translation>Па</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_pressure.cpp" line="37"/>
|
||||
<source>atm</source>
|
||||
<translation>атм</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_pressure.cpp" line="38"/>
|
||||
<source>bar</source>
|
||||
<translation>бар</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_pressure.cpp" line="39"/>
|
||||
<source>mmHg</source>
|
||||
<translation>мм рт. ст.</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_pressure.cpp" line="28"/>
|
||||
<source>mm Hg</source>
|
||||
<translation>мм рт. ст.</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_pressure.cpp" line="25"/>
|
||||
<source>pascal</source>
|
||||
<translation>паскаль</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_pressure.cpp" line="26"/>
|
||||
<source>atmosphere</source>
|
||||
<translation>атмосфер</translation>
|
||||
</message>
|
||||
</context>
|
||||
<context>
|
||||
<name>PIUnitsInformation</name>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_information.cpp" line="35"/>
|
||||
<source>B</source>
|
||||
<translation>Б</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_information.cpp" line="34"/>
|
||||
<source>b</source>
|
||||
<translation>б</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_information.cpp" line="25"/>
|
||||
<source>bit</source>
|
||||
<translation>бит</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_information.cpp" line="26"/>
|
||||
<source>byte</source>
|
||||
<translation>байт</translation>
|
||||
</message>
|
||||
</context>
|
||||
<context>
|
||||
<name>PIUnitsTemperature</name>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_temperature.cpp" line="35"/>
|
||||
<source>K</source>
|
||||
<translation type="unfinished"></translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_temperature.cpp" line="36"/>
|
||||
<source>°C</source>
|
||||
<translation type="unfinished"></translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_temperature.cpp" line="37"/>
|
||||
<source>°F</source>
|
||||
<translation type="unfinished"></translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_temperature.cpp" line="25"/>
|
||||
<source>Kelvin</source>
|
||||
<translation>Кельвин</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_temperature.cpp" line="26"/>
|
||||
<source>Celsius</source>
|
||||
<translation>Цельсий</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../libs/main/units/piunits_class_temperature.cpp" line="27"/>
|
||||
<source>Fahrenheit</source>
|
||||
<translation>Фаренгейт</translation>
|
||||
</message>
|
||||
</context>
|
||||
</TS>
|
||||
|
||||
@@ -72,11 +72,7 @@ PIClientServer::Server::~Server() {
|
||||
clean_thread->waitForFinish();
|
||||
piDeleteSafety(clean_thread);
|
||||
stopServer();
|
||||
for (auto c: clients) {
|
||||
c->aboutDelete();
|
||||
c->destroy();
|
||||
delete c;
|
||||
}
|
||||
closeAll();
|
||||
piDeleteSafety(tcp_server);
|
||||
}
|
||||
|
||||
|
||||
@@ -189,8 +189,8 @@ void PIScreen::SystemConsole::print() {
|
||||
for (int j = 0; j < dh; ++j) {
|
||||
int k = j * dw + i;
|
||||
Cell & c(cells[j + dy0][i + dx0]);
|
||||
PRIVATE->chars[k].Char.UnicodeChar = 0;
|
||||
PRIVATE->chars[k].Char.AsciiChar = c.symbol.toConsole1Byte();
|
||||
PRIVATE->chars[k].Char.UnicodeChar = c.symbol.unicode16Code();
|
||||
// PRIVATE->chars[k].Char.AsciiChar = c.symbol.toConsole1Byte();
|
||||
PRIVATE->chars[k].Attributes = attributes(c);
|
||||
}
|
||||
// piCout << "draw" << dw << dh;
|
||||
@@ -200,7 +200,7 @@ void PIScreen::SystemConsole::print() {
|
||||
PRIVATE->srect.Top += dy0;
|
||||
PRIVATE->srect.Right -= width - dx1 - 1;
|
||||
PRIVATE->srect.Bottom -= height - dy1 - 1;
|
||||
WriteConsoleOutput(PRIVATE->hOut, PRIVATE->chars.data(), PRIVATE->bs, PRIVATE->bc, &PRIVATE->srect);
|
||||
WriteConsoleOutputW(PRIVATE->hOut, PRIVATE->chars.data(), PRIVATE->bs, PRIVATE->bc, &PRIVATE->srect);
|
||||
#else
|
||||
PIString s;
|
||||
int si = 0, sj = 0;
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Tile for PIScreen with PIConsole API
|
||||
Andrey Bychkov work.a.b@yandex.ru
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Lesser General Public License as published by
|
||||
the Free Software Foundation, either version 3 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 Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "piscreenconsole.h"
|
||||
|
||||
using namespace PIScreenTypes;
|
||||
|
||||
|
||||
TileVars::TileVars(const PIString & n): PIScreenTile(n) {
|
||||
alignment = Left;
|
||||
}
|
||||
|
||||
|
||||
void TileVars::sizeHint(int & w, int & h) const {}
|
||||
|
||||
void TileVars::drawEvent(PIScreenDrawer * d) {}
|
||||
|
||||
|
||||
PIScreenConsoleTile::PIScreenConsoleTile() {}
|
||||
@@ -59,7 +59,7 @@ bool PIHTTPClient::init() {
|
||||
if (is_cancel) return false;
|
||||
CurlThreadPool::instance();
|
||||
if (!PRIVATE->init()) return false;
|
||||
auto ait = request.arguments().makeIterator();
|
||||
auto ait = request.queryArguments().makeIterator();
|
||||
while (ait.next()) {
|
||||
if (!url.contains('?'))
|
||||
url.append('?');
|
||||
@@ -93,6 +93,7 @@ bool PIHTTPClient::init() {
|
||||
// curl_easy_setopt(PRIVATE->handle, CURLOPT_VERBOSE, 1L);
|
||||
// curl_easy_setopt(PRIVATE->handle, CURLOPT_ERRORBUFFER, buffer_error.data());
|
||||
curl_easy_setopt(PRIVATE->handle, CURLOPT_SSL_VERIFYPEER, 0L);
|
||||
curl_easy_setopt(PRIVATE->handle, CURLOPT_SSL_VERIFYHOST, ignore_ssl_errors ? 0L : 1L);
|
||||
if (request.body().isNotEmpty()) {
|
||||
curl_easy_setopt(PRIVATE->handle, CURLOPT_UPLOAD, 1L);
|
||||
curl_easy_setopt(PRIVATE->handle, CURLOPT_INFILESIZE_LARGE, static_cast<curl_off_t>(request.body().size()));
|
||||
@@ -246,7 +247,7 @@ PIHTTPClient * PIHTTPClient::onFinish(std::function<void()> f) {
|
||||
|
||||
|
||||
PIHTTPClient * PIHTTPClient::onFinish(std::function<void(const PIHTTP::MessageConst &)> f) {
|
||||
on_finish = f;
|
||||
on_finish = std::move(f);
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -257,7 +258,7 @@ PIHTTPClient * PIHTTPClient::onError(std::function<void()> f) {
|
||||
|
||||
|
||||
PIHTTPClient * PIHTTPClient::onError(std::function<void(const PIHTTP::MessageConst &)> f) {
|
||||
on_error = f;
|
||||
on_error = std::move(f);
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -268,7 +269,13 @@ PIHTTPClient * PIHTTPClient::onAbort(std::function<void()> f) {
|
||||
|
||||
|
||||
PIHTTPClient * PIHTTPClient::onAbort(std::function<void(const PIHTTP::MessageConst &)> f) {
|
||||
on_abort = f;
|
||||
on_abort = std::move(f);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
PIHTTPClient * PIHTTPClient::ignoreSSLErrors() {
|
||||
ignore_ssl_errors = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
@@ -363,5 +363,5 @@ void MicrohttpdServer::addFixedHeaders(MessageMutable & msg) {
|
||||
msg.addHeader(Header::ContentType, "application/json; charset=utf-8");
|
||||
}
|
||||
}
|
||||
msg.addHeader(Header::AccessControlAllowOrigin, "*");
|
||||
// msg.addHeader(Header::AccessControlAllowOrigin, "*");
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ bool PIHTTPServer::registerPath(const PIString & path, PIHTTP::Method method, Re
|
||||
Endpoint ep;
|
||||
if (!ep.create(path)) return false;
|
||||
ep.method = method;
|
||||
ep.function = functor;
|
||||
ep.function = std::move(functor);
|
||||
endpoints[ep.priority] << ep;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,13 @@
|
||||
/*! \file piapplicationmodule.h
|
||||
* \ingroup Application
|
||||
* \~\brief
|
||||
* \~english Application-level classes.
|
||||
* \~russian Классы уровня "приложение".
|
||||
*
|
||||
* \~\details
|
||||
* \~english Includes the public CLI, logging, single-application, system monitoring, and translation headers.
|
||||
* \~russian Подключает публичные заголовки CLI, логирования, одиночного приложения, системного мониторинга и перевода.
|
||||
*/
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Module includes
|
||||
@@ -30,14 +40,14 @@
|
||||
//! target_link_libraries([target] PIP)
|
||||
//! \endcode
|
||||
//!
|
||||
//! \~english \par Common
|
||||
//! \~russian \par Общее
|
||||
//!
|
||||
//! \~english
|
||||
//! These files provides some classes for help to create application
|
||||
//! This umbrella header includes public Application classes for command-line
|
||||
//! parsing, logging, single-instance control, process monitoring and translation.
|
||||
//!
|
||||
//! \~russian
|
||||
//! Эти файлы предоставляют классы для облегчения создания приложения
|
||||
//! Этот зонтичный заголовок подключает публичные классы Application для
|
||||
//! разбора командной строки, ведения лога, контроля одного экземпляра,
|
||||
//! мониторинга процесса и перевода.
|
||||
//!
|
||||
//! \~\authors
|
||||
//! \~english
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/*! \file picli.h
|
||||
* \ingroup Application
|
||||
* \~\brief
|
||||
* \~english Command-Line parser
|
||||
* \~russian Парсер командной строки
|
||||
*/
|
||||
//! \~\file picli.h
|
||||
//! \~\ingroup Application
|
||||
//! \brief
|
||||
//! \~english Command-line argument parser
|
||||
//! \~russian Парсер аргументов командной строки
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Command-Line Parser
|
||||
@@ -29,10 +28,15 @@
|
||||
#include "piset.h"
|
||||
#include "pistringlist.h"
|
||||
|
||||
//! \ingroup Application
|
||||
//! \~\ingroup Application
|
||||
//! \~\brief
|
||||
//! \~english Command-Line parser.
|
||||
//! \~russian Парсер командной строки.
|
||||
//! \~english Command-line argument parser class
|
||||
//! \~russian Класс парсера аргументов командной строки
|
||||
//! \details
|
||||
//! \~english The PICLI class provides convenient parsing of command-line arguments. It supports short keys (e.g., -c), full keys (e.g.,
|
||||
//! --console), and arguments with/without values.
|
||||
//! \~russian Класс PICLI предоставляет удобный разбор аргументов командной строки. Поддерживаются короткие ключи (например, -c), полные
|
||||
//! ключи (например, --console) и аргументы с значениями/без значений.
|
||||
class PIP_EXPORT PICLI {
|
||||
public:
|
||||
//! \~english Constructs %PICLI from "argc" and "argv" from "int main()" method.
|
||||
@@ -64,13 +68,25 @@ public:
|
||||
//! \~english Returns unparsed command-line argument by index "index". Index 0 is program execute command.
|
||||
//! \~russian Возвращает исходный аргумент командной строки по индексу "index". Индекс 0 это команда вызова программы.
|
||||
PIString rawArgument(int index);
|
||||
|
||||
//! \~english Returns mandatory positional argument by index.
|
||||
//! \~russian Возвращает обязательный позиционный аргумент по индексу.
|
||||
PIString mandatoryArgument(int index);
|
||||
|
||||
//! \~english Returns optional positional argument by index.
|
||||
//! \~russian Возвращает необязательный позиционный аргумент по индексу.
|
||||
PIString optionalArgument(int index);
|
||||
|
||||
//! \~english Returns unparsed command-line arguments.
|
||||
//! \~russian Возвращает исходные аргументы командной строки.
|
||||
const PIStringList & rawArguments();
|
||||
|
||||
//! \~english Returns all mandatory positional arguments.
|
||||
//! \~russian Возвращает все обязательные позиционные аргументы.
|
||||
const PIStringList & mandatoryArguments();
|
||||
|
||||
//! \~english Returns all optional positional arguments.
|
||||
//! \~russian Возвращает все необязательные позиционные аргументы.
|
||||
const PIStringList & optionalArguments();
|
||||
|
||||
//! \~english Returns program execute command without arguments.
|
||||
@@ -93,18 +109,52 @@ public:
|
||||
//! \~russian Возвращает полный ключ аргумента "name" или пустую строку, если аргумента нет.
|
||||
PIString argumentFullKey(const PIString & name);
|
||||
|
||||
//! \~english Returns prefix used for short keys.
|
||||
//! \~russian Возвращает префикс коротких ключей.
|
||||
const PIString & shortKeyPrefix() const { return _prefix_short; }
|
||||
|
||||
//! \~english Returns prefix used for full keys.
|
||||
//! \~russian Возвращает префикс полных ключей.
|
||||
const PIString & fullKeyPrefix() const { return _prefix_full; }
|
||||
|
||||
//! \~english Returns expected count of mandatory positional arguments.
|
||||
//! \~russian Возвращает ожидаемое количество обязательных позиционных аргументов.
|
||||
int mandatoryArgumentsCount() const { return _count_mand; }
|
||||
|
||||
//! \~english Returns expected count of optional positional arguments.
|
||||
//! \~russian Возвращает ожидаемое количество необязательных позиционных аргументов.
|
||||
int optionalArgumentsCount() const { return _count_opt; }
|
||||
|
||||
//! \~english Sets prefix used for short keys such as "-d".
|
||||
//! \~russian Устанавливает префикс коротких ключей, например "-d".
|
||||
void setShortKeyPrefix(const PIString & prefix);
|
||||
|
||||
//! \~english Sets prefix used for full keys such as "--debug".
|
||||
//! \~russian Устанавливает префикс полных ключей, например "--debug".
|
||||
void setFullKeyPrefix(const PIString & prefix);
|
||||
|
||||
//! \~english Sets count of mandatory positional arguments collected before optional ones.
|
||||
//! \~russian Устанавливает количество обязательных позиционных аргументов, собираемых до необязательных.
|
||||
void setMandatoryArgumentsCount(const int count);
|
||||
|
||||
//! \~english Sets count of optional positional arguments. Negative value means unlimited.
|
||||
//! \~russian Устанавливает количество необязательных позиционных аргументов. Отрицательное значение означает без ограничения.
|
||||
void setOptionalArgumentsCount(const int count);
|
||||
|
||||
//! \~english Returns debug mode flag.
|
||||
//! \~russian Возвращает флаг режима отладки.
|
||||
bool debug() const { return debug_; }
|
||||
|
||||
//! \~english Enables or disables debug mode.
|
||||
//! \~russian Включает или выключает режим отладки.
|
||||
void setDebug(bool debug) { debug_ = debug; }
|
||||
|
||||
//! \~english Returns class name.
|
||||
//! \~russian Возвращает имя класса.
|
||||
PIConstChars className() const { return "PICLI"; }
|
||||
|
||||
//! \~english Returns human-readable object name.
|
||||
//! \~russian Возвращает читаемое имя объекта.
|
||||
PIString name() const { return PIStringAscii("CLI"); }
|
||||
|
||||
private:
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/*! \file pilog.h
|
||||
* \ingroup Application
|
||||
* \~\brief
|
||||
* \~english High-level log
|
||||
* \~russian Высокоуровневый лог
|
||||
*/
|
||||
//! \~\file pilog.h
|
||||
//! \~\ingroup Application
|
||||
//! \~\brief
|
||||
//! \~english High-level log
|
||||
//! \~russian Высокоуровневый лог
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
High-level log
|
||||
@@ -30,15 +29,23 @@
|
||||
#include "piiostream.h"
|
||||
#include "pithread.h"
|
||||
|
||||
//! \ingroup Application
|
||||
//! \~\ingroup Application
|
||||
//! \~\brief
|
||||
//! \~english High-level log
|
||||
//! \~russian Высокоуровневый лог
|
||||
//! \~\details
|
||||
//! \~english Provides log with optional file and console output, with configurable timestamp format and line format.
|
||||
//! \~russian Предоставляет лог с опциональным выводом в файл и консоль, с настраиваемым форматом метки времени и форматом строки.
|
||||
class PIP_EXPORT PILog: public PIThread {
|
||||
PIOBJECT_SUBCLASS(PILog, PIThread)
|
||||
|
||||
public:
|
||||
//! \~english Constructs log with console output, timestamped lines and rotated log files.
|
||||
//! \~russian Создает лог с выводом в консоль, строками с метками времени и ротацией файлов.
|
||||
PILog();
|
||||
|
||||
//! \~english Stops logging thread and flushes queued messages.
|
||||
//! \~russian Останавливает поток логирования и дописывает сообщения из очереди.
|
||||
~PILog();
|
||||
|
||||
//! \~english Message category
|
||||
@@ -58,8 +65,8 @@ public:
|
||||
All /** \~english All \~russian Все */ = 0xFF,
|
||||
};
|
||||
|
||||
//! \~english Set output channel \"o\" to \"on\".
|
||||
//! \~russian Установить канал вывода \"o\" в \"on\".
|
||||
//! \~english Enables or disables output channel "o".
|
||||
//! \~russian Включает или выключает канал вывода "o".
|
||||
void setOutput(Output o, bool on = true) { output.setFlag(o, on); }
|
||||
|
||||
//! \~english Returns prefix for filename.
|
||||
@@ -80,7 +87,7 @@ public:
|
||||
|
||||
|
||||
//! \~english Returns directory for log files.
|
||||
//! \~russian Возвращает директорию для файлов.
|
||||
//! \~russian Возвращает директорию файлов лога.
|
||||
PIString dir() const { return log_dir; }
|
||||
|
||||
//! \~english Set directory for log files. Should be set \b after \a setLogName()!
|
||||
@@ -92,8 +99,8 @@ public:
|
||||
//! \~russian Возвращает время жизни файла.
|
||||
PISystemTime fileSplitTime() const { return split_time; }
|
||||
|
||||
//! \~english Set lifetime for file. Each "st" interval new file will be created.
|
||||
//! \~russian Устанавливает время жизни файла. Каждый интервал "st" будет создан новый файл.
|
||||
//! \~english Sets log file rotation interval. A new file is created every "st".
|
||||
//! \~russian Устанавливает интервал ротации файла лога. Новый файл создается каждые "st".
|
||||
void setFileSplitTime(PISystemTime st) { split_time = st; }
|
||||
|
||||
|
||||
@@ -110,8 +117,8 @@ public:
|
||||
//! \~russian Возвращает формат строки.
|
||||
PIString lineFormat() const { return line_format; }
|
||||
|
||||
//! \~english Set line format. "t" is timestamp, "c" is category and "m" is message. Default is "t - c: m".
|
||||
//! \~russian Устанавливает формат строки. "t" - метка времени, "c" - категория и "m" - сообщение. По умолчанию "t - c: m".
|
||||
//! \~english Sets line format. "t" is timestamp, "c" is category and "m" is message. Default is "t - c: m".
|
||||
//! \~russian Устанавливает формат строки. "t" - метка времени, "c" - категория, "m" - сообщение. По умолчанию "t - c: m".
|
||||
void setLineFormat(const PIString & f);
|
||||
|
||||
|
||||
@@ -119,9 +126,8 @@ public:
|
||||
//! \~russian Возвращает максимальную категорию.
|
||||
Level level() const { return max_level; }
|
||||
|
||||
//! \~english Set maximum level. All levels greater than \"l\" will be ignored. Default is \a Level::Debug.
|
||||
//! \~russian Устанавливает максимальную категорию. Все сообщения с большей категорией, чем \"l\", будут игнорироваться. По умолчанию \a
|
||||
//! Level::Debug.
|
||||
//! \~english Sets maximum accepted level. Messages above "l" are ignored. Default is \a Level::Debug.
|
||||
//! \~russian Устанавливает максимальный принимаемый уровень. Сообщения выше "l" игнорируются. По умолчанию \a Level::Debug.
|
||||
void setLevel(Level l);
|
||||
|
||||
//! \~english Returns \a PICout for \a Level::Error level.
|
||||
@@ -140,12 +146,12 @@ public:
|
||||
//! \~russian Возвращает \a PICout для категории \a Level::Debug.
|
||||
PICout debug(PIObject * context = nullptr);
|
||||
|
||||
//! \~english Write all queued lines and stop. Also called in destructor.
|
||||
//! \~russian Записывает все строки из очереди и останавливается. Также вызывается в деструкторе.
|
||||
//! \~english Writes all queued lines and stops logging. Also called from destructor.
|
||||
//! \~russian Записывает все строки из очереди и останавливает логирование. Также вызывается из деструктора.
|
||||
void stop();
|
||||
|
||||
//! \~english Read all previous and current log content and returns them as %PIStringList.
|
||||
//! \~russian Читает все предыдущие и текущий логи и возвращает их как %PIStringList.
|
||||
//! \~english Reads all rotated and current log lines and returns them as %PIStringList.
|
||||
//! \~russian Читает строки из текущего и уже ротированных логов и возвращает их как %PIStringList.
|
||||
PIStringList readAllLogs() const;
|
||||
|
||||
private:
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/*! \file pisingleapplication.h
|
||||
* \ingroup Application
|
||||
* \~\brief
|
||||
* \~english Single-instance application control
|
||||
* \~russian Контроль одного экземпляра приложения
|
||||
*/
|
||||
//! \~\file pisingleapplication.h
|
||||
//! \~\ingroup Application
|
||||
//! \~\brief
|
||||
//! \~english Single-instance application control
|
||||
//! \~russian Контроль одного экземпляра приложения
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Single application
|
||||
@@ -30,35 +29,44 @@
|
||||
|
||||
class PISharedMemory;
|
||||
|
||||
//! \ingroup Application
|
||||
//! \~\ingroup Application
|
||||
//! \~\brief
|
||||
//! \~english Single-instance application control.
|
||||
//! \~russian Контроль одного экземпляра приложения.
|
||||
//! \~\details
|
||||
//! \~english The PISingleApplication class provides single-instance application control. It allows detecting if the current application
|
||||
//! instance is the first one launched and enables inter-process communication between multiple instances. Multiple instances with the same
|
||||
//! "app_name" can detect each other and communicate. The first instance becomes the server, receiving messages from subsequent instances.
|
||||
//! \~russian Класс PISingleApplication предоставляет контроль одного экземпляра приложения. Он позволяет определить, является ли текущий
|
||||
//! экземпляр первым запущенным, и обеспечивает межпроцессное взаимодействие между несколькими экземплярами. Несколько экземпляров с
|
||||
//! одинаковым "app_name" могут обнаруживать друг друга и обмениваться сообщениями. Первый экземпляр становится сервером, принимающим
|
||||
//! сообщения от последующих экземпляров.
|
||||
|
||||
class PIP_EXPORT PISingleApplication: public PIThread {
|
||||
PIOBJECT_SUBCLASS(PISingleApplication, PIThread);
|
||||
|
||||
public:
|
||||
//! \~english Construct %PISingleApplication with name "app_name"
|
||||
//! \~russian Создает %PISingleApplication с именем "app_name"
|
||||
//! \~english Constructs %PISingleApplication for application name "app_name".
|
||||
//! \~russian Создает %PISingleApplication для имени приложения "app_name".
|
||||
PISingleApplication(const PIString & app_name = PIString());
|
||||
|
||||
//! \~english Stops instance monitoring and releases shared resources.
|
||||
//! \~russian Останавливает мониторинг экземпляра и освобождает общие ресурсы.
|
||||
~PISingleApplication();
|
||||
|
||||
|
||||
//! \~english Returns if this application instance is launched first
|
||||
//! \~russian Возвращает первым ли был запущен этот экземпляр приложения
|
||||
//! \~english Returns whether this process is the first launched instance.
|
||||
//! \~russian Возвращает, является ли этот процесс первым запущенным экземпляром.
|
||||
bool isFirst() const;
|
||||
|
||||
EVENT_HANDLER1(void, sendMessage, const PIByteArray &, m);
|
||||
EVENT1(messageReceived, PIByteArray, m);
|
||||
|
||||
//! \handlers
|
||||
//! \{
|
||||
|
||||
//! \fn void sendMessage(const PIByteArray & m)
|
||||
//! \brief
|
||||
//! \~english Send message "m" to first launched application
|
||||
//! \~russian Посылает сообщение "m" первому запущеному приложению
|
||||
//! \~english Sends message "m" to the first launched application instance
|
||||
//! \~russian Посылает сообщение "m" первому запущенному экземпляру приложения
|
||||
EVENT_HANDLER1(void, sendMessage, const PIByteArray &, m);
|
||||
|
||||
//! \}
|
||||
//! \events
|
||||
@@ -66,8 +74,9 @@ public:
|
||||
|
||||
//! \fn void messageReceived(PIByteArray m)
|
||||
//! \brief
|
||||
//! \~english Raise on first launched application receive message from another
|
||||
//! \~russian Вызывается первым запущеным приложением по приему сообщения от других
|
||||
//! \~english Emitted by the first launched application when receiving a message from another instance
|
||||
//! \~russian Вызывается первым запущенным приложением при получении сообщения от другого экземпляра
|
||||
EVENT1(messageReceived, PIByteArray, m);
|
||||
|
||||
//! \}
|
||||
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/*! \file pisystemmonitor.h
|
||||
* \ingroup Application
|
||||
* \~\brief
|
||||
* \~english System resources monitoring
|
||||
* \~russian Мониторинг ресурсов системы
|
||||
*/
|
||||
//! \~\file pisystemmonitor.h
|
||||
//! \~\ingroup Application
|
||||
//! \brief
|
||||
//! \~english System resources monitoring
|
||||
//! \~russian Мониторинг ресурсов системы
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Process resource monitor
|
||||
@@ -30,23 +29,30 @@
|
||||
#include "pithread.h"
|
||||
|
||||
|
||||
//! \ingroup Application
|
||||
//! \~\ingroup Application
|
||||
//! \~\brief
|
||||
//! \~english Process monitoring.
|
||||
//! \~russian Мониторинг процесса.
|
||||
//! \~english Process and thread resource monitoring.
|
||||
//! \~russian Мониторинг ресурсов процесса и его потоков.
|
||||
//! \details
|
||||
//! \~english This module provides process and system resource monitoring capabilities including CPU usage, memory consumption, and thread
|
||||
//! statistics. It supports cross-platform monitoring on Linux, Windows, macOS, and ESP platforms.
|
||||
//! \~russian Этот модуль предоставляет возможности мониторинга ресурсов процессов и системы, включая использование CPU, потребление памяти
|
||||
//! и статистику потоков. Поддерживается кроссплатформенный мониторинг на Linux, Windows, macOS и ESP платформах.
|
||||
class PIP_EXPORT PISystemMonitor: public PIThread {
|
||||
PIOBJECT_SUBCLASS(PISystemMonitor, PIThread);
|
||||
friend class PIIntrospectionServer;
|
||||
|
||||
public:
|
||||
//! \~english Constructs unassigned %PISystemMonitor
|
||||
//! \~russian Создает непривязанный %PISystemMonitor
|
||||
//! \~english Constructs unassigned %PISystemMonitor.
|
||||
//! \~russian Создает непривязанный %PISystemMonitor.
|
||||
PISystemMonitor();
|
||||
|
||||
//! \~english Stops monitoring and detaches from the current process target.
|
||||
//! \~russian Останавливает мониторинг и отсоединяет объект от текущей цели.
|
||||
~PISystemMonitor();
|
||||
|
||||
#pragma pack(push, 1)
|
||||
//! \ingroup Application
|
||||
//! \~\ingroup Application
|
||||
//! \~\brief
|
||||
//! \~english Process statistics (fixed-size fields).
|
||||
//! \~russian Статистика процесса (фиксированные поля).
|
||||
@@ -95,16 +101,16 @@ public:
|
||||
//! \~russian Память данных в байтах
|
||||
ullong data_memsize = 0;
|
||||
|
||||
//! \~english
|
||||
//! \~russian
|
||||
//! \~english Total RAM in bytes.
|
||||
//! \~russian Общий объем RAM в байтах.
|
||||
ullong ram_total = 0;
|
||||
|
||||
//! \~english
|
||||
//! \~russian
|
||||
//! \~english Free RAM in bytes.
|
||||
//! \~russian Свободный объем RAM в байтах.
|
||||
ullong ram_free = 0;
|
||||
|
||||
//! \~english
|
||||
//! \~russian
|
||||
//! \~english Used RAM in bytes.
|
||||
//! \~russian Используемый объем RAM в байтах.
|
||||
ullong ram_used = 0;
|
||||
|
||||
//! \~english CPU load in kernel space
|
||||
@@ -116,7 +122,7 @@ public:
|
||||
float cpu_load_user = 0.f;
|
||||
};
|
||||
|
||||
//! \ingroup Application
|
||||
//! \~\ingroup Application
|
||||
//! \~\brief
|
||||
//! \~english Thread statistics (fixed-size fields).
|
||||
//! \~russian Статистика потока (фиксированные поля).
|
||||
@@ -151,13 +157,13 @@ public:
|
||||
};
|
||||
#pragma pack(pop)
|
||||
|
||||
//! \ingroup Application
|
||||
//! \~\ingroup Application
|
||||
//! \~\brief
|
||||
//! \~english Process statistics.
|
||||
//! \~russian Статистика процесса.
|
||||
struct PIP_EXPORT ProcessStats: ProcessStatsFixed {
|
||||
//! \~english Fill human-readable fields
|
||||
//! \~russian Заполнить читаемые поля
|
||||
//! \~english Fills human-readable memory size fields.
|
||||
//! \~russian Заполняет поля с человекочитаемыми размерами памяти.
|
||||
void makeStrings();
|
||||
|
||||
//! \~english Execution command
|
||||
@@ -189,7 +195,7 @@ public:
|
||||
PIString data_memsize_readable;
|
||||
};
|
||||
|
||||
//! \ingroup Application
|
||||
//! \~\ingroup Application
|
||||
//! \~\brief
|
||||
//! \~english Thread statistics.
|
||||
//! \~russian Статистика потока.
|
||||
@@ -201,51 +207,59 @@ public:
|
||||
|
||||
#ifndef MICRO_PIP
|
||||
|
||||
//! \~english Starts monitoring of process with PID "pID" and update interval "interval_ms" milliseconds
|
||||
//! \~russian Начинает мониторинг процесса с PID "pID" и интервалом обновления "interval_ms" миллисекунд
|
||||
//! \~english Starts monitoring the process with PID "pID" using the given update interval.
|
||||
//! \~russian Запускает мониторинг процесса с PID "pID" с указанным интервалом обновления.
|
||||
bool startOnProcess(int pID, PISystemTime interval = PISystemTime::fromSeconds(1.));
|
||||
#endif
|
||||
|
||||
//! \~english Starts monitoring of application process with update interval "interval_ms" milliseconds
|
||||
//! \~russian Начинает мониторинг процесса приложения с интервалом обновления "interval_ms" миллисекунд
|
||||
//! \~english Starts monitoring the current application process.
|
||||
//! \~russian Запускает мониторинг текущего процесса приложения.
|
||||
bool startOnSelf(PISystemTime interval = PISystemTime::fromSeconds(1.));
|
||||
|
||||
//! \~english Stop monitoring
|
||||
//! \~russian Останавливает мониторинг
|
||||
//! \~english Stops monitoring.
|
||||
//! \~russian Останавливает мониторинг.
|
||||
void stop();
|
||||
|
||||
|
||||
//! \~english Returns monitoring process PID
|
||||
//! \~russian Возвращает PID наблюдаемого процесса
|
||||
//! \~english Returns PID of the monitored process.
|
||||
//! \~russian Возвращает PID наблюдаемого процесса.
|
||||
int pID() const { return pID_; }
|
||||
|
||||
//! \~english Returns monitoring process statistics
|
||||
//! \~russian Возвращает статистику наблюдаемого процесса
|
||||
//! \~english Returns latest process statistics snapshot.
|
||||
//! \~russian Возвращает последний снимок статистики процесса.
|
||||
ProcessStats statistic() const;
|
||||
|
||||
//! \~english Returns monitoring process threads statistics
|
||||
//! \~russian Возвращает статистику потоков наблюдаемого процесса
|
||||
//! \~english Returns latest per-thread statistics snapshot.
|
||||
//! \~russian Возвращает последний снимок статистики по потокам.
|
||||
PIVector<ThreadStats> threadsStatistic() const;
|
||||
|
||||
//! \~english Replaces current process statistics with external data.
|
||||
//! \~russian Заменяет текущую статистику процесса внешними данными.
|
||||
void setStatistic(const ProcessStats & s);
|
||||
|
||||
|
||||
//! \~english
|
||||
//! \~russian
|
||||
//! \~english Returns total RAM in bytes on supported platforms.
|
||||
//! \~russian Возвращает общий объем RAM в байтах на поддерживаемых платформах.
|
||||
static ullong totalRAM();
|
||||
|
||||
//! \~english
|
||||
//! \~russian
|
||||
//! \~english Returns free RAM in bytes on supported platforms.
|
||||
//! \~russian Возвращает свободный объем RAM в байтах на поддерживаемых платформах.
|
||||
static ullong freeRAM();
|
||||
|
||||
//! \~english
|
||||
//! \~russian
|
||||
//! \~english Returns used RAM in bytes on supported platforms.
|
||||
//! \~russian Возвращает используемый объем RAM в байтах на поддерживаемых платформах.
|
||||
static ullong usedRAM();
|
||||
|
||||
//! \~english
|
||||
//! \~russian
|
||||
//! \~\events
|
||||
//! \~\{
|
||||
|
||||
//! \~\fn void measured()
|
||||
//! \~english Raised after a new statistics snapshot is measured.
|
||||
//! \~russian Вызывается после измерения нового снимка статисти
|
||||
EVENT(measured);
|
||||
|
||||
//! \~\}
|
||||
|
||||
private:
|
||||
void run() override;
|
||||
void gatherThread(llong id);
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/*! \file pitranslator.h
|
||||
* \ingroup Application
|
||||
* \~\brief
|
||||
* \~english Translation support
|
||||
* \~russian Поддержка перевода
|
||||
*/
|
||||
//! \~\file pitranslator.h
|
||||
//! \~\ingroup Application
|
||||
//! \brief
|
||||
//! \~english Translation support
|
||||
//! \~russian Поддержка перевода
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Translation support
|
||||
@@ -29,24 +28,74 @@
|
||||
#include "pistring.h"
|
||||
|
||||
|
||||
#ifdef DOXYGEN
|
||||
|
||||
//! \relatesalso PITranslator
|
||||
//! \~\brief
|
||||
//! \~english Alias to \a PITranslator::tr().
|
||||
//! \~russian Алиас к \a PITranslator::tr().
|
||||
# define piTr
|
||||
|
||||
//! \relatesalso PITranslator
|
||||
//! \~\brief
|
||||
//! \~english Alias to \a PITranslator::trNoOp().
|
||||
//! \~russian Алиас к \a PITranslator::trNoOp().
|
||||
# define piTrNoOp
|
||||
|
||||
#else
|
||||
|
||||
# define piTr PITranslator::tr
|
||||
# define piTrNoOp PITranslator::trNoOp
|
||||
|
||||
//! \ingroup Application
|
||||
#endif
|
||||
|
||||
//! \~\ingroup Application
|
||||
//! \~\brief
|
||||
//! \~english Translation support
|
||||
//! \~russian Поддержка перевода
|
||||
//! \~\details
|
||||
//! \~english Provides translation support with context-aware string wrappers and multiple loading methods.
|
||||
//! %PITranslator stores loaded translations in a process-wide singleton.
|
||||
//! If translation or context is missing, the source string is returned unchanged.
|
||||
//! \~russian Предоставляет поддержку перевода с контекстно-зависимыми обертками строк и методами загрузки.
|
||||
//! %PITranslator хранит загруженные переводы в синглтоне процесса.
|
||||
//! Если перевод или контекст не найдены, исходная строка возвращается без изменений.
|
||||
class PIP_EXPORT PITranslator {
|
||||
public:
|
||||
//! \~english Returns translated string for "in" in optional "context".
|
||||
//! \~russian Возвращает перевод строки "in" в необязательном "context".
|
||||
static PIString tr(const PIString & in, const PIString & context = {});
|
||||
|
||||
//! \~english Converts UTF-8 string literal to %PIString and translates it.
|
||||
//! \~russian Преобразует UTF-8 строковый литерал в %PIString и переводит его.
|
||||
static PIString tr(const char * in, const PIString & context = {}) { return tr(PIString::fromUTF8(in), context); }
|
||||
|
||||
//! \~english Marks string for translation-aware code paths and returns it unchanged.
|
||||
//! \~russian Помечает строку для кода, работающего с переводом, и возвращает ее без изменений.
|
||||
static PIString trNoOp(const PIString & in, const PIString & context = {}) { return in; }
|
||||
|
||||
//! \~english UTF-8 overload of \a trNoOp().
|
||||
//! \~russian UTF-8 перегрузка для \a trNoOp().
|
||||
static PIString trNoOp(const char * in, const PIString & context = {}) { return trNoOp(PIString::fromUTF8(in), context); }
|
||||
|
||||
//! \~english Clears all loaded translations.
|
||||
//! \~russian Очищает все загруженные переводы.
|
||||
static void clear();
|
||||
|
||||
//! \~english Clears current translations and loads language files matching "short_lang" from "dir".
|
||||
//! \~russian Очищает текущие переводы и загружает языковые файлы, соответствующие "short_lang", из "dir".
|
||||
static void loadLang(const PIString & short_lang, PIString dir = {});
|
||||
|
||||
//! \~english Loads translations from textual configuration content.
|
||||
//! \~russian Загружает переводы из текстового конфигурационного содержимого.
|
||||
static void loadConfig(const PIString & content);
|
||||
|
||||
//! \~english Loads translations from binary content in PIP translation format.
|
||||
//! \~russian Загружает переводы из бинарного содержимого в формате переводов PIP.
|
||||
static bool load(const PIByteArray & content);
|
||||
|
||||
//! \~english Loads translations from file and checks its translation header.
|
||||
//! \~russian Загружает переводы из файла и проверяет его заголовок переводов.
|
||||
static bool loadFile(const PIString & path);
|
||||
|
||||
private:
|
||||
@@ -59,10 +108,24 @@ private:
|
||||
};
|
||||
|
||||
|
||||
//! \~\ingroup Application
|
||||
//! \~\brief
|
||||
//! \~english Context-aware string wrapper that automatically translates strings using PITranslator::tr().
|
||||
//! Helper returned by \a operator""_tr for optional-context translation.
|
||||
//! \~russian Контекстно-зависимая обертка строки, автоматически переводящая строки с помощью PITranslator::tr().
|
||||
//! Вспомогательный тип, возвращаемый \a operator""_tr для перевода с необязательным контекстом.
|
||||
class PIStringContextTr {
|
||||
public:
|
||||
//! \~english Stores source string for later translation.
|
||||
//! \~russian Сохраняет исходную строку для последующего перевода.
|
||||
PIStringContextTr(PIString && s): _s(s) {}
|
||||
|
||||
//! \~english Translates stored string without explicit context.
|
||||
//! \~russian Переводит сохраненную строку без явного контекста.
|
||||
operator PIString() const { return PITranslator::tr(_s); }
|
||||
|
||||
//! \~english Translates stored string in context "ctx".
|
||||
//! \~russian Переводит сохраненную строку в контексте "ctx".
|
||||
PIString operator()(const PIString & ctx = {}) const { return PITranslator::tr(_s, ctx); }
|
||||
|
||||
private:
|
||||
@@ -70,10 +133,24 @@ private:
|
||||
};
|
||||
|
||||
|
||||
//! \~\ingroup Application
|
||||
//! \~\brief
|
||||
//! \~english Context-aware string wrapper that preserves original strings without translation (no-op).
|
||||
//! Helper returned by \a operator""_trNoOp that keeps source text unchanged.
|
||||
//! \~russian Контекстно-зависимая обертка строки, сохраняющая оригинальные строки без перевода (заглушка).
|
||||
//! Вспомогательный тип, возвращаемый \a operator""_trNoOp, который сохраняет исходный текст без изменений.
|
||||
class PIStringContextTrNoOp {
|
||||
public:
|
||||
//! \~english Stores source string without translating it.
|
||||
//! \~russian Сохраняет исходную строку без перевода.
|
||||
PIStringContextTrNoOp(PIString && s): _s(s) {}
|
||||
|
||||
//! \~english Returns stored string unchanged.
|
||||
//! \~russian Возвращает сохраненную строку без изменений.
|
||||
operator PIString() const { return _s; }
|
||||
|
||||
//! \~english Returns stored string unchanged and ignores "ctx".
|
||||
//! \~russian Возвращает сохраненную строку без изменений и игнорирует "ctx".
|
||||
PIString operator()(const PIString & ctx = {}) const { return _s; }
|
||||
|
||||
private:
|
||||
@@ -82,15 +159,17 @@ private:
|
||||
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Translate string with \a PITranslator::tr()
|
||||
//! \~russian Перевести строку с помощью \a PITranslator::tr()
|
||||
//! \~english User-defined literal that defers translation through \a PITranslator::tr().
|
||||
//! \~russian Пользовательский литерал, откладывающий перевод через \a PITranslator::tr().
|
||||
//! \~\code "hello"_tr \endcode
|
||||
inline PIStringContextTr operator""_tr(const char * v, size_t sz) {
|
||||
return PIStringContextTr(PIString::fromUTF8(v, sz));
|
||||
}
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Translate string with \a PITranslator::tr()
|
||||
//! \~russian Перевести строку с помощью \a PITranslator::tr()
|
||||
//! \~english User-defined literal that keeps source text unchanged via \a PITranslator::trNoOp().
|
||||
//! \~russian Пользовательский литерал, сохраняющий исходный текст без изменений через \a PITranslator::trNoOp().
|
||||
//! \~\code "hello"_trNoOp \endcode
|
||||
inline PIStringContextTrNoOp operator""_trNoOp(const char * v, size_t sz) {
|
||||
return PIStringContextTrNoOp(PIString::fromUTF8(v, sz));
|
||||
}
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/*! \file piclientserver_client.h
|
||||
* \ingroup ClientServer
|
||||
* \~\brief
|
||||
* \~english
|
||||
* \~russian
|
||||
*/
|
||||
//! \~\file piclientserver_client.h
|
||||
//! \~\ingroup ClientServer
|
||||
//! \brief
|
||||
//! \~english Client-side and server-side client connection classes
|
||||
//! \~russian Классы клиентского подключения и серверного представления клиента
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Ivan Pelipenko peri4ko@yandex.ru
|
||||
@@ -33,18 +32,27 @@ namespace PIClientServer {
|
||||
|
||||
// ServerClient
|
||||
|
||||
//! ~english Server-side client implementation
|
||||
//! ~russian Серверная реализация клиента
|
||||
//! \~\ingroup ClientServer
|
||||
//! \~\brief
|
||||
//! \~english Server-side representation of one accepted client connection.
|
||||
//! \~russian Серверное представление одного принятого клиентского соединения.
|
||||
//! \details
|
||||
//! \~english Server-side client representation. Created and managed by Server. Used to communicate with remote clients connected to the
|
||||
//! server.
|
||||
//! \~russian Представление клиента на стороне сервера. Создаётся и управляется сервером. Используется для коммуникации с удалёнными
|
||||
//! клиентами, подключёнными к серверу.
|
||||
class PIP_CLIENT_SERVER_EXPORT ServerClient: public ClientBase {
|
||||
friend class Server;
|
||||
NO_COPY_CLASS(ServerClient);
|
||||
|
||||
public:
|
||||
//! \~english Constructs an unbound server-side client object.
|
||||
//! \~russian Создает непривязанный объект серверного клиента.
|
||||
ServerClient() {}
|
||||
|
||||
protected:
|
||||
//! ~english Called before client destruction
|
||||
//! ~russian Вызывается перед уничтожением клиента
|
||||
//! \~english Called right before the server deletes this client object.
|
||||
//! \~russian Вызывается непосредственно перед удалением этого объекта сервером.
|
||||
virtual void aboutDelete() {}
|
||||
|
||||
private:
|
||||
@@ -54,17 +62,28 @@ private:
|
||||
|
||||
// Client
|
||||
|
||||
//! ~english Client implementation for connecting to servers
|
||||
//! ~russian Клиентская реализация для подключения к серверам
|
||||
//! \~\ingroup ClientServer
|
||||
//! \~\brief
|
||||
//! \~english Active client connection that initiates a connection to a server.
|
||||
//! \~russian Активное клиентское соединение, которое само подключается к серверу.
|
||||
//! \details
|
||||
//! \~english Client implementation for connecting to servers. Provides TCP connection to remote server with diagnostics and packet
|
||||
//! streaming support.
|
||||
//! \~russian Реализация клиента для подключения к серверам. Обеспечивает TCP-соединение с удалённым сервером с поддержкой диагностики и
|
||||
//! потоковой передачи пакетов.
|
||||
class PIP_CLIENT_SERVER_EXPORT Client: public ClientBase {
|
||||
NO_COPY_CLASS(Client);
|
||||
|
||||
public:
|
||||
//! \~english Constructs a client ready to connect to a remote server.
|
||||
//! \~russian Создает клиент, готовый к подключению к удаленному серверу.
|
||||
Client();
|
||||
//! \~english Destroys the client and closes its connection if needed.
|
||||
//! \~russian Уничтожает клиента и при необходимости закрывает его соединение.
|
||||
~Client();
|
||||
|
||||
//! ~english Connects to specified server address
|
||||
//! ~russian Подключается к указанному адресу сервера
|
||||
//! \~english Connects to the server at address "addr".
|
||||
//! \~russian Подключается к серверу по адресу "addr".
|
||||
void connect(PINetworkAddress addr);
|
||||
|
||||
protected:
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
/*! \file piclientserver_client_base.h
|
||||
* \ingroup ClientServer
|
||||
* \~\brief
|
||||
* \~english
|
||||
* \~russian
|
||||
*/
|
||||
//! \~\file piclientserver_client_base.h
|
||||
//! \~\ingroup ClientServer
|
||||
//! \brief
|
||||
//! \~english Base class for client-server communication
|
||||
//! \~russian Базовый класс для клиент-серверного взаимодействия
|
||||
//! \details
|
||||
//! \~english Provides base functionality for client-server communication with diagnostics support.
|
||||
//! \~russian Обеспечивает базовую функциональность для клиент-серверного взаимодействия с поддержкой диагностики.
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Ivan Pelipenko peri4ko@yandex.ru
|
||||
@@ -35,77 +37,93 @@ namespace PIClientServer {
|
||||
|
||||
class Server;
|
||||
|
||||
class ClientInterface {};
|
||||
|
||||
//! ~english Base class for client-server communication with diagnostics support
|
||||
//! ~russian Базовый класс для клиент-серверного взаимодействия с поддержкой диагностики
|
||||
//! \~\ingroup ClientServer
|
||||
//! \~\brief
|
||||
//! \~english Base class for client and server-side client communication. Provides TCP connection management, diagnostics, and packet
|
||||
//! streaming capabilities.
|
||||
//! \~russian Базовый класс для клиентской и серверной коммуникации. Обеспечивает управление TCP-соединением, диагностику и потоковую
|
||||
//! передачу пакетов.
|
||||
// template<bool EnableDiagnostics = false>
|
||||
class PIP_CLIENT_SERVER_EXPORT ClientBase {
|
||||
friend class Server;
|
||||
NO_COPY_CLASS(ClientBase);
|
||||
|
||||
public:
|
||||
//! \~english Constructs a disconnected client connection object.
|
||||
//! \~russian Создает объект клиентского соединения в отключенном состоянии.
|
||||
ClientBase();
|
||||
|
||||
//! \~english Destroys the client connection and releases owned resources.
|
||||
//! \~russian Уничтожает клиентское соединение и освобождает связанные ресурсы.
|
||||
virtual ~ClientBase();
|
||||
|
||||
//! ~english Gets underlying TCP connection
|
||||
//! ~russian Возвращает TCP-соединение
|
||||
|
||||
//! \~english Returns the underlying TCP transport object.
|
||||
//! \~russian Возвращает базовый объект TCP-транспорта.
|
||||
const PIEthernet * getTCP() const { return tcp; }
|
||||
|
||||
//! ~english Closes the connection
|
||||
//! ~russian Закрывает соединение
|
||||
//! \~english Closes the connection immediately.
|
||||
//! \~russian Немедленно закрывает соединение.
|
||||
void close();
|
||||
|
||||
//! ~english Gracefully stops and waits for completion
|
||||
//! ~russian Плавно останавливает и ожидает завершения
|
||||
//! \~english Stops the connection workflow and waits until shutdown completes.
|
||||
//! \~russian Останавливает работу соединения и ждет полного завершения.
|
||||
void stopAndWait();
|
||||
|
||||
|
||||
//! ~english Writes byte array to the connection
|
||||
//! ~russian Записывает массив байтов в соединение
|
||||
//! \~english Sends raw payload bytes through the stream packer.
|
||||
//! \~russian Отправляет сырые байты полезной нагрузки через упаковщик потока.
|
||||
int write(const void * d, const size_t s);
|
||||
|
||||
//! ~english Writes byte array to the connection
|
||||
//! ~russian Записывает массив байтов в соединение
|
||||
//! \~english Sends payload stored in "ba".
|
||||
//! \~russian Отправляет полезную нагрузку из "ba".
|
||||
int write(const PIByteArray & ba) { return write(ba.data(), ba.size()); }
|
||||
|
||||
|
||||
//! ~english Enables diagnostics collection
|
||||
//! ~russian Включает сбор диагностики
|
||||
//! \~english Enables connection diagnostics collection.
|
||||
//! \~russian Включает сбор диагностики соединения.
|
||||
void enableDiagnostics();
|
||||
|
||||
//! ~english Gets current diagnostics state
|
||||
//! ~russian Возвращает текущее состояние диагностики
|
||||
//! \~english Returns a snapshot of current diagnostics counters.
|
||||
//! \~russian Возвращает снимок текущих диагностических счетчиков.
|
||||
PIDiagnostics::State diagnostics() const;
|
||||
|
||||
|
||||
//! ~english Gets current received packet bytes already received (all bytes count passed in \a receivePacketStart())
|
||||
//! ~russian Возвращает сколько байт принимаемого пакета получено (общее количество передается в \a receivePacketStart())
|
||||
//! \~english Returns how many payload bytes of the current packet are already received (all bytes count passed in \a receivePacketStart()).
|
||||
//! \~russian Возвращает, сколько байтов полезной нагрузки текущего пакета уже получено (общее количество передается в \a receivePacketStart()).
|
||||
int receivePacketProgress() const;
|
||||
|
||||
//! \~english Returns the current packet framing configuration.
|
||||
//! \~russian Возвращает текущую конфигурацию пакетирования.
|
||||
const PIStreamPackerConfig & configuration() const { return stream.configuration(); }
|
||||
|
||||
//! \~english Returns the current packet framing configuration for modification.
|
||||
//! \~russian Возвращает текущую конфигурацию пакетирования для изменения.
|
||||
PIStreamPackerConfig & configuration() { return stream.configuration(); }
|
||||
|
||||
//! \~english Replaces the packet framing configuration.
|
||||
//! \~russian Заменяет конфигурацию пакетирования.
|
||||
void setConfiguration(const PIStreamPackerConfig & config) { stream.setConfiguration(config); }
|
||||
|
||||
protected:
|
||||
//! ~english Called when data is received
|
||||
//! ~russian Вызывается при получении данных
|
||||
//! \~english Called when a full payload packet is received.
|
||||
//! \~russian Вызывается при получении полного пакета полезной нагрузки.
|
||||
virtual void readed(PIByteArray data) {}
|
||||
|
||||
//! ~english Called when connection is established
|
||||
//! ~russian Вызывается при установке соединения
|
||||
//! \~english Called after the TCP connection becomes active.
|
||||
//! \~russian Вызывается после перехода TCP-соединения в активное состояние.
|
||||
virtual void connected() {}
|
||||
|
||||
//! ~english Called when connection is closed
|
||||
//! ~russian Вызывается при закрытии соединения
|
||||
//! \~english Called after the connection is closed.
|
||||
//! \~russian Вызывается после закрытия соединения.
|
||||
virtual void disconnected() {}
|
||||
|
||||
//! ~english Called when packet receiving starts
|
||||
//! ~russian Вызывается при начале получения пакета
|
||||
//! \~english Called when reception of a new packet starts.
|
||||
//! \~russian Вызывается при начале приема нового пакета.
|
||||
virtual void receivePacketStart(int size) {}
|
||||
|
||||
//! ~english Called when packet receiving ends
|
||||
//! ~russian Вызывается при завершении получения пакета
|
||||
//! \~english Called when reception of the current packet finishes.
|
||||
//! \~russian Вызывается при завершении приема текущего пакета.
|
||||
virtual void receivePacketEnd() {}
|
||||
|
||||
void init();
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/*! \file piclientserver_server.h
|
||||
* \ingroup ClientServer
|
||||
* \~\brief
|
||||
* \~english
|
||||
* \~russian
|
||||
*/
|
||||
//! \~\file piclientserver_server.h
|
||||
//! \~\ingroup ClientServer
|
||||
//! \brief
|
||||
//! \~english TCP Server
|
||||
//! \~russian TCP Сервер
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Ivan Pelipenko peri4ko@yandex.ru
|
||||
@@ -38,55 +37,73 @@ namespace PIClientServer {
|
||||
|
||||
class ServerClient;
|
||||
|
||||
//! ~english TCP server for client-server communication
|
||||
//! ~russian TCP сервер для клиент-серверного взаимодействия
|
||||
//! \~\ingroup ClientServer
|
||||
//! \~\brief
|
||||
//! \~english TCP server implementation for client-server communication. Accepts incoming connections and manages multiple clients with
|
||||
//! configurable factory for client instance creation.
|
||||
//! \~russian Реализация TCP сервера для клиент-серверного взаимодействия. Принимает входящие соединения и управляет несколькими клиентами с
|
||||
//! настраиваемой фабрикой для создания экземпляров клиентов.
|
||||
class PIP_CLIENT_SERVER_EXPORT Server: public PIStreamPackerConfig {
|
||||
friend class ServerClient;
|
||||
NO_COPY_CLASS(Server);
|
||||
|
||||
public:
|
||||
//! \~english Constructs a stopped server with default limits.
|
||||
//! \~russian Создает остановленный сервер с ограничениями по умолчанию.
|
||||
Server();
|
||||
|
||||
//! \~english Stops the server and releases transport resources.
|
||||
//! \~russian Останавливает сервер и освобождает транспортные ресурсы.
|
||||
virtual ~Server();
|
||||
|
||||
//! ~english Starts listening on specified address
|
||||
//! ~russian Начинает прослушивание на указанном адресе
|
||||
//! \~english Starts listening for clients on address "addr".
|
||||
//! \~russian Начинает принимать клиентов по адресу "addr".
|
||||
void listen(PINetworkAddress addr);
|
||||
|
||||
//! ~english Starts listening on all interfaces
|
||||
//! ~russian Начинает прослушивание на всех интерфейсах
|
||||
//! \~english Starts listening on all interfaces at port "port".
|
||||
//! \~russian Начинает прослушивание на всех интерфейсах на порту "port".
|
||||
//! \~\details
|
||||
//! \~english Equivalent to listen({0, port}), binds to all available network interfaces.
|
||||
//! \~russian Эквивалентно listen({0, port}), привязывается ко всем доступным сетевым интерфейсам.
|
||||
void listenAll(ushort port) { listen({0, port}); }
|
||||
|
||||
|
||||
//! ~english Stops the server
|
||||
//! ~russian Останавливает сервер
|
||||
//! \~english Stops accepting clients and shuts the server down.
|
||||
//! \~russian Прекращает прием клиентов и завершает работу сервера.
|
||||
void stopServer();
|
||||
|
||||
//! ~english Closes all client connections
|
||||
//! ~russian Закрывает все клиентские соединения
|
||||
//! \~english Closes all currently connected clients.
|
||||
//! \~russian Закрывает все текущие клиентские соединения.
|
||||
//! \~\details
|
||||
//! \~english Immediately closes all active client connections without stopping the server.
|
||||
//! \~russian Немедленно закрывает все активные клиентские соединения без остановки сервера.
|
||||
void closeAll();
|
||||
|
||||
|
||||
//! ~english Gets maximum allowed clients
|
||||
//! ~russian Возвращает максимальное число клиентов
|
||||
//! \~english Returns the configured maximum number of simultaneous clients.
|
||||
//! \~russian Возвращает настроенный максимум одновременных клиентов.
|
||||
int getMaxClients() const { return max_clients; }
|
||||
|
||||
//! ~english Sets maximum allowed clients
|
||||
//! ~russian Устанавливает максимальное число клиентов
|
||||
//! \~english Sets the maximum number of simultaneous clients.
|
||||
//! \~russian Устанавливает максимальное число одновременных клиентов.
|
||||
//! \~\details
|
||||
//! \~english Sets the maximum number of concurrent client connections. Default is 1000.
|
||||
//! \~russian Устанавливает максимальное количество одновременных клиентских подключений. По умолчанию 1000.
|
||||
void setMaxClients(int new_max_clients);
|
||||
|
||||
//! ~english Gets current clients count
|
||||
//! ~russian Возвращает текущее количество клиентов
|
||||
//! \~english Returns the number of currently connected clients.
|
||||
//! \~russian Возвращает текущее количество подключенных клиентов.
|
||||
int clientsCount() const;
|
||||
|
||||
|
||||
//! ~english Executes function for each connected client
|
||||
//! ~russian Выполняет функцию для каждого подключённого клиента
|
||||
//! \~english Calls "func" for each currently connected client.
|
||||
//! \~russian Вызывает "func" для каждого текущего подключенного клиента.
|
||||
void forEachClient(std::function<void(ServerClient *)> func);
|
||||
|
||||
|
||||
//! ~english Sets factory for creating new client instances
|
||||
//! ~russian Устанавливает фабрику для создания клиентских экземпляров
|
||||
void setClientFactory(std::function<ServerClient *()> f) { client_factory = f; }
|
||||
//! \~english Sets the factory used to create accepted client objects.
|
||||
//! \~russian Устанавливает фабрику, создающую объекты принятых клиентов.
|
||||
void setClientFactory(std::function<ServerClient *()> f) { client_factory = std::move(f); }
|
||||
|
||||
private:
|
||||
void newClient(ServerClient * c);
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
//! \~\file piclientservermodule.h
|
||||
//! \~\ingroup ClientServer
|
||||
//! \~\brief
|
||||
//! \~english Umbrella header and module group for TCP client-server helpers
|
||||
//! \~russian Общий заголовок и группа модуля для TCP-клиент-серверных компонентов
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Module includes
|
||||
@@ -34,10 +39,10 @@
|
||||
//! \~russian \par Общее
|
||||
//!
|
||||
//! \~english
|
||||
//! These files provides server with clients dispatching for server-side and client for client-side.
|
||||
//! These headers provide a TCP server with server-side client objects and an active client for remote connections.
|
||||
//!
|
||||
//! \~russian
|
||||
//! Эти файлы предоставляют сервер с диспетчеризацией клиентов для серверной стороны и клиента для клиентской стороны.
|
||||
//! Эти заголовки предоставляют TCP-сервер с серверными объектами клиентов и активного клиента для удаленных подключений.
|
||||
//!
|
||||
//! \~\authors
|
||||
//! \~english
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/*! \file picloudbase.h
|
||||
* \ingroup Cloud
|
||||
* \~\brief
|
||||
* \~english Base class for PICloudClient and PICloudServer
|
||||
* \~russian Базовый класс для PICloudClient и PICloudServer
|
||||
*/
|
||||
//! \~\file picloudbase.h
|
||||
//! \~\ingroup Cloud
|
||||
//! \brief
|
||||
//! \~english Base class for PICloudClient and PICloudServer.
|
||||
//! \~russian Базовый класс для PICloudClient и PICloudServer.
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
PICloud Base - Base class for PICloudClient and PICloud Server
|
||||
@@ -30,11 +29,18 @@
|
||||
#include "piethernet.h"
|
||||
#include "pistreampacker.h"
|
||||
|
||||
|
||||
//! \~\ingroup Cloud
|
||||
//! \brief
|
||||
//! \~english Base class for cloud client and server.
|
||||
//! \~russian Базовый класс для облачного клиента и сервера.
|
||||
class PIP_CLOUD_EXPORT PICloudBase {
|
||||
public:
|
||||
//! \~english Constructs the shared PICloud transport state.
|
||||
//! \~russian Создает общее транспортное состояние PICloud.
|
||||
PICloudBase();
|
||||
|
||||
//! \~english Returns the logical server name configured for the transport.
|
||||
//! \~russian Возвращает логическое имя сервера, настроенное для транспорта.
|
||||
PIString serverName() const;
|
||||
|
||||
protected:
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/*! \file picloudclient.h
|
||||
* \ingroup Cloud
|
||||
* \~\brief
|
||||
* \~english PICloud Client
|
||||
* \~russian Клиент PICloud
|
||||
*/
|
||||
//! \~\file picloudclient.h
|
||||
//! \~\ingroup Cloud
|
||||
//! \~\brief
|
||||
//! \~english Client-side PICloud device for one named server
|
||||
//! \~russian Клиентское устройство PICloud для одного именованного сервера
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
PICloud Client
|
||||
@@ -29,27 +28,61 @@
|
||||
#include "picloudbase.h"
|
||||
#include "piconditionvar.h"
|
||||
|
||||
|
||||
//! \brief PICloudClient
|
||||
|
||||
//! \~\ingroup Cloud
|
||||
//! \~\brief
|
||||
//! \~english %PIIODevice implementation for a logical PICloud client.
|
||||
//! \~russian Реализация %PIIODevice для логического клиента PICloud.
|
||||
class PIP_CLOUD_EXPORT PICloudClient
|
||||
: public PIIODevice
|
||||
, public PICloudBase {
|
||||
PIIODEVICE(PICloudClient, "");
|
||||
|
||||
public:
|
||||
//! \~english Constructs a client for transport endpoint "path" and mode "mode".
|
||||
//! \~russian Создает клиент для транспортной точки "path" и режима "mode".
|
||||
explicit PICloudClient(const PIString & path = PIString(), PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||
|
||||
//! \~english Destroys the client and closes the underlying transport.
|
||||
//! \~russian Уничтожает клиент и закрывает нижележащий транспорт.
|
||||
virtual ~PICloudClient();
|
||||
|
||||
|
||||
//! \~english Sets the logical server name used during the PICloud handshake.
|
||||
//! \~russian Устанавливает логическое имя сервера, используемое при рукопожатии PICloud.
|
||||
void setServerName(const PIString & server_name);
|
||||
|
||||
//! \~english Enables or disables automatic reconnect of the underlying TCP link.
|
||||
//! \~russian Включает или выключает автоматическое переподключение нижележащего TCP-соединения.
|
||||
void setKeepConnection(bool on);
|
||||
|
||||
//! \~english Returns whether the logical PICloud session is established.
|
||||
//! \~russian Возвращает, установлена ли логическая сессия PICloud.
|
||||
bool isConnected() const { return is_connected; }
|
||||
|
||||
//! \~english Returns the number of payload bytes buffered for \a read().
|
||||
//! \~russian Возвращает количество байтов полезной нагрузки, буферизованных для \a read().
|
||||
ssize_t bytesAvailable() const override { return buff.size(); }
|
||||
|
||||
//! \~english Interrupts pending connection and read waits.
|
||||
//! \~russian Прерывает ожидающие операции подключения и чтения.
|
||||
void interrupt() override;
|
||||
|
||||
|
||||
//! \events
|
||||
//! \{
|
||||
|
||||
//! \fn void connected()
|
||||
//! \~english Raised after the logical PICloud session becomes ready.
|
||||
//! \~russian Вызывается после того, как логическая сессия PICloud готова к работе.
|
||||
EVENT(connected);
|
||||
|
||||
//! \fn void disconnected()
|
||||
//! \~english Raised when the logical PICloud session is closed.
|
||||
//! \~russian Вызывается при закрытии логической сессии PICloud.
|
||||
EVENT(disconnected);
|
||||
|
||||
//! \}
|
||||
|
||||
protected:
|
||||
bool openDevice() override;
|
||||
bool closeDevice() override;
|
||||
|
||||
@@ -1,3 +1,13 @@
|
||||
/*! \file picloudmodule.h
|
||||
* \ingroup Cloud
|
||||
* \~\brief
|
||||
* \~english Umbrella header for the PICloud module
|
||||
* \~russian Зонтичный заголовок модуля PICloud
|
||||
*
|
||||
* \~\details
|
||||
* \~english Includes the public client, server, and low-level transport helpers of the module.
|
||||
* \~russian Подключает публичные клиентские, серверные и низкоуровневые транспортные помощники модуля.
|
||||
*/
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Module includes
|
||||
@@ -18,8 +28,8 @@
|
||||
*/
|
||||
//! \defgroup Cloud Cloud
|
||||
//! \~\brief
|
||||
//! \~english Cloud transport over ethernet
|
||||
//! \~russian Облачный транспорт через ethernet
|
||||
//! \~english Named cloud endpoints over an ethernet transport
|
||||
//! \~russian Именованные облачные конечные точки поверх Ethernet-транспорта
|
||||
//!
|
||||
//! \~\details
|
||||
//! \~english \section cmake_module_Cloud Building with CMake
|
||||
@@ -34,10 +44,10 @@
|
||||
//! \~russian \par Общее
|
||||
//!
|
||||
//! \~english
|
||||
//! These files provides server-side and client-side of PICloud transport.
|
||||
//! Includes logical client and server devices together with low-level PICloud framing helpers.
|
||||
//!
|
||||
//! \~russian
|
||||
//! Эти файлы обеспечивают серверную и клиентскую сторону транспорта PICloud.
|
||||
//! Подключает логические клиентские и серверные устройства вместе с низкоуровневыми помощниками кадрирования PICloud.
|
||||
//!
|
||||
//! \~\authors
|
||||
//! \~english
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/*! \file picloudserver.h
|
||||
* \ingroup Cloud
|
||||
* \~\brief
|
||||
* \~english PICloud Server
|
||||
* \~russian Сервер PICloud
|
||||
*/
|
||||
//! \~\file picloudserver.h
|
||||
//! \~\ingroup Cloud
|
||||
//! \~\brief
|
||||
//! \~english Server-side PICloud device for one named endpoint
|
||||
//! \~russian Серверное устройство PICloud для одной именованной конечной точки
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
PICloud Server
|
||||
@@ -29,23 +28,43 @@
|
||||
#include "picloudbase.h"
|
||||
#include "piconditionvar.h"
|
||||
|
||||
|
||||
//! \~\ingroup Cloud
|
||||
//! \~\brief
|
||||
//! \~english %PIIODevice implementation for a logical PICloud server.
|
||||
//! \~russian Реализация %PIIODevice для логического сервера PICloud.
|
||||
class PIP_CLOUD_EXPORT PICloudServer
|
||||
: public PIIODevice
|
||||
, public PICloudBase {
|
||||
PIIODEVICE(PICloudServer, "");
|
||||
|
||||
public:
|
||||
//! PICloudServer
|
||||
//! \~english Constructs a logical server for transport endpoint "path" and mode "mode".
|
||||
//! \~russian Создает логический сервер для транспортной точки "path" и режима "mode".
|
||||
explicit PICloudServer(const PIString & path = PIString(), PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||
|
||||
//! \~english Destroys the server and closes all logical clients.
|
||||
//! \~russian Уничтожает сервер и закрывает всех логических клиентов.
|
||||
virtual ~PICloudServer();
|
||||
|
||||
|
||||
//! \~\ingroup Cloud
|
||||
//! \~\brief
|
||||
//! \~english Per-client %PIIODevice exposed by %PICloudServer.
|
||||
//! \~russian Клиентское %PIIODevice, предоставляемое %PICloudServer.
|
||||
//! \~\details
|
||||
//! \~english Instances are created by \a newConnection() and represent one logical cloud client.
|
||||
//! \~russian Экземпляры создаются через \a newConnection() и представляют одного логического облачного клиента.
|
||||
class Client: public PIIODevice {
|
||||
PIIODEVICE(PICloudServer::Client, "");
|
||||
friend class PICloudServer;
|
||||
|
||||
public:
|
||||
//! \~english Constructs a wrapper for logical client "id" owned by server "srv".
|
||||
//! \~russian Создает обертку для логического клиента "id", принадлежащего серверу "srv".
|
||||
Client(PICloudServer * srv = nullptr, uint id = 0);
|
||||
|
||||
//! \~english Destroys the client wrapper.
|
||||
//! \~russian Уничтожает клиентскую обертку.
|
||||
virtual ~Client();
|
||||
|
||||
protected:
|
||||
@@ -67,12 +86,25 @@ public:
|
||||
std::atomic_bool is_connected;
|
||||
};
|
||||
|
||||
//! \~english Sets the logical server name announced by this server.
|
||||
//! \~russian Устанавливает логическое имя сервера, объявляемое этим сервером.
|
||||
void setServerName(const PIString & server_name);
|
||||
|
||||
//! \~english Returns a snapshot of the currently connected logical clients.
|
||||
//! \~russian Возвращает снимок текущих подключенных логических клиентов.
|
||||
PIVector<PICloudServer::Client *> clients() const;
|
||||
|
||||
|
||||
//! \events
|
||||
//! \{
|
||||
|
||||
//! \fn void newConnection(PICloudServer::Client * client)
|
||||
//! \~english Raised when a new logical client appears for this server name.
|
||||
//! \~russian Вызывается, когда для этого имени сервера появляется новый логический клиент.
|
||||
EVENT1(newConnection, PICloudServer::Client *, client);
|
||||
|
||||
//! \}
|
||||
|
||||
protected:
|
||||
bool openDevice() override;
|
||||
bool closeDevice() override;
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
/*! \file picloudtcp.h
|
||||
* \ingroup Cloud
|
||||
* \~\brief
|
||||
* \~english PICloud TCP transport
|
||||
* \~russian TCP слой PICloud
|
||||
*/
|
||||
//! \~\file picloudtcp.h
|
||||
//! \~\ingroup Cloud
|
||||
//! \~\brief
|
||||
//! \~english Low-level TCP framing helpers for PICloud
|
||||
//! \~russian Низкоуровневые помощники TCP-кадрирования для PICloud
|
||||
//!
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
PICloud TCP transport
|
||||
@@ -31,50 +31,113 @@
|
||||
#include "pistring.h"
|
||||
|
||||
|
||||
class PIEthernet;
|
||||
class PIStreamPacker;
|
||||
|
||||
//! \~\ingroup Cloud
|
||||
//! \~english Namespace for low-level PICloud transport helpers.
|
||||
//! \~russian Пространство имен для низкоуровневых транспортных помощников PICloud.
|
||||
namespace PICloud {
|
||||
|
||||
|
||||
//! \~\ingroup Cloud
|
||||
//! \~\brief
|
||||
//! \~english Builds and parses PICloud frames on top of %PIStreamPacker.
|
||||
//! \~russian Формирует и разбирает кадры PICloud поверх %PIStreamPacker.
|
||||
class PIP_CLOUD_EXPORT TCP {
|
||||
public:
|
||||
//! \~english Supported PICloud frame versions.
|
||||
//! \~russian Поддерживаемые версии кадров PICloud.
|
||||
enum Version {
|
||||
Version_1 = 1,
|
||||
Version_2 = 2,
|
||||
Version_1 = 1 /** \~english First protocol version \~russian Первая версия протокола */,
|
||||
Version_2 = 2 /** \~english Current protocol version \~russian Текущая версия протокола */
|
||||
};
|
||||
|
||||
//! \~english Logical destination role of a PICloud frame.
|
||||
//! \~russian Логическая роль получателя кадра PICloud.
|
||||
enum Role {
|
||||
InvalidRole = 0,
|
||||
Server = 1,
|
||||
Client = 2,
|
||||
InvalidRole = 0 /** \~english Invalid or unknown role \~russian Некорректная или неизвестная роль */,
|
||||
Server = 1 /** \~english Frame for a logical server \~russian Кадр для логического сервера */,
|
||||
Client = 2 /** \~english Frame for a logical client \~russian Кадр для логического клиента */
|
||||
};
|
||||
|
||||
//! \~english Kind of PICloud frame payload.
|
||||
//! \~russian Вид полезной нагрузки кадра PICloud.
|
||||
enum Type {
|
||||
InvalidType = 0,
|
||||
Connect = 1,
|
||||
Disconnect = 2,
|
||||
Data = 3,
|
||||
Ping = 4,
|
||||
InvalidType = 0 /** \~english Invalid or unknown frame \~russian Некорректный или неизвестный кадр */,
|
||||
Connect = 1 /** \~english Connect or registration frame \~russian Кадр подключения или регистрации */,
|
||||
Disconnect = 2 /** \~english Disconnect notification frame \~russian Кадр уведомления об отключении */,
|
||||
Data = 3 /** \~english Payload data frame \~russian Кадр с полезными данными */,
|
||||
Ping = 4 /** \~english Keepalive frame \~russian Кадр поддержания соединения */
|
||||
};
|
||||
|
||||
|
||||
//! \~english Constructs a PICloud frame helper bound to packer "s".
|
||||
//! \~russian Создает помощник кадров PICloud, связанный с упаковщиком "s".
|
||||
TCP(PIStreamPacker * s);
|
||||
|
||||
//! \~english Sets the logical role written into outgoing frames.
|
||||
//! \~russian Устанавливает логическую роль, записываемую в исходящие кадры.
|
||||
void setRole(Role r);
|
||||
|
||||
//! \~english Returns the logical role of this helper.
|
||||
//! \~russian Возвращает логическую роль этого помощника.
|
||||
Role role() const { return (Role)header.role; }
|
||||
|
||||
//! \~english Sets the logical server name used by connect and keepalive frames.
|
||||
//! \~russian Устанавливает логическое имя сервера, используемое кадрами подключения и поддержания соединения.
|
||||
void setServerName(const PIString & server_name_);
|
||||
|
||||
//! \~english Returns the configured logical server name.
|
||||
//! \~russian Возвращает настроенное логическое имя сервера.
|
||||
PIString serverName() const;
|
||||
|
||||
|
||||
//! \~english Sends the initial connect frame for the current server name.
|
||||
//! \~russian Отправляет начальный кадр подключения для текущего имени сервера.
|
||||
void sendStart();
|
||||
|
||||
//! \~english Sends a connect frame for logical client "client_id".
|
||||
//! \~russian Отправляет кадр подключения для логического клиента "client_id".
|
||||
void sendConnected(uint client_id);
|
||||
|
||||
//! \~english Sends a disconnect frame for logical client "client_id".
|
||||
//! \~russian Отправляет кадр отключения для логического клиента "client_id".
|
||||
void sendDisconnected(uint client_id);
|
||||
|
||||
//! \~english Sends a payload frame for the current logical role.
|
||||
//! \~russian Отправляет кадр с полезными данными для текущей логической роли.
|
||||
int sendData(const PIByteArray & data);
|
||||
|
||||
//! \~english Sends a payload frame tagged with logical client "client_id".
|
||||
//! \~russian Отправляет кадр с полезными данными, помеченный логическим клиентом "client_id".
|
||||
int sendData(const PIByteArray & data, uint client_id);
|
||||
|
||||
//! \~english Sends a keepalive frame.
|
||||
//! \~russian Отправляет кадр поддержания соединения.
|
||||
void sendPing();
|
||||
|
||||
//! \~english Parses frame header and returns its type and destination role.
|
||||
//! \~russian Разбирает заголовок кадра и возвращает его тип и роль получателя.
|
||||
PIPair<PICloud::TCP::Type, PICloud::TCP::Role> parseHeader(PIByteArray & ba);
|
||||
|
||||
//! \~english Returns whether current role uses direct payload parsing.
|
||||
//! \~russian Возвращает, использует ли текущая роль прямой разбор полезной нагрузки.
|
||||
bool canParseData(PIByteArray & ba);
|
||||
|
||||
//! \~english Extracts logical client identifier and payload from a server-side data frame.
|
||||
//! \~russian Извлекает идентификатор логического клиента и полезную нагрузку из серверного кадра данных.
|
||||
PIPair<uint, PIByteArray> parseDataServer(PIByteArray & ba);
|
||||
|
||||
//! \~english Validates and returns raw connect payload used for server identity exchange.
|
||||
//! \~russian Проверяет и возвращает сырой payload подключения, используемый при обмене идентичностью сервера.
|
||||
PIByteArray parseConnect_d(PIByteArray & ba);
|
||||
|
||||
//! \~english Extracts logical client identifier from a connect frame.
|
||||
//! \~russian Извлекает идентификатор логического клиента из кадра подключения.
|
||||
uint parseConnect(PIByteArray & ba);
|
||||
|
||||
//! \~english Extracts logical client identifier from a disconnect frame.
|
||||
//! \~russian Извлекает идентификатор логического клиента из кадра отключения.
|
||||
uint parseDisconnect(PIByteArray & ba);
|
||||
|
||||
private:
|
||||
|
||||
@@ -59,6 +59,7 @@ PICodeInfo::__Storage__::__Storage__() {
|
||||
enumsInfo = new PIMap<PIConstChars, EnumInfo *>;
|
||||
accessValueFunctions = new PIMap<PIConstChars, AccessValueFunction>;
|
||||
accessTypeFunctions = new PIMap<PIConstChars, AccessTypeFunction>;
|
||||
accessOffsetFunctions = new PIMap<PIConstChars, AccessOffsetFunction>;
|
||||
(*enumsInfo)[""] = new EnumInfo();
|
||||
}
|
||||
|
||||
@@ -70,6 +71,7 @@ PICodeInfo::__Storage__::~__Storage__() {
|
||||
piDeleteSafety(enumsInfo);
|
||||
piDeleteSafety(accessValueFunctions);
|
||||
piDeleteSafety(accessTypeFunctions);
|
||||
piDeleteSafety(accessOffsetFunctions);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
/*! \file picodeinfo.h
|
||||
* \ingroup Code
|
||||
* \~\brief
|
||||
* \~english C++ code info structs. See \ref code_model.
|
||||
* \~russian Структуры для C++ кода. Подробнее \ref code_model.
|
||||
*/
|
||||
//! \~\file picodeinfo.h
|
||||
//! \~\ingroup Code
|
||||
//! \~\brief
|
||||
//! \~english C++ code info structs. See \ref code_model.
|
||||
//! \~russian Структуры для C++ кода. Подробнее \ref code_model.
|
||||
//! \~\details
|
||||
//! \~english Contains structures for code generation and reflection: TypeInfo, FunctionInfo, ClassInfo, EnumInfo, EnumeratorInfo.
|
||||
//! \~russian Содержит структуры для кодогенерации и рефлексии: TypeInfo, FunctionInfo, ClassInfo, EnumInfo, EnumeratorInfo.
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
C++ code info structs
|
||||
@@ -36,33 +38,49 @@ class PIVariant;
|
||||
|
||||
//! \~english Namespace contains structures for code generation. See \ref code_model.
|
||||
//! \~russian Пространство имен содержит структуры для кодогенерации. Подробнее \ref code_model.
|
||||
//! \~\details
|
||||
//! \~english Provides classes and structures for code introspection, including type information, function details, class metadata, and enum
|
||||
//! information.
|
||||
//! \~russian Предоставляет классы и структуры для интроспекции кода, включая информацию о типах, детали функций, метаданные классов и
|
||||
//! информацию о перечислениях.
|
||||
namespace PICodeInfo {
|
||||
|
||||
|
||||
//! \~english
|
||||
//! Type modifiers
|
||||
//! \~russian
|
||||
//! Модификаторы типа
|
||||
//! \~english Type modifiers.
|
||||
//! \~russian Модификаторы типа.
|
||||
enum TypeFlag {
|
||||
NoFlag,
|
||||
Const /** const */ = 0x01,
|
||||
Static /** static */ = 0x02,
|
||||
Mutable /** mutable */ = 0x04,
|
||||
Volatile /** volatile */ = 0x08,
|
||||
Inline /** inline */ = 0x10,
|
||||
Virtual /** virtual */ = 0x20,
|
||||
Extern /** extern */ = 0x40
|
||||
NoFlag /** \~english No modifiers. \~russian Модификаторы отсутствуют. */,
|
||||
Const = 0x01 /** \~english \c const modifier. \~russian Модификатор \c const. */,
|
||||
Static = 0x02 /** \~english \c static modifier. \~russian Модификатор \c static. */,
|
||||
Mutable = 0x04 /** \~english \c mutable modifier. \~russian Модификатор \c mutable. */,
|
||||
Volatile = 0x08 /** \~english \c volatile modifier. \~russian Модификатор \c volatile. */,
|
||||
Inline = 0x10 /** \~english \c inline modifier. \~russian Модификатор \c inline. */,
|
||||
Virtual = 0x20 /** \~english \c virtual modifier. \~russian Модификатор \c virtual. */,
|
||||
Extern = 0x40 /** \~english \c extern modifier. \~russian Модификатор \c extern. */
|
||||
};
|
||||
|
||||
//! \~english Bitmask of type modifiers.
|
||||
//! \~russian Битовая маска модификаторов типа.
|
||||
typedef PIFlags<PICodeInfo::TypeFlag> TypeFlags;
|
||||
//! \~english Custom metadata map produced by \c PIMETA.
|
||||
//! \~russian Карта пользовательских метаданных, создаваемых \c PIMETA.
|
||||
typedef PIMap<PIString, PIString> MetaMap;
|
||||
//! \~english Callback returning serialized member data by member name.
|
||||
//! \~russian Обратный вызов, возвращающий сериализованные данные члена по имени.
|
||||
typedef PIByteArray (*AccessValueFunction)(const void *, const char *);
|
||||
//! \~english Callback returning a member type name by member name.
|
||||
//! \~russian Обратный вызов, возвращающий имя типа члена по его имени.
|
||||
typedef const char * (*AccessTypeFunction)(const char *);
|
||||
//! \~english Callback returning a member offset by member name.
|
||||
//! \~russian Обратный вызов, возвращающий смещение члена по его имени.
|
||||
typedef int (*AccessOffsetFunction)(const char *);
|
||||
|
||||
|
||||
//! \~english Type information
|
||||
//! \~russian Информация о типе
|
||||
struct PIP_EXPORT TypeInfo {
|
||||
//! \~english Constructs type information for one variable or argument.
|
||||
//! \~russian Создает описание типа для одной переменной или аргумента.
|
||||
TypeInfo(const PIConstChars & n = PIConstChars(), const PIConstChars & t = PIConstChars(), PICodeInfo::TypeFlags f = 0, int b = -1) {
|
||||
name = n;
|
||||
type = t;
|
||||
@@ -70,8 +88,8 @@ struct PIP_EXPORT TypeInfo {
|
||||
bits = b;
|
||||
}
|
||||
|
||||
//! \~english Returns if variable if bitfield
|
||||
//! \~russian Возвращает битовым ли полем является переменная
|
||||
//! \~english Returns whether the described variable is a bitfield.
|
||||
//! \~russian Возвращает, является ли описываемая переменная битовым полем.
|
||||
bool isBitfield() const { return bits > 0; }
|
||||
|
||||
//! \~english Custom PIMETA content
|
||||
@@ -108,7 +126,7 @@ struct PIP_EXPORT FunctionInfo {
|
||||
PIConstChars name;
|
||||
|
||||
//! \~english Return type
|
||||
//! \~russian Возвращаемые тип
|
||||
//! \~russian Возвращаемый тип
|
||||
TypeInfo return_type;
|
||||
|
||||
//! \~english Arguments types
|
||||
@@ -120,26 +138,28 @@ struct PIP_EXPORT FunctionInfo {
|
||||
//! \~english Class or struct information
|
||||
//! \~russian Информация о классе или структуре
|
||||
struct PIP_EXPORT ClassInfo {
|
||||
ClassInfo() { has_name = true; }
|
||||
//! \~english Constructs an empty class description.
|
||||
//! \~russian Создает пустое описание класса.
|
||||
ClassInfo() { is_anonymous = false; }
|
||||
|
||||
//! \~english Custom PIMETA content
|
||||
//! \~russian Произвольное содержимое PIMETA
|
||||
MetaMap meta;
|
||||
|
||||
//! \~english Has name or not
|
||||
//! \~russian Имеет или нет имя
|
||||
bool has_name;
|
||||
//! \~english Indicates that the type was declared without a name
|
||||
//! \~russian Показывает, что тип был объявлен без имени
|
||||
bool is_anonymous;
|
||||
|
||||
//! \~english Type
|
||||
//! \~russian Тип
|
||||
//! \~english Declaration kind, for example \c class or \c struct
|
||||
//! \~russian Вид объявления, например \c class или \c struct
|
||||
PIConstChars type;
|
||||
|
||||
//! \~english Name
|
||||
//! \~russian Имя
|
||||
PIConstChars name;
|
||||
|
||||
//! \~english Parent names
|
||||
//! \~russian Имена родителей
|
||||
//! \~english Base class names
|
||||
//! \~russian Имена базовых классов
|
||||
PIVector<PIConstChars> parents;
|
||||
|
||||
//! \~english Variables
|
||||
@@ -150,8 +170,8 @@ struct PIP_EXPORT ClassInfo {
|
||||
//! \~russian Методы
|
||||
PIVector<PICodeInfo::FunctionInfo> functions;
|
||||
|
||||
//! \~english Subclass list
|
||||
//! \~russian Список наследников
|
||||
//! \~english Registered derived class descriptions
|
||||
//! \~russian Зарегистрированные описания производных классов
|
||||
PIVector<PICodeInfo::ClassInfo *> children_info;
|
||||
};
|
||||
|
||||
@@ -159,10 +179,14 @@ struct PIP_EXPORT ClassInfo {
|
||||
//! \~english Enumerator information
|
||||
//! \~russian Информация об элементе перечисления
|
||||
struct PIP_EXPORT EnumeratorInfo {
|
||||
//! \~english Constructs one enum member description.
|
||||
//! \~russian Создает описание одного элемента перечисления.
|
||||
EnumeratorInfo(const PIConstChars & n = PIConstChars(), int v = 0) {
|
||||
name = n;
|
||||
value = v;
|
||||
}
|
||||
//! \~english Converts the enumerator to the %PIVariantTypes representation.
|
||||
//! \~russian Преобразует элемент перечисления в представление %PIVariantTypes.
|
||||
PIVariantTypes::Enumerator toPIVariantEnumerator() { return PIVariantTypes::Enumerator(value, name.toString()); }
|
||||
|
||||
//! \~english Custom PIMETA content
|
||||
@@ -182,16 +206,16 @@ struct PIP_EXPORT EnumeratorInfo {
|
||||
//! \~english Enum information
|
||||
//! \~russian Информация о перечислении
|
||||
struct PIP_EXPORT EnumInfo {
|
||||
//! \~english Returns member name with value "value"
|
||||
//! \~russian Возвращает имя элемента со значением "value"
|
||||
//! \~english Returns the member name for the value \a value.
|
||||
//! \~russian Возвращает имя элемента для значения \a value.
|
||||
PIString memberName(int value) const;
|
||||
|
||||
//! \~english Returns member value with name "name"
|
||||
//! \~russian Возвращает значение элемента с именем "name"
|
||||
//! \~english Returns the member value for the name \a name.
|
||||
//! \~russian Возвращает значение элемента для имени \a name.
|
||||
int memberValue(const PIString & name) const;
|
||||
|
||||
//! \~english Returns as PIVariantTypes::Enum
|
||||
//! \~russian Возвращает как PIVariantTypes::Enum
|
||||
//! \~english Converts the enum description to %PIVariantTypes::Enum.
|
||||
//! \~russian Преобразует описание перечисления в %PIVariantTypes::Enum.
|
||||
PIVariantTypes::Enum toPIVariantEnum();
|
||||
|
||||
//! \~english Custom PIMETA content
|
||||
@@ -208,6 +232,8 @@ struct PIP_EXPORT EnumInfo {
|
||||
};
|
||||
|
||||
|
||||
//! \~english Writes a declaration-like view of \a v to \a s.
|
||||
//! \~russian Записывает в \a s представление \a v в стиле объявления.
|
||||
inline PICout operator<<(PICout s, const PICodeInfo::TypeInfo & v) {
|
||||
if (v.flags[Inline]) s << "inline ";
|
||||
if (v.flags[Virtual]) s << "virtual ";
|
||||
@@ -220,11 +246,15 @@ inline PICout operator<<(PICout s, const PICodeInfo::TypeInfo & v) {
|
||||
return s;
|
||||
}
|
||||
|
||||
//! \~english Writes an enum member description to \a s.
|
||||
//! \~russian Записывает описание элемента перечисления в \a s.
|
||||
inline PICout operator<<(PICout s, const PICodeInfo::EnumeratorInfo & v) {
|
||||
s << v.name << " = " << v.value << " Meta" << v.meta;
|
||||
return s;
|
||||
}
|
||||
|
||||
//! \~english Writes a human-readable class description to \a s.
|
||||
//! \~russian Записывает в \a s человекочитаемое описание класса.
|
||||
inline PICout operator<<(PICout s, const PICodeInfo::ClassInfo & v) {
|
||||
s.saveAndSetControls(0);
|
||||
s << "class " << v.name;
|
||||
@@ -261,6 +291,8 @@ inline PICout operator<<(PICout s, const PICodeInfo::ClassInfo & v) {
|
||||
return s;
|
||||
}
|
||||
|
||||
//! \~english Writes a human-readable enum description to \a s.
|
||||
//! \~russian Записывает в \a s человекочитаемое описание перечисления.
|
||||
inline PICout operator<<(PICout s, const PICodeInfo::EnumInfo & v) {
|
||||
s.saveAndSetControls(0);
|
||||
s << "enum " << v.name << " Meta" << v.meta << " {\n";
|
||||
@@ -289,6 +321,7 @@ public:
|
||||
PIMap<PIConstChars, PICodeInfo::EnumInfo *> * enumsInfo;
|
||||
PIMap<PIConstChars, PICodeInfo::AccessValueFunction> * accessValueFunctions;
|
||||
PIMap<PIConstChars, PICodeInfo::AccessTypeFunction> * accessTypeFunctions;
|
||||
PIMap<PIConstChars, PICodeInfo::AccessOffsetFunction> * accessOffsetFunctions;
|
||||
|
||||
private:
|
||||
NO_COPY_CLASS(__Storage__)
|
||||
@@ -296,12 +329,10 @@ private:
|
||||
|
||||
class PIP_EXPORT __StorageAccess__ {
|
||||
public:
|
||||
//! \~english Getter for single storage of PICodeInfo::ClassInfo, access by name
|
||||
//! \~russian Доступ к единому хранилищу PICodeInfo::ClassInfo, доступ по имени
|
||||
static const PIMap<PIConstChars, PICodeInfo::ClassInfo *> & classes() { return *(__Storage__::instance()->classesInfo); }
|
||||
static const PIMap<PIConstChars, PICodeInfo::ClassInfo *> & classes() {
|
||||
return *(__Storage__::instance()->classesInfo);
|
||||
} // namespace PICodeInfo
|
||||
|
||||
//! \~english Getter for single storage of PICodeInfo::EnumInfo, access by name
|
||||
//! \~russian Доступ к единому хранилищу хранилище PICodeInfo::EnumInfo, доступ по имени
|
||||
static const PIMap<PIConstChars, PICodeInfo::EnumInfo *> & enums() { return *(__Storage__::instance()->enumsInfo); }
|
||||
|
||||
static const PIMap<PIConstChars, PICodeInfo::AccessValueFunction> & accessValueFunctions() {
|
||||
@@ -311,8 +342,15 @@ public:
|
||||
static const PIMap<PIConstChars, PICodeInfo::AccessTypeFunction> & accessTypeFunctions() {
|
||||
return *(__Storage__::instance()->accessTypeFunctions);
|
||||
}
|
||||
|
||||
static const PIMap<PIConstChars, PICodeInfo::AccessOffsetFunction> & accessOffsetFunctions() {
|
||||
return *(__Storage__::instance()->accessOffsetFunctions);
|
||||
}
|
||||
};
|
||||
|
||||
//! \relatesalso PICodeInfo
|
||||
//! \~english Macro for the global code model registries.
|
||||
//! \~russian Макрос для доступа к глобальным реестрам модели кода.
|
||||
#define PICODEINFO PICodeInfo::__StorageAccess__
|
||||
|
||||
|
||||
@@ -322,6 +360,7 @@ public:
|
||||
return __Storage__::instance()->classesInfo;
|
||||
}
|
||||
};
|
||||
|
||||
static ClassInfoInterface classesInfo;
|
||||
|
||||
|
||||
@@ -331,6 +370,7 @@ public:
|
||||
return __Storage__::instance()->enumsInfo;
|
||||
}
|
||||
};
|
||||
|
||||
static EnumsInfoInterface enumsInfo;
|
||||
|
||||
|
||||
@@ -340,6 +380,7 @@ public:
|
||||
return __Storage__::instance()->accessValueFunctions;
|
||||
}
|
||||
};
|
||||
|
||||
static AccessValueFunctionInterface accessValueFunctions;
|
||||
|
||||
|
||||
@@ -349,6 +390,7 @@ public:
|
||||
return __Storage__::instance()->accessTypeFunctions;
|
||||
}
|
||||
};
|
||||
|
||||
static AccessTypeFunctionInterface accessTypeFunctions;
|
||||
|
||||
|
||||
@@ -360,6 +402,8 @@ STATIC_INITIALIZER_BEGIN
|
||||
STATIC_INITIALIZER_END
|
||||
|
||||
|
||||
//! \~english Returns a serialized value of \a member_name from an instance of \a class_name.
|
||||
//! \~russian Возвращает сериализованное значение \a member_name из экземпляра \a class_name.
|
||||
inline PIByteArray getMemberValue(const void * p, const char * class_name, const char * member_name) {
|
||||
if (!p || !class_name || !member_name) return PIByteArray();
|
||||
AccessValueFunction af = PICODEINFO::accessValueFunctions().value(class_name, (AccessValueFunction)0);
|
||||
@@ -367,6 +411,8 @@ inline PIByteArray getMemberValue(const void * p, const char * class_name, const
|
||||
return af(p, member_name);
|
||||
}
|
||||
|
||||
//! \~english Returns the registered type name of \a member_name in \a class_name.
|
||||
//! \~russian Возвращает зарегистрированное имя типа \a member_name в \a class_name.
|
||||
inline const char * getMemberType(const char * class_name, const char * member_name) {
|
||||
if (!class_name || !member_name) return "";
|
||||
AccessTypeFunction af = PICODEINFO::accessTypeFunctions().value(class_name, (AccessTypeFunction)0);
|
||||
@@ -374,14 +420,20 @@ inline const char * getMemberType(const char * class_name, const char * member_n
|
||||
return af(member_name);
|
||||
}
|
||||
|
||||
//! \~english Returns \a member_name from \a class_name as %PIVariant when accessors are registered.
|
||||
//! \~russian Возвращает \a member_name из \a class_name как %PIVariant, если зарегистрированы функции доступа.
|
||||
PIP_EXPORT PIVariant getMemberAsVariant(const void * p, const char * class_name, const char * member_name);
|
||||
|
||||
|
||||
//! \~english Serializes assignable values into \a ret through the stream operator.
|
||||
//! \~russian Сериализует присваиваемые значения в \a ret через оператор потока.
|
||||
template<typename T, typename std::enable_if<std::is_assignable<T &, const T &>::value, int>::type = 0>
|
||||
void serialize(PIByteArray & ret, const T & v) {
|
||||
ret << v;
|
||||
}
|
||||
|
||||
//! \~english Fallback overload for values that cannot be written to the byte-array stream.
|
||||
//! \~russian Резервная перегрузка для значений, которые нельзя записать в поток массива байт.
|
||||
template<typename T, typename std::enable_if<!std::is_assignable<T &, const T &>::value, int>::type = 0>
|
||||
void serialize(PIByteArray & ret, const T & v) {}
|
||||
|
||||
|
||||
@@ -1,3 +1,13 @@
|
||||
/*! \file picodemodule.h
|
||||
* \ingroup Code
|
||||
* \~\brief
|
||||
* \~english Umbrella header for the code parsing module
|
||||
* \~russian Общий заголовок модуля разбора кода
|
||||
*
|
||||
* \~\details
|
||||
* \~english Includes the public code information and parser headers.
|
||||
* \~russian Подключает публичные заголовки информации о коде и парсера.
|
||||
*/
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Module includes
|
||||
@@ -34,12 +44,12 @@
|
||||
//! \~russian \par Общее
|
||||
//!
|
||||
//! \~english
|
||||
//! These files provides parsing C++ code and storage to use results of \a pip_cmg utility.
|
||||
//! See \ref code_model.
|
||||
//! This module provides C++ source parsing and the storage types used by the
|
||||
//! \a pip_cmg utility. See \ref code_model.
|
||||
//!
|
||||
//! \~russian
|
||||
//! Эти файлы обеспечивают разбор C++ кода и хранение результатов работы утилиты \a pip_cmg.
|
||||
//! Подробнее \ref code_model.
|
||||
//! Этот модуль предоставляет разбор исходного кода C++ и типы хранения,
|
||||
//! используемые утилитой \a pip_cmg. Подробнее \ref code_model.
|
||||
//!
|
||||
//! \~\authors
|
||||
//! \~english
|
||||
|
||||
@@ -19,6 +19,8 @@
|
||||
|
||||
#include "picodeparser.h"
|
||||
|
||||
#include "piliterals_string.h"
|
||||
|
||||
|
||||
PIString PICodeParser::Macro::expand(PIString args_, bool * ok) const {
|
||||
PIStringList arg_vals;
|
||||
@@ -454,7 +456,7 @@ bool PICodeParser::parseFileContent(PIString & fc, bool main) {
|
||||
cur_namespace += pfc.takeCWord() + s_ns;
|
||||
ccmn = pfc.takeRange('{', '}');
|
||||
// piCout << "namespace" << cur_namespace;
|
||||
parseClass(0, ccmn, true);
|
||||
parseClass(nullptr, ccmn, true);
|
||||
cur_namespace = prev_namespace;
|
||||
continue;
|
||||
}
|
||||
@@ -483,8 +485,8 @@ bool PICodeParser::parseFileContent(PIString & fc, bool main) {
|
||||
continue;
|
||||
}
|
||||
ccmn = pfc.left(dind) + s_bo + pfc.mid(dind).takeRange('{', '}') + s_bc;
|
||||
pfc.remove(0, ccmn.size());
|
||||
parseClass(0, ccmn, false);
|
||||
pfc.remove(0, ccmn.size() - 2);
|
||||
parseClass(nullptr, ccmn, false);
|
||||
continue;
|
||||
}
|
||||
if (pfc.left(4) == s_enum) {
|
||||
@@ -499,17 +501,59 @@ bool PICodeParser::parseFileContent(PIString & fc, bool main) {
|
||||
meta << smeta;
|
||||
}
|
||||
// piCout << "pfc E" << cur_namespace << "," << tmp;
|
||||
parseEnum(0, cur_namespace + tmp, pfc.takeRange('{', '}'), meta);
|
||||
parseEnum(nullptr, cur_namespace + tmp, pfc.takeRange('{', '}'), meta);
|
||||
pfc.takeSymbol();
|
||||
continue;
|
||||
}
|
||||
if (pfc.left(7) == s_typedef) {
|
||||
pfc.cutLeft(7);
|
||||
typedefs << parseTypedef(pfc.takeLeft(pfc.find(';')));
|
||||
PIString typedef_type = pfc.takeCWord();
|
||||
if (typedef_type == s_class || typedef_type == s_struct || typedef_type == s_union) {
|
||||
int dind = pfc.find('{', 0), find = pfc.find(';', 0);
|
||||
if (dind < 0 && find < 0) {
|
||||
pfc.cutLeft(6);
|
||||
continue;
|
||||
}
|
||||
if (dind < 0 || find < dind) {
|
||||
pfc.cutLeft(find + 1);
|
||||
continue;
|
||||
}
|
||||
PIString cname = pfc.left(dind);
|
||||
ccmn = cname + s_bo + pfc.mid(dind).takeRange('{', '}') + s_bc;
|
||||
pfc.remove(0, ccmn.size() - 3);
|
||||
if (cname.trimmed().isEmpty()) {
|
||||
cname = pfc.takeCWord();
|
||||
ccmn.prepend(cname);
|
||||
}
|
||||
ccmn.prepend(typedef_type + " "_a);
|
||||
parseClass(nullptr, ccmn, false);
|
||||
} else if (typedef_type == s_enum) {
|
||||
tmp = pfc.takeCWord();
|
||||
pfc.trim();
|
||||
MetaMap meta = maybeMeta(pfc);
|
||||
if (tmp == s_class || tmp == s_struct) {
|
||||
tmp = pfc.takeCWord();
|
||||
pfc.trim();
|
||||
MetaMap smeta = maybeMeta(pfc);
|
||||
meta << smeta;
|
||||
}
|
||||
ccmn = pfc.takeRange('{', '}');
|
||||
if (tmp.isEmpty()) {
|
||||
tmp = pfc.takeCWord();
|
||||
}
|
||||
// piCout << "pfc E" << cur_namespace << "," << tmp;
|
||||
parseEnum(nullptr, cur_namespace + tmp, ccmn, meta);
|
||||
} else {
|
||||
pfc.prepend(typedef_type);
|
||||
}
|
||||
PIString last = pfc.takeLeft(pfc.find(';')).trim();
|
||||
if (last.isNotEmpty()) {
|
||||
typedefs << parseTypedef(last);
|
||||
if (typedefs.back().first.isEmpty())
|
||||
typedefs.pop_back();
|
||||
else
|
||||
root_.typedefs << typedefs.back();
|
||||
}
|
||||
pfc.takeSymbol();
|
||||
continue;
|
||||
}
|
||||
@@ -567,15 +611,14 @@ PICodeParser::Entity * PICodeParser::parseClassDeclaration(const PIString & fc)
|
||||
Visibility vis = cur_def_vis;
|
||||
cur_def_vis = (is_class ? Private : Public);
|
||||
PIString cn = cd.mid(6).trim();
|
||||
bool has_name = !cn.isEmpty();
|
||||
bool is_anonymous = cn.isEmpty();
|
||||
if (cn.isEmpty()) cn = PIStringAscii("<unnamed_") + PIString::fromNumber(anon_num++) + '>';
|
||||
// piCout << "found " << typename_ << cn;
|
||||
if (cn.isEmpty()) return nullptr;
|
||||
Entity * e = new Entity();
|
||||
e->meta = meta;
|
||||
e->name = cur_namespace + cn;
|
||||
e->type = typename_;
|
||||
e->has_name = has_name;
|
||||
e->is_anonymous = is_anonymous;
|
||||
e->parents = parents;
|
||||
e->visibility = vis;
|
||||
e->file = cur_file;
|
||||
@@ -584,7 +627,7 @@ PICodeParser::Entity * PICodeParser::parseClassDeclaration(const PIString & fc)
|
||||
}
|
||||
|
||||
|
||||
void PICodeParser::parseClass(Entity * parent, PIString & fc, bool is_namespace) {
|
||||
PICodeParser::Entity * PICodeParser::parseClass(Entity * parent, PIString & fc, bool is_namespace) {
|
||||
static const PIString s_ns = PIStringAscii("::");
|
||||
static const PIString s_public = PIStringAscii("public");
|
||||
static const PIString s_protected = PIStringAscii("protected");
|
||||
@@ -599,7 +642,7 @@ void PICodeParser::parseClass(Entity * parent, PIString & fc, bool is_namespace)
|
||||
static const PIString s_template = PIStringAscii("template");
|
||||
Visibility prev_vis = cur_def_vis;
|
||||
int dind = fc.find('{'), find = fc.find(';'), end = 0;
|
||||
if (dind < 0 && find < 0) return;
|
||||
if (dind < 0 && find < 0) return nullptr;
|
||||
// piCout << "parse class <****\n" << fc << "\n****>";
|
||||
Entity * ce = parent;
|
||||
if (!is_namespace) {
|
||||
@@ -608,7 +651,6 @@ void PICodeParser::parseClass(Entity * parent, PIString & fc, bool is_namespace)
|
||||
}
|
||||
// piCout << "found class <****\n" << fc << "\n****>";
|
||||
if (ce) {
|
||||
if (parent) parent->children << ce;
|
||||
ce->parent_scope = parent;
|
||||
}
|
||||
int ps = -1;
|
||||
@@ -650,11 +692,29 @@ void PICodeParser::parseClass(Entity * parent, PIString & fc, bool is_namespace)
|
||||
fc.takeSymbol();
|
||||
continue;
|
||||
}
|
||||
tmp = fc.takeLeft(fc.find('{'));
|
||||
tmp = fc.takeLeft(fc.find('{')).trim();
|
||||
stmp = fc.takeRange('{', '}');
|
||||
fc.takeSymbol();
|
||||
stmp = cw + ' ' + tmp + '{' + stmp + '}';
|
||||
parseClass(ce, stmp, false);
|
||||
auto new_entity = parseClass(ce, stmp, false);
|
||||
// piCout << "!!! > \"" << fc << "\"";
|
||||
PIStringList vars;
|
||||
PIString var;
|
||||
do {
|
||||
var = fc.takeCWord();
|
||||
if (var.isNotEmpty()) vars << var;
|
||||
if (fc.takeSymbol() == ";") break;
|
||||
} while (var.isNotEmpty());
|
||||
if (new_entity) {
|
||||
Member me;
|
||||
me.visibility = cur_def_vis;
|
||||
me.type = new_entity->name;
|
||||
if (tmp.isEmpty() && vars.isEmpty()) vars = {""};
|
||||
for (const auto & v: vars) {
|
||||
me.name = v;
|
||||
ce->members << me;
|
||||
}
|
||||
}
|
||||
// piCout << "!!! <" << vars;
|
||||
continue;
|
||||
}
|
||||
if (cw == s_enum) {
|
||||
@@ -710,6 +770,7 @@ void PICodeParser::parseClass(Entity * parent, PIString & fc, bool is_namespace)
|
||||
}
|
||||
cur_def_vis = prev_vis;
|
||||
cur_namespace = prev_namespace;
|
||||
return ce;
|
||||
}
|
||||
|
||||
|
||||
@@ -766,7 +827,7 @@ bool PICodeParser::parseEnum(Entity * parent, const PIString & name, PIString fc
|
||||
|
||||
|
||||
PICodeParser::Typedef PICodeParser::parseTypedef(PIString fc) {
|
||||
// piCout << "parse typedef" << fc;
|
||||
// piCout << "parse typedef \"" << fc << "\"";
|
||||
Typedef td;
|
||||
fc.replaceAll('\t', ' ');
|
||||
|
||||
@@ -1197,7 +1258,7 @@ void PICodeParser::replaceMeta(PIString & dn) {
|
||||
PICodeParser::Entity * PICodeParser::findEntityByName(const PIString & en) {
|
||||
for (auto * e: entities)
|
||||
if (e->name == en) return e;
|
||||
return 0;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/*! \file picodeparser.h
|
||||
* \ingroup Code
|
||||
* \~\brief
|
||||
* \~english C++ code parser
|
||||
* \~russian Разбор C++ кода
|
||||
*/
|
||||
//! \~\file picodeparser.h
|
||||
//! \~\ingroup Code
|
||||
//! \~\brief
|
||||
//! \~english C++ code parser
|
||||
//! \~russian Разбор C++ кода
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
C++ code parser
|
||||
@@ -37,44 +36,88 @@ inline bool _isCChar(const PIString & c) {
|
||||
return _isCChar(c[0]);
|
||||
}
|
||||
|
||||
//! \~\ingroup Code
|
||||
//! \~\brief
|
||||
//! \~english Parser of C/C++ declarations used by the code model tools.
|
||||
//! \~russian Разборщик объявлений C/C++, используемый инструментами модели кода.
|
||||
//! \~\details
|
||||
//! \~english Parser for analyzing C++ source files. Extracts information about classes, structures, enums, macros, functions, and members.
|
||||
//! \~russian Парсер для анализа C++ исходных файлов. Извлекает информацию о классах, структурах, перечислениях, макросах, функциях и
|
||||
//! членах.
|
||||
class PIP_EXPORT PICodeParser {
|
||||
public:
|
||||
//! \~english Constructs a parser with built-in PIP macro presets.
|
||||
//! \~russian Создает разборщик со встроенными предустановками макросов PIP.
|
||||
PICodeParser();
|
||||
|
||||
//! \~english Visibility of a parsed declaration inside the current scope.
|
||||
//! \~russian Видимость разобранного объявления в текущей области.
|
||||
enum Visibility {
|
||||
Global,
|
||||
Public,
|
||||
Protected,
|
||||
Private
|
||||
};
|
||||
enum Attribute {
|
||||
NoAttributes = 0x0,
|
||||
Const = 0x01,
|
||||
Static = 0x02,
|
||||
Mutable = 0x04,
|
||||
Volatile = 0x08,
|
||||
Inline = 0x10,
|
||||
Virtual = 0x20,
|
||||
Extern = 0x40
|
||||
Global /** \~english Global or namespace-level declaration. \~russian Глобальное объявление или объявление уровня пространства имен.
|
||||
*/
|
||||
,
|
||||
Public /** \~english Public class member. \~russian Открытый член класса. */,
|
||||
Protected /** \~english Protected class member. \~russian Защищенный член класса. */,
|
||||
Private /** \~english Private class member. \~russian Закрытый член класса. */
|
||||
};
|
||||
|
||||
//! \~english Parsed declaration attributes.
|
||||
//! \~russian Атрибуты разобранного объявления.
|
||||
enum Attribute {
|
||||
NoAttributes = 0x0 /** \~english No attributes. \~russian Атрибуты отсутствуют. */,
|
||||
Const = 0x01 /** \~english \c const declaration. \~russian Объявление с \c const. */,
|
||||
Static = 0x02 /** \~english \c static declaration. \~russian Объявление с \c static. */,
|
||||
Mutable = 0x04 /** \~english \c mutable declaration. \~russian Объявление с \c mutable. */,
|
||||
Volatile = 0x08 /** \~english \c volatile declaration. \~russian Объявление с \c volatile. */,
|
||||
Inline = 0x10 /** \~english \c inline declaration. \~russian Объявление с \c inline. */,
|
||||
Virtual = 0x20 /** \~english \c virtual declaration. \~russian Объявление с \c virtual. */,
|
||||
Extern = 0x40 /** \~english \c extern declaration. \~russian Объявление с \c extern. */
|
||||
};
|
||||
|
||||
//! \~english Bitmask of parsed declaration attributes.
|
||||
//! \~russian Битовая маска атрибутов разобранного объявления.
|
||||
typedef PIFlags<Attribute> Attributes;
|
||||
|
||||
//! \~english Preprocessor define name and value.
|
||||
//! \~russian Имя и значение макроса \c define.
|
||||
typedef PIPair<PIString, PIString> Define;
|
||||
|
||||
//! \~english Typedef alias and target type.
|
||||
//! \~russian Псевдоним typedef и целевой тип.
|
||||
typedef PIPair<PIString, PIString> Typedef;
|
||||
|
||||
//! \~english Parsed metadata map.
|
||||
//! \~russian Карта разобранных метаданных.
|
||||
typedef PIMap<PIString, PIString> MetaMap;
|
||||
|
||||
//! \~english Parsed function-like macro.
|
||||
//! \~russian Разобранный функциональный макрос.
|
||||
struct PIP_EXPORT Macro {
|
||||
Macro(const PIString & n = PIString(), const PIString & v = PIString(), const PIStringList & a = PIStringList()) {
|
||||
name = n;
|
||||
value = v;
|
||||
args = a;
|
||||
}
|
||||
|
||||
//! \~english Expands the macro body with arguments from \a args_.
|
||||
//! \~russian Разворачивает тело макроса с аргументами из \a args_.
|
||||
PIString expand(PIString args_, bool * ok = 0) const;
|
||||
|
||||
//! \~english Macro name.
|
||||
//! \~russian Имя макроса.
|
||||
PIString name;
|
||||
|
||||
//! \~english Macro replacement text.
|
||||
//! \~russian Текст замены макроса.
|
||||
PIString value;
|
||||
|
||||
//! \~english Ordered list of macro argument names.
|
||||
//! \~russian Упорядоченный список имен аргументов макроса.
|
||||
PIStringList args;
|
||||
};
|
||||
|
||||
//! \~english Parsed member declaration or function signature.
|
||||
//! \~russian Разобранное объявление члена или сигнатура функции.
|
||||
struct PIP_EXPORT Member {
|
||||
Member() {
|
||||
visibility = Global;
|
||||
@@ -83,79 +126,224 @@ public:
|
||||
is_type_ptr = false;
|
||||
attributes = NoAttributes;
|
||||
}
|
||||
|
||||
//! \~english Returns whether the member is declared as a bitfield.
|
||||
//! \~russian Возвращает, объявлен ли член как битовое поле.
|
||||
bool isBitfield() const { return bits > 0; }
|
||||
|
||||
//! \~english Parsed metadata attached to the member.
|
||||
//! \~russian Разобранные метаданные, привязанные к члену.
|
||||
MetaMap meta;
|
||||
|
||||
//! \~english Member type or return type.
|
||||
//! \~russian Тип члена или возвращаемый тип.
|
||||
PIString type;
|
||||
|
||||
//! \~english Member name.
|
||||
//! \~russian Имя члена.
|
||||
PIString name;
|
||||
|
||||
//! \~english Full textual argument declarations.
|
||||
//! \~russian Полные текстовые объявления аргументов.
|
||||
PIStringList arguments_full;
|
||||
|
||||
//! \~english Argument types only.
|
||||
//! \~russian Только типы аргументов.
|
||||
PIStringList arguments_type;
|
||||
|
||||
//! \~english Parsed array dimensions.
|
||||
//! \~russian Разобранные размеры массива.
|
||||
PIStringList dims;
|
||||
|
||||
//! \~english Member visibility.
|
||||
//! \~russian Видимость члена.
|
||||
Visibility visibility;
|
||||
|
||||
//! \~english Member attributes.
|
||||
//! \~russian Атрибуты члена.
|
||||
Attributes attributes;
|
||||
|
||||
//! \~english Indicates that the parsed type is a pointer.
|
||||
//! \~russian Показывает, что разобранный тип является указателем.
|
||||
bool is_type_ptr;
|
||||
|
||||
//! \~english Parsed size in bytes when available.
|
||||
//! \~russian Разобранный размер в байтах, если он известен.
|
||||
int size;
|
||||
|
||||
//! \~english Bit count for bitfields, or \c -1 otherwise.
|
||||
//! \~russian Количество бит для битового поля или \c -1 в остальных случаях.
|
||||
int bits;
|
||||
};
|
||||
|
||||
//! \~english Parsed class, struct or namespace.
|
||||
//! \~russian Разобранный класс, структура или пространство имен.
|
||||
struct PIP_EXPORT Entity {
|
||||
Entity() {
|
||||
visibility = Global;
|
||||
has_name = true;
|
||||
is_anonymous = false;
|
||||
size = 0;
|
||||
parent_scope = 0;
|
||||
}
|
||||
|
||||
//! \~english Parsed metadata attached to the entity.
|
||||
//! \~russian Разобранные метаданные, привязанные к сущности.
|
||||
MetaMap meta;
|
||||
|
||||
//! \~english Entity kind, for example \c class, \c struct or \c namespace.
|
||||
//! \~russian Вид сущности, например \c class, \c struct или \c namespace.
|
||||
PIString type;
|
||||
|
||||
//! \~english Entity name.
|
||||
//! \~russian Имя сущности.
|
||||
PIString name;
|
||||
|
||||
//! \~english Source file where the entity was parsed.
|
||||
//! \~russian Исходный файл, в котором была разобрана сущность.
|
||||
PIString file;
|
||||
|
||||
//! \~english Entity visibility inside its parent scope.
|
||||
//! \~russian Видимость сущности внутри родительской области.
|
||||
Visibility visibility;
|
||||
|
||||
//! \~english Parsed size in bytes when available.
|
||||
//! \~russian Разобранный размер в байтах, если он известен.
|
||||
int size;
|
||||
bool has_name;
|
||||
|
||||
//! \~english Indicates that the entity was declared without a name.
|
||||
//! \~russian Показывает, что сущность объявлена без имени.
|
||||
bool is_anonymous;
|
||||
|
||||
//! \~english Immediate containing entity, or \c nullptr for the root scope.
|
||||
//! \~russian Непосредственная содержащая сущность или \c nullptr для корневой области.
|
||||
Entity * parent_scope;
|
||||
|
||||
//! \~english Direct base entities.
|
||||
//! \~russian Непосредственные базовые сущности.
|
||||
PIVector<Entity *> parents;
|
||||
PIVector<Entity *> children;
|
||||
|
||||
//! \~english Parsed member functions.
|
||||
//! \~russian Разобранные функции-члены.
|
||||
PIVector<Member> functions;
|
||||
|
||||
//! \~english Parsed data members.
|
||||
//! \~russian Разобранные поля данных.
|
||||
PIVector<Member> members;
|
||||
|
||||
//! \~english Typedefs declared inside the entity.
|
||||
//! \~russian Typedef-объявления внутри сущности.
|
||||
PIVector<Typedef> typedefs;
|
||||
};
|
||||
|
||||
//! \~english Parsed enumerator entry.
|
||||
//! \~russian Разобранный элемент перечисления.
|
||||
struct PIP_EXPORT EnumeratorInfo {
|
||||
EnumeratorInfo(const PIString & n = PIString(), int v = 0, const MetaMap & m = MetaMap()) {
|
||||
name = n;
|
||||
value = v;
|
||||
meta = m;
|
||||
}
|
||||
|
||||
//! \~english Parsed metadata attached to the enumerator.
|
||||
//! \~russian Разобранные метаданные, привязанные к элементу перечисления.
|
||||
MetaMap meta;
|
||||
|
||||
//! \~english Enumerator name.
|
||||
//! \~russian Имя элемента перечисления.
|
||||
PIString name;
|
||||
|
||||
//! \~english Enumerator value.
|
||||
//! \~russian Значение элемента перечисления.
|
||||
int value;
|
||||
};
|
||||
|
||||
//! \~english Parsed enumeration.
|
||||
//! \~russian Разобранное перечисление.
|
||||
struct PIP_EXPORT Enum {
|
||||
Enum(const PIString & n = PIString()) { name = n; }
|
||||
|
||||
//! \~english Parsed metadata attached to the enum.
|
||||
//! \~russian Разобранные метаданные, привязанные к перечислению.
|
||||
MetaMap meta;
|
||||
|
||||
//! \~english Enum name.
|
||||
//! \~russian Имя перечисления.
|
||||
PIString name;
|
||||
|
||||
//! \~english Parsed enumerators.
|
||||
//! \~russian Разобранные элементы перечисления.
|
||||
PIVector<EnumeratorInfo> members;
|
||||
};
|
||||
|
||||
//! \~english Parses one source file and optionally follows its includes.
|
||||
//! \~russian Разбирает один исходный файл и при необходимости следует по его include-зависимостям.
|
||||
void parseFile(const PIString & file, bool follow_includes = true);
|
||||
|
||||
//! \~english Parses several source files into one parser state.
|
||||
//! \~russian Разбирает несколько исходных файлов в одном состоянии разборщика.
|
||||
void parseFiles(const PIStringList & files, bool follow_includes = true);
|
||||
|
||||
//! \~english Parses source text provided directly in memory.
|
||||
//! \~russian Разбирает исходный текст, переданный напрямую из памяти.
|
||||
void parseFileContent(PIString fc);
|
||||
|
||||
|
||||
//! \~english Adds a directory to the include search list.
|
||||
//! \~russian Добавляет каталог в список поиска include-файлов.
|
||||
void includeDirectory(const PIString & dir) { includes << dir; }
|
||||
|
||||
//! \~english Adds a custom preprocessor definition before parsing.
|
||||
//! \~russian Добавляет пользовательское препроцессорное определение перед разбором.
|
||||
void addDefine(const PIString & def_name, const PIString & def_value) { custom_defines << Define(def_name, def_value); }
|
||||
|
||||
//! \~english Returns whether an enum with \a name was parsed.
|
||||
//! \~russian Возвращает, было ли разобрано перечисление с именем \a name.
|
||||
bool isEnum(const PIString & name);
|
||||
|
||||
//! \~english Finds a parsed entity by its full name.
|
||||
//! \~russian Ищет разобранную сущность по ее полному имени.
|
||||
Entity * findEntityByName(const PIString & en);
|
||||
|
||||
//! \~english Returns the set of files already processed by the parser.
|
||||
//! \~russian Возвращает набор файлов, уже обработанных разборщиком.
|
||||
PIStringList parsedFiles() const { return PIStringList(proc_files.toVector()); }
|
||||
|
||||
//! \~english Returns the file detected as the main translation unit.
|
||||
//! \~russian Возвращает файл, определенный как основной единицей трансляции.
|
||||
PIString mainFile() const { return main_file; }
|
||||
|
||||
//! \~english Returns the synthetic global scope entity.
|
||||
//! \~russian Возвращает синтетическую сущность глобальной области.
|
||||
const PICodeParser::Entity * global() const { return &root_; }
|
||||
|
||||
|
||||
//! \~english Returns the maximum number of macro substitution passes.
|
||||
//! \~russian Возвращает максимальное число проходов подстановки макросов.
|
||||
int macrosSubstitutionMaxIterations() const { return macros_iter; }
|
||||
|
||||
//! \~english Sets the maximum number of macro substitution passes.
|
||||
//! \~russian Задает максимальное число проходов подстановки макросов.
|
||||
void setMacrosSubstitutionMaxIterations(int value) { macros_iter = value; }
|
||||
|
||||
|
||||
//! \~english Parsed \c define directives, including built-in and custom ones.
|
||||
//! \~russian Разобранные директивы \c define, включая встроенные и пользовательские.
|
||||
PIVector<Define> defines, custom_defines;
|
||||
|
||||
//! \~english Parsed function-like macros.
|
||||
//! \~russian Разобранные функциональные макросы.
|
||||
PIVector<Macro> macros;
|
||||
|
||||
//! \~english Parsed enums from the processed files.
|
||||
//! \~russian Разобранные перечисления из обработанных файлов.
|
||||
PIVector<Enum> enums;
|
||||
|
||||
//! \~english Parsed top-level typedef declarations.
|
||||
//! \~russian Разобранные typedef-объявления верхнего уровня.
|
||||
PIVector<Typedef> typedefs;
|
||||
|
||||
//! \~english Parsed entities discovered in the processed files.
|
||||
//! \~russian Разобранные сущности, найденные в обработанных файлах.
|
||||
PIVector<Entity *> entities;
|
||||
|
||||
private:
|
||||
@@ -164,7 +352,7 @@ private:
|
||||
bool parseFileContent(PIString & fc, bool main);
|
||||
bool parseDirective(PIString d);
|
||||
Entity * parseClassDeclaration(const PIString & fc);
|
||||
void parseClass(Entity * parent, PIString & fc, bool is_namespace);
|
||||
Entity * parseClass(Entity * parent, PIString & fc, bool is_namespace);
|
||||
MetaMap parseMeta(PIString & fc);
|
||||
bool parseEnum(Entity * parent, const PIString & name, PIString fc, const MetaMap & meta);
|
||||
Typedef parseTypedef(PIString fc);
|
||||
|
||||
@@ -1,3 +1,12 @@
|
||||
//! \~\file piconsolemodule.h
|
||||
//! \~\ingroup Console
|
||||
//! \~\brief
|
||||
//! \~english Console module headers
|
||||
//! \~russian Заголовочные файлы модуля консоли
|
||||
//! \~\details
|
||||
//! \~english This file includes all Console module headers providing keyboard input, screen management, and tile-based UI.
|
||||
//! \~russian Этот файл включает все заголовочные файлы модуля консоли, обеспечивающие ввод с клавиатуры, управление экраном и UI на основе
|
||||
//! тайлов.
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Module includes
|
||||
@@ -18,8 +27,8 @@
|
||||
*/
|
||||
//! \defgroup Console Console
|
||||
//! \~\brief
|
||||
//! \~english Console graphic
|
||||
//! \~russian Графика в консоли
|
||||
//! \~english Console screen, input, and terminal utilities
|
||||
//! \~russian Средства консольного экрана, ввода и терминала
|
||||
//!
|
||||
//! \~\details
|
||||
//! \~english \section cmake_module_Console Building with CMake
|
||||
@@ -34,10 +43,10 @@
|
||||
//! \~russian \par Общее
|
||||
//!
|
||||
//! \~english
|
||||
//! These files provides grab keyboard from console, simple tiling manager and virtual terminal.
|
||||
//! These files provide keyboard capture from the console, a simple tile-based screen API and a virtual terminal.
|
||||
//!
|
||||
//! \~russian
|
||||
//! Эти файлы обеспечивают захват клавиатуры в консоли, простой тайловый менеджер и виртуальный терминал.
|
||||
//! Эти файлы предоставляют захват клавиатуры из консоли, простой экранный API на тайлах и виртуальный терминал.
|
||||
//!
|
||||
//! \~\authors
|
||||
//! \~english
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/*! \file pikbdlistener.h
|
||||
* \ingroup Console
|
||||
* \~\brief
|
||||
* \~english Keyboard console input listener
|
||||
* \~russian Консольный захват клавиатуры
|
||||
*/
|
||||
//! \~\file pikbdlistener.h
|
||||
//! \~\ingroup Console
|
||||
//! \~\brief
|
||||
//! \~english Console keyboard and mouse input listener
|
||||
//! \~russian Слушатель клавиатурного и мышиного консольного ввода
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Keyboard grabber for console
|
||||
@@ -29,6 +28,10 @@
|
||||
#include "pithread.h"
|
||||
#include "pitime.h"
|
||||
|
||||
//! \relatesalso PIKbdListener
|
||||
//! \~\brief
|
||||
//! \~english Waits until the active listener captures the configured exit key and then stops it.
|
||||
//! \~russian Ожидает, пока активный слушатель перехватит настроенную клавишу выхода, и затем останавливает его.
|
||||
#define WAIT_FOR_EXIT \
|
||||
while (!PIKbdListener::exiting) \
|
||||
piMSleep(PIP_MIN_MSLEEP * 5); \
|
||||
@@ -37,87 +40,107 @@
|
||||
}
|
||||
|
||||
|
||||
//! \~\ingroup Console
|
||||
//! \~\brief
|
||||
//! \~english Console input listener for keyboard and mouse events.
|
||||
//! \~russian Слушатель консольного ввода для событий клавиатуры и мыши.
|
||||
class PIP_EXPORT PIKbdListener: public PIThread {
|
||||
PIOBJECT_SUBCLASS(PIKbdListener, PIThread);
|
||||
friend class PIConsole;
|
||||
friend class PITerminal;
|
||||
|
||||
public:
|
||||
//! Special keyboard keys
|
||||
//! \~english Keyboard keys reported as non-character codes.
|
||||
//! \~russian Клавиши, передаваемые как несимвольные коды.
|
||||
enum SpecialKey {
|
||||
Tab /** Tab key */ = 0x09,
|
||||
Return /** Enter key */ = 0x0a,
|
||||
Esc /** Escape key */ = 0x1b,
|
||||
Space /** Space key */ = 0x20,
|
||||
Backspace /** Backspace key */ = 0x7f,
|
||||
UpArrow /** Up arrow key */ = -1,
|
||||
DownArrow /** Down arrow key */ = -2,
|
||||
RightArrow /** Right arrow key */ = -3,
|
||||
LeftArrow /** Left arrow key */ = -4,
|
||||
Home /** Home key */ = -5,
|
||||
End /** End key */ = -6,
|
||||
PageUp /** Page up key */ = -7,
|
||||
PageDown /** Page down key */ = -8,
|
||||
Insert /** Delete key */ = -9,
|
||||
Delete /** Delete key */ = -10,
|
||||
F1 /** F1 key */ = -11,
|
||||
F2 /** F2 key */ = -12,
|
||||
F3 /** F3 key */ = -13,
|
||||
F4 /** F4 key */ = -14,
|
||||
F5 /** F5 key */ = -15,
|
||||
F6 /** F6 key */ = -16,
|
||||
F7 /** F7 key */ = -17,
|
||||
F8 /** F8 key */ = -18,
|
||||
F9 /** F9 key */ = -19,
|
||||
F10 /** F10 key */ = -20,
|
||||
F11 /** F11 key */ = -21,
|
||||
F12 /** F12 key */ = -22
|
||||
Tab = 0x09 /** \~english Tab key \~russian Клавиша Tab */,
|
||||
Return = 0x0a /** \~english Enter key \~russian Клавиша Enter */,
|
||||
Esc = 0x1b /** \~english Escape key \~russian Клавиша Escape */,
|
||||
Space = 0x20 /** \~english Space key \~russian Клавиша пробела */,
|
||||
Backspace = 0x7f /** \~english Backspace key \~russian Клавиша Backspace */,
|
||||
UpArrow = -1 /** \~english Up arrow key \~russian Стрелка вверх */,
|
||||
DownArrow = -2 /** \~english Down arrow key \~russian Стрелка вниз */,
|
||||
RightArrow = -3 /** \~english Right arrow key \~russian Стрелка вправо */,
|
||||
LeftArrow = -4 /** \~english Left arrow key \~russian Стрелка влево */,
|
||||
Home = -5 /** \~english Home key \~russian Клавиша Home */,
|
||||
End = -6 /** \~english End key \~russian Клавиша End */,
|
||||
PageUp = -7 /** \~english Page Up key \~russian Клавиша Page Up */,
|
||||
PageDown = -8 /** \~english Page Down key \~russian Клавиша Page Down */,
|
||||
Insert = -9 /** \~english Insert key \~russian Клавиша Insert */,
|
||||
Delete = -10 /** \~english Delete key \~russian Клавиша Delete */,
|
||||
F1 = -11 /** \~english F1 key \~russian Клавиша F1 */,
|
||||
F2 = -12 /** \~english F2 key \~russian Клавиша F2 */,
|
||||
F3 = -13 /** \~english F3 key \~russian Клавиша F3 */,
|
||||
F4 = -14 /** \~english F4 key \~russian Клавиша F4 */,
|
||||
F5 = -15 /** \~english F5 key \~russian Клавиша F5 */,
|
||||
F6 = -16 /** \~english F6 key \~russian Клавиша F6 */,
|
||||
F7 = -17 /** \~english F7 key \~russian Клавиша F7 */,
|
||||
F8 = -18 /** \~english F8 key \~russian Клавиша F8 */,
|
||||
F9 = -19 /** \~english F9 key \~russian Клавиша F9 */,
|
||||
F10 = -20 /** \~english F10 key \~russian Клавиша F10 */,
|
||||
F11 = -21 /** \~english F11 key \~russian Клавиша F11 */,
|
||||
F12 = -22 /** \~english F12 key \~russian Клавиша F12 */
|
||||
};
|
||||
|
||||
//! Keyboard modifiers
|
||||
//! \~english Keyboard modifier bit flags.
|
||||
//! \~russian Битовые флаги модификаторов клавиатуры.
|
||||
enum KeyModifier {
|
||||
Ctrl /** Control key */ = 0x1,
|
||||
Shift /** Shift key */ = 0x2,
|
||||
Alt /** Alt key */ = 0x4
|
||||
// Meta /** Meta (windows) key */ = 0x8
|
||||
Ctrl = 0x1 /** \~english Control key \~russian Клавиша Control */,
|
||||
Shift = 0x2 /** \~english Shift key \~russian Клавиша Shift */,
|
||||
Alt = 0x4 /** \~english Alt key \~russian Клавиша Alt */,
|
||||
// Meta = 0x8 /** Meta (windows) key */
|
||||
};
|
||||
|
||||
//! \~english Combination of \a KeyModifier flags.
|
||||
//! \~russian Комбинация флагов \a KeyModifier.
|
||||
typedef PIFlags<KeyModifier> KeyModifiers;
|
||||
|
||||
//! This struct contains information about pressed keyboard key
|
||||
//! \~english Information about one keyboard event.
|
||||
//! \~russian Информация об одном событии клавиатуры.
|
||||
struct PIP_EXPORT KeyEvent {
|
||||
//! \~english Constructs an empty event or initializes it with key and modifiers.
|
||||
//! \~russian Создает пустое событие или инициализирует его клавишей и модификаторами.
|
||||
KeyEvent(int k = 0, KeyModifiers m = 0) {
|
||||
key = k;
|
||||
modifiers = m;
|
||||
}
|
||||
|
||||
//! Pressed key. It can be simple \b char or special key (see PIKbdListener::SpecialKey)
|
||||
//! \~english Pressed key code. It can be a character code or one of \a SpecialKey values.
|
||||
//! \~russian Код нажатой клавиши. Это может быть код символа или одно из значений \a SpecialKey.
|
||||
int key;
|
||||
|
||||
//! Active keyboard modifiers. It contains PIKbdListener::KeyModifier bitfields
|
||||
//! \~english Active keyboard modifiers as a combination of \a KeyModifier flags.
|
||||
//! \~russian Активные модификаторы клавиатуры как комбинация флагов \a KeyModifier.
|
||||
KeyModifiers modifiers;
|
||||
};
|
||||
|
||||
//! Mouse buttons
|
||||
//! \~english Mouse button bit flags.
|
||||
//! \~russian Битовые флаги кнопок мыши.
|
||||
enum MouseButton {
|
||||
MouseLeft /** Left button */ = 0x01,
|
||||
MouseRight /** Right button */ = 0x02,
|
||||
MouseMiddle /** Middle button */ = 0x04
|
||||
MouseLeft = 0x01 /** \~english Left button \~russian Левая кнопка */,
|
||||
MouseRight = 0x02 /** \~english Right button \~russian Правая кнопка */,
|
||||
MouseMiddle = 0x04 /** \~english Middle button \~russian Средняя кнопка */
|
||||
};
|
||||
|
||||
//! Mouse actions
|
||||
//! \~english Mouse action kind.
|
||||
//! \~russian Вид действия мыши.
|
||||
enum MouseAction {
|
||||
MouseButtonPress /** Mouse button pressed */,
|
||||
MouseButtonRelease /** Mouse button released */,
|
||||
MouseButtonDblClick /** Mouse button double click */,
|
||||
MouseMove /** Mouse moved */,
|
||||
MouseWheel /** Mouse wheel rotated */
|
||||
MouseButtonPress /** \~english Mouse button pressed \~russian Нажатие кнопки мыши */,
|
||||
MouseButtonRelease /** \~english Mouse button released \~russian Отпускание кнопки мыши */,
|
||||
MouseButtonDblClick /** \~english Mouse button double-click \~russian Двойной щелчок кнопкой мыши */,
|
||||
MouseMove /** \~english Mouse moved \~russian Перемещение мыши */,
|
||||
MouseWheel /** \~english Mouse wheel rotated \~russian Прокрутка колеса мыши */
|
||||
};
|
||||
|
||||
//! \~english Combination of pressed \a MouseButton flags.
|
||||
//! \~russian Комбинация нажатых флагов \a MouseButton.
|
||||
typedef PIFlags<MouseButton> MouseButtons;
|
||||
|
||||
//! This struct contains information about mouse action
|
||||
//! \~english Information about one mouse event.
|
||||
//! \~russian Информация об одном событии мыши.
|
||||
struct PIP_EXPORT MouseEvent {
|
||||
//! \~english Constructs an event with coordinates at the origin.
|
||||
//! \~russian Создает событие с координатами в начале области.
|
||||
MouseEvent(MouseAction a = MouseButtonPress, MouseButtons b = 0, KeyModifiers m = 0) {
|
||||
x = y = 0;
|
||||
action = a;
|
||||
@@ -125,107 +148,156 @@ public:
|
||||
modifiers = m;
|
||||
}
|
||||
|
||||
//! Event X coordinate in view-space, from 0
|
||||
//! \~english Event X coordinate in screen space, starting from zero.
|
||||
//! \~russian Координата X события в экранном пространстве, начиная с нуля.
|
||||
int x;
|
||||
|
||||
//! Event Y coordinate in view-space, from 0
|
||||
//! \~english Event Y coordinate in screen space, starting from zero.
|
||||
//! \~russian Координата Y события в экранном пространстве, начиная с нуля.
|
||||
int y;
|
||||
|
||||
//! Mouse action type
|
||||
//! \~english Mouse action kind.
|
||||
//! \~russian Вид действия мыши.
|
||||
MouseAction action;
|
||||
|
||||
//! Pressed buttons. It contains PIKbdListener::MouseButton bitfields
|
||||
//! \~english Pressed mouse buttons as a combination of \a MouseButton flags.
|
||||
//! \~russian Нажатые кнопки мыши как комбинация флагов \a MouseButton.
|
||||
MouseButtons buttons;
|
||||
|
||||
//! Active keyboard modifiers. It contains PIKbdListener::KeyModifier bitfields
|
||||
//! \~english Active keyboard modifiers as a combination of \a KeyModifier flags.
|
||||
//! \~russian Активные модификаторы клавиатуры как комбинация флагов \a KeyModifier.
|
||||
KeyModifiers modifiers;
|
||||
};
|
||||
|
||||
//! This struct contains information about mouse wheel action
|
||||
//! \~english Information about one mouse wheel event.
|
||||
//! \~russian Информация об одном событии колеса мыши.
|
||||
struct PIP_EXPORT WheelEvent: public MouseEvent {
|
||||
//! \~english Constructs a wheel event with downward direction by default.
|
||||
//! \~russian Создает событие колеса мыши; по умолчанию направление вниз.
|
||||
WheelEvent(): MouseEvent() { direction = false; }
|
||||
|
||||
//! Wheel direction, /b true - up, /b fasle - down
|
||||
//! \~english Wheel direction: \b true for up, \b false for down.
|
||||
//! \~russian Направление прокрутки: \b true вверх, \b false вниз.
|
||||
bool direction;
|
||||
};
|
||||
|
||||
//! \~english Callback receiving a key event and user data.
|
||||
//! \~russian Обратный вызов, принимающий событие клавиши и пользовательские данные.
|
||||
typedef std::function<void(KeyEvent, void *)> KBFunc;
|
||||
|
||||
//! Constructs keyboard listener with external function "slot" and custom data "data"
|
||||
//! \~english Constructs a listener with optional callback, user data, and auto-start mode.
|
||||
//! \~russian Создает слушатель с необязательным обратным вызовом, пользовательскими данными и автозапуском.
|
||||
explicit PIKbdListener(KBFunc slot = 0, void * data = 0, bool startNow = true);
|
||||
|
||||
//! \~english Stops the listener and restores the console state.
|
||||
//! \~russian Останавливает слушатель и восстанавливает состояние консоли.
|
||||
~PIKbdListener();
|
||||
|
||||
|
||||
//! Returns custom data
|
||||
//! \~english Returns the user data passed back with callbacks and events.
|
||||
//! \~russian Возвращает пользовательские данные, передаваемые обратно в обратные вызовы и события.
|
||||
void * data() { return kbddata_; }
|
||||
|
||||
//! Set custom data to "_data"
|
||||
//! \~english Sets the user data passed back with callbacks and events.
|
||||
//! \~russian Задает пользовательские данные, возвращаемые в обратных вызовах и событиях.
|
||||
void setData(void * _data) { kbddata_ = _data; }
|
||||
|
||||
//! Set external function to "slot"
|
||||
void setSlot(KBFunc slot) { ret_func = slot; }
|
||||
//! \~english Sets the callback receiving both key event and user data.
|
||||
//! \~russian Устанавливает обратный вызов, получающий событие клавиши и пользовательские данные.
|
||||
void setSlot(KBFunc slot) { ret_func = std::move(slot); }
|
||||
|
||||
//! Set external function to "slot"
|
||||
//! \~english Sets the callback that only receives the key event and ignores user data.
|
||||
//! \~russian Устанавливает обратный вызов, получающий только событие клавиши и игнорирующий пользовательские данные.
|
||||
void setSlot(std::function<void(KeyEvent)> slot) {
|
||||
ret_func = [slot](KeyEvent e, void *) { slot(e); };
|
||||
}
|
||||
|
||||
//! Returns if exit key if awaiting
|
||||
//! \~english Returns whether the exit key is currently being captured.
|
||||
//! \~russian Возвращает, включен ли сейчас перехват клавиши выхода.
|
||||
bool exitCaptured() const { return exit_enabled; }
|
||||
|
||||
//! Returns exit key, default 'Q'
|
||||
//! \~english Returns the configured exit key. The default is \c 'Q'.
|
||||
//! \~russian Возвращает настроенную клавишу выхода. По умолчанию это \c 'Q'.
|
||||
int exitKey() const { return exit_key; }
|
||||
|
||||
//! \~english Returns the double-click interval in milliseconds.
|
||||
//! \~russian Возвращает интервал двойного щелчка в миллисекундах.
|
||||
double doubleClickInterval() const { return dbl_interval; }
|
||||
|
||||
//! \~english Sets the mouse double-click interval in milliseconds.
|
||||
//! \~russian Задает интервал двойного щелчка мыши в миллисекундах.
|
||||
void setDoubleClickInterval(double v) { dbl_interval = v; }
|
||||
|
||||
//! \~english Performs one low-level polling cycle and dispatches decoded input events.
|
||||
//! \~russian Выполняет один цикл низкоуровневого опроса и отправляет декодированные события ввода.
|
||||
void readKeyboard();
|
||||
|
||||
//! \~english Requests listener shutdown and interrupts a pending wait for console input.
|
||||
//! \~russian Запрашивает остановку слушателя и прерывает текущее ожидание консольного ввода.
|
||||
void stop();
|
||||
|
||||
//! \~english Requests shutdown and waits until console capture is restored or the timeout expires.
|
||||
//! \~russian Запрашивает остановку и ждет восстановления режима консоли до истечения таймаута.
|
||||
bool stopAndWait(PISystemTime timeout = {});
|
||||
|
||||
//! Returns if keyboard listening is active (not running!)
|
||||
//! \~english Returns whether low-level console capture is currently enabled.
|
||||
//! \~russian Возвращает, включен ли сейчас низкоуровневый захват консольного ввода.
|
||||
bool isActive() { return is_active; }
|
||||
|
||||
EVENT_HANDLER(void, enableExitCapture) { enableExitCapture('Q'); }
|
||||
EVENT_HANDLER1(void, enableExitCapture, int, key) {
|
||||
exit_enabled = true;
|
||||
exit_key = key;
|
||||
}
|
||||
EVENT_HANDLER(void, disableExitCapture) { exit_enabled = false; }
|
||||
EVENT_HANDLER(void, setActive) { setActive(true); }
|
||||
EVENT_HANDLER1(void, setActive, bool, yes);
|
||||
|
||||
EVENT2(keyPressed, PIKbdListener::KeyEvent, key, void *, data);
|
||||
EVENT2(mouseEvent, PIKbdListener::MouseEvent, mouse, void *, data);
|
||||
EVENT2(wheelEvent, PIKbdListener::WheelEvent, wheel, void *, data);
|
||||
|
||||
//! \handlers
|
||||
//! \{
|
||||
|
||||
//! \fn void enableExitCapture(int key = 'Q')
|
||||
//! \brief Enable exit key "key" awaiting
|
||||
//! \~english Enables capture of exit key \a key.
|
||||
//! \~russian Включает перехват клавиши выхода \a key.
|
||||
EVENT_HANDLER(void, enableExitCapture) { enableExitCapture('Q'); }
|
||||
EVENT_HANDLER1(void, enableExitCapture, int, key) {
|
||||
exit_enabled = true;
|
||||
exit_key = key;
|
||||
}
|
||||
|
||||
//! \fn void disableExitCapture()
|
||||
//! \brief Disable exit key awaiting
|
||||
//! \~english Disables exit key capture.
|
||||
//! \~russian Выключает перехват клавиши выхода.
|
||||
EVENT_HANDLER(void, disableExitCapture) { exit_enabled = false; }
|
||||
|
||||
//! \fn void setActive(bool yes = true)
|
||||
//! \brief Set keyboard listening is active or not
|
||||
//! \~english Enables or disables low-level console input capture.
|
||||
//! \~russian Включает или выключает низкоуровневый захват консольного ввода.
|
||||
EVENT_HANDLER(void, setActive) { setActive(true); }
|
||||
EVENT_HANDLER1(void, setActive, bool, yes);
|
||||
|
||||
//! \}
|
||||
//! \events
|
||||
//! \{
|
||||
|
||||
//! \fn void keyPressed(PIKbdListener::KeyEvent key, void * data)
|
||||
//! \brief Raise on key "key" pressed, "data" is custom data
|
||||
//! \~english Raised when a key event is decoded. \a data is the user data pointer.
|
||||
//! \~russian Вызывается, когда декодировано событие клавиши. \a data содержит указатель на пользовательские данные.
|
||||
EVENT2(keyPressed, PIKbdListener::KeyEvent, key, void *, data);
|
||||
|
||||
//! \fn void mouseEvent(PIKbdListener::MouseEvent mouse, void * data)
|
||||
//! \~english Raised when a mouse button or move event is decoded. \a data is the user data pointer.
|
||||
//! \~russian Вызывается, когда декодировано событие кнопки мыши или перемещения. \a data содержит указатель на пользовательские данные.
|
||||
EVENT2(mouseEvent, PIKbdListener::MouseEvent, mouse, void *, data);
|
||||
|
||||
//! \fn void wheelEvent(PIKbdListener::WheelEvent wheel, void * data)
|
||||
//! \~english Raised when a mouse wheel event is decoded. \a data is the user data pointer.
|
||||
//! \~russian Вызывается, когда декодировано событие колеса мыши. \a data содержит указатель на пользовательские данные.
|
||||
EVENT2(wheelEvent, PIKbdListener::WheelEvent, wheel, void *, data);
|
||||
|
||||
//! \}
|
||||
|
||||
static bool exiting;
|
||||
|
||||
//! \~english Returns the listener instance currently registered by the console subsystem.
|
||||
//! \~russian Возвращает экземпляр слушателя, который сейчас зарегистрирован консольной подсистемой.
|
||||
static PIKbdListener * instance() { return _object; }
|
||||
|
||||
//! \~english Becomes \b true after the configured exit key is captured.
|
||||
//! \~russian Становится \b true после перехвата настроенной клавиши выхода.
|
||||
static bool exiting;
|
||||
|
||||
private:
|
||||
void begin() override;
|
||||
void run() override { readKeyboard(); }
|
||||
@@ -268,16 +340,16 @@ private:
|
||||
|
||||
|
||||
//! \relatesalso PIBinaryStream
|
||||
//! \~english Store operator
|
||||
//! \~russian Оператор сохранения
|
||||
//! \~english Store operator for MouseEvent.
|
||||
//! \~russian Оператор сохранения для MouseEvent.
|
||||
BINARY_STREAM_WRITE(PIKbdListener::MouseEvent) {
|
||||
s << v.x << v.y << v.action << v.buttons << v.modifiers;
|
||||
return s;
|
||||
}
|
||||
|
||||
//! \relatesalso PIBinaryStream
|
||||
//! \~english Restore operator
|
||||
//! \~russian Оператор извлечения
|
||||
//! \~english Restore operator for MouseEvent.
|
||||
//! \~russian Оператор извлечения для MouseEvent.
|
||||
BINARY_STREAM_READ(PIKbdListener::MouseEvent) {
|
||||
s >> v.x >> v.y >> v.action >> v.buttons >> v.modifiers;
|
||||
return s;
|
||||
@@ -285,16 +357,16 @@ BINARY_STREAM_READ(PIKbdListener::MouseEvent) {
|
||||
|
||||
|
||||
//! \relatesalso PIBinaryStream
|
||||
//! \~english Store operator
|
||||
//! \~russian Оператор сохранения
|
||||
//! \~english Store operator for WheelEvent.
|
||||
//! \~russian Оператор сохранения для WheelEvent.
|
||||
BINARY_STREAM_WRITE(PIKbdListener::WheelEvent) {
|
||||
s << (*(PIKbdListener::MouseEvent *)&v) << v.direction;
|
||||
return s;
|
||||
}
|
||||
|
||||
//! \relatesalso PIBinaryStream
|
||||
//! \~english Restore operator
|
||||
//! \~russian Оператор извлечения
|
||||
//! \~english Restore operator for WheelEvent.
|
||||
//! \~russian Оператор извлечения для WheelEvent.
|
||||
BINARY_STREAM_READ(PIKbdListener::WheelEvent) {
|
||||
s >> (*(PIKbdListener::MouseEvent *)&v) >> v.direction;
|
||||
return s;
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/*! \file piscreen.h
|
||||
* \ingroup Console
|
||||
* \~\brief
|
||||
* \~english Console tiling manager
|
||||
* \~russian Консольный тайловый менеджер
|
||||
*/
|
||||
//! \~\file piscreen.h
|
||||
//! \~\ingroup Console
|
||||
//! \~\brief
|
||||
//! \~english Console screen manager and tile host
|
||||
//! \~russian Менеджер консольного экрана и контейнер тайлов
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Console GUI
|
||||
@@ -31,6 +30,10 @@
|
||||
#include "piscreentile.h"
|
||||
|
||||
|
||||
//! \~\ingroup Console
|
||||
//! \~\brief
|
||||
//! \~english Console screen manager with tile layout, drawing, and input routing.
|
||||
//! \~russian Менеджер консольного экрана с раскладкой тайлов, отрисовкой и маршрутизацией ввода.
|
||||
class PIP_CONSOLE_EXPORT PIScreen
|
||||
: public PIThread
|
||||
, public PIScreenTypes::PIScreenBase {
|
||||
@@ -38,69 +41,122 @@ class PIP_CONSOLE_EXPORT PIScreen
|
||||
class SystemConsole;
|
||||
|
||||
public:
|
||||
//! Constructs %PIScreen with key handler "slot" and if "startNow" start it
|
||||
//! \~english Constructs a screen with an internal keyboard listener, optional callback, and auto-start mode.
|
||||
//! \~russian Создает экран со встроенным слушателем клавиатуры, необязательным обратным вызовом и режимом автозапуска.
|
||||
//! \~\details
|
||||
//! \~english Constructs a new PIScreen instance with optional immediate start.
|
||||
//! \~russian Создает новый экземпляр PIScreen с опциональным немедленным запуском.
|
||||
//! \~\param startNow
|
||||
//! \~english Start immediately if true.
|
||||
//! \~russian Запустить немедленно, если true.
|
||||
//! \~\param slot
|
||||
//! \~english Keyboard handler function.
|
||||
//! \~russian Функция обработчика клавиатуры.
|
||||
PIScreen(bool startNow = true, PIKbdListener::KBFunc slot = 0);
|
||||
|
||||
//! \~english Destroys PIScreen and cleans up resources.
|
||||
//! \~russian Уничтожает PIScreen и очищает ресурсы.
|
||||
~PIScreen();
|
||||
|
||||
//! Directly call function from \a PIKbdListener
|
||||
//! \~english Enables catching the exit key (default is 'Q') to stop the screen.
|
||||
//! \~russian Включает захват клавиши выхода (по умолчанию 'Q') для остановки экрана.
|
||||
void enableExitCapture(int key = 'Q') { listener->enableExitCapture(key); }
|
||||
|
||||
//! Directly call function from \a PIKbdListener
|
||||
//! \~english Disables catching the exit key.
|
||||
//! \~russian Отключает захват клавиши выхода.
|
||||
void disableExitCapture() { listener->disableExitCapture(); }
|
||||
|
||||
//! Directly call function from \a PIKbdListener
|
||||
//! \~english Returns whether exit key capture is enabled.
|
||||
//! \~russian Возвращает, включен ли перехват клавиши выхода.
|
||||
bool exitCaptured() const { return listener->exitCaptured(); }
|
||||
|
||||
//! Directly call function from \a PIKbdListener
|
||||
//! \~english Returns the configured exit key.
|
||||
//! \~russian Возвращает настроенную клавишу выхода.
|
||||
int exitKey() const { return listener->exitKey(); }
|
||||
|
||||
//! \~english Returns the current console width in characters.
|
||||
//! \~russian Возвращает текущую ширину консоли в символах.
|
||||
int windowWidth() const { return console.width; }
|
||||
|
||||
//! \~english Returns the current console height in characters.
|
||||
//! \~russian Возвращает текущую высоту консоли в символах.
|
||||
int windowHeight() const { return console.height; }
|
||||
|
||||
//! \~english Returns whether mouse hit-testing and routing are enabled.
|
||||
//! \~russian Возвращает, включены ли проверка попадания и маршрутизация событий мыши.
|
||||
bool isMouseEnabled() const { return mouse_; }
|
||||
|
||||
//! \~english Enables or disables mouse routing and tile hit-testing.
|
||||
//! \~russian Включает или выключает маршрутизацию мыши и проверку попадания по тайлам.
|
||||
void setMouseEnabled(bool on);
|
||||
|
||||
//! \~english Returns the root tile covering the whole screen.
|
||||
//! \~russian Возвращает корневой тайл, покрывающий весь экран.
|
||||
PIScreenTile * rootTile() { return &root; }
|
||||
|
||||
//! \~english Searches the root tile subtree by object name.
|
||||
//! \~russian Ищет тайл по имени объекта в поддереве корневого тайла.
|
||||
//! \~\return
|
||||
//! \~english Tile pointer if found, otherwise nullptr.
|
||||
//! \~russian Указатель на тайл, если найден, иначе nullptr.
|
||||
PIScreenTile * tileByName(const PIString & name);
|
||||
|
||||
//! \~english Sets a dialog tile drawn above the root tree, centered on screen, and focused first. Pass \c nullptr to remove it.
|
||||
//! \~russian Задает диалоговый тайл, рисуемый поверх корневого дерева, центрируемый на экране и первым получающий фокус. Передайте \c
|
||||
//! nullptr, чтобы убрать его.
|
||||
void setDialogTile(PIScreenTile * t);
|
||||
|
||||
//! \~english Returns the currently active dialog tile or \c nullptr.
|
||||
//! \~russian Возвращает активный диалоговый тайл или \c nullptr.
|
||||
PIScreenTile * dialogTile() const { return tile_dialog; }
|
||||
|
||||
//! \~english Returns the drawer used to fill the off-screen cell buffer for the next frame.
|
||||
//! \~russian Возвращает рисовальщик, используемый для заполнения внеэкранного буфера ячеек следующего кадра.
|
||||
PIScreenDrawer * drawer() { return &drawer_; }
|
||||
|
||||
//! \~english Clears the off-screen cell buffer. The terminal is updated on the next draw cycle.
|
||||
//! \~russian Очищает внеэкранный буфер ячеек. Терминал обновится на следующем цикле отрисовки.
|
||||
void clear() { drawer_.clear(); }
|
||||
|
||||
//! \~english Resizes the internal console buffers used for subsequent frames.
|
||||
//! \~russian Изменяет размер внутренних консольных буферов, используемых в следующих кадрах.
|
||||
void resize(int w, int h) { console.resize(w, h); }
|
||||
|
||||
EVENT_HANDLER0(void, waitForFinish);
|
||||
EVENT_HANDLER0(void, start) { start(false); }
|
||||
EVENT_HANDLER1(void, start, bool, wait);
|
||||
EVENT_HANDLER0(void, stop) { stop(false); }
|
||||
EVENT_HANDLER1(void, stop, bool, clear);
|
||||
|
||||
EVENT2(keyPressed, PIKbdListener::KeyEvent, key, void *, data);
|
||||
EVENT2(tileEvent, PIScreenTile *, tile, PIScreenTypes::TileEvent, e);
|
||||
|
||||
//! \handlers
|
||||
//! \{
|
||||
|
||||
//! \fn void waitForFinish()
|
||||
//! \brief block until finished (exit key will be pressed)
|
||||
//! \~english Blocks until the captured exit key is pressed and then stops the screen.
|
||||
//! \~russian Блокирует выполнение, пока не будет нажата перехватываемая клавиша выхода, затем останавливает экран.
|
||||
EVENT_HANDLER0(void, waitForFinish);
|
||||
|
||||
//! \fn void start(bool wait = false)
|
||||
//! \brief Start console output and if "wait" block until finished (exit key will be pressed)
|
||||
//! \~english Starts the screen thread and optionally waits until the configured exit key is captured.
|
||||
//! \~russian Запускает поток экрана и при необходимости ждет, пока не будет перехвачена настроенная клавиша выхода.
|
||||
EVENT_HANDLER0(void, start) { start(false); }
|
||||
EVENT_HANDLER1(void, start, bool, wait);
|
||||
|
||||
//! \fn void stop(bool clear = false)
|
||||
//! \brief Stop console output and if "clear" clear the screen
|
||||
//! \~english Stops the screen thread, restores console state, and optionally clears the terminal.
|
||||
//! \~russian Останавливает поток экрана, восстанавливает состояние консоли и при необходимости очищает терминал.
|
||||
EVENT_HANDLER0(void, stop) { stop(false); }
|
||||
EVENT_HANDLER1(void, stop, bool, clear);
|
||||
|
||||
//! \}
|
||||
//! \events
|
||||
//! \{
|
||||
|
||||
//! \fn void keyPressed(PIKbdListener::KeyEvent key, void * data)
|
||||
//! \brief Raise on key "key" pressed, "data" is pointer to %PIConsole object
|
||||
//! \~english Raised when a key was not consumed by focus navigation or the focused tile. \a data is the screen user data pointer.
|
||||
//! \~russian Вызывается, когда клавиша не была поглощена навигацией фокуса или тайлом с фокусом. \a data содержит пользовательский
|
||||
//! указатель экрана.
|
||||
EVENT2(keyPressed, PIKbdListener::KeyEvent, key, void *, data);
|
||||
|
||||
//! \fn void tileEvent(PIScreenTile * tile, PIScreenTypes::TileEvent e)
|
||||
//! \brief Raise on some event "e" from tile "tile"
|
||||
//! \~english Raised when a tile reports a custom event \a e.
|
||||
//! \~russian Вызывается, когда тайл сообщает пользовательское событие \a e.
|
||||
EVENT2(tileEvent, PIScreenTile *, tile, PIScreenTypes::TileEvent, e);
|
||||
|
||||
//! \}
|
||||
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
/*! \file piscreenconsole.h
|
||||
* \ingroup Console
|
||||
* \~\brief
|
||||
* \~english Tile for PIScreen with PIConsole API
|
||||
* \~russian Тайл для PIScreen с API PIConsole
|
||||
*/
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Tile for PIScreen with PIConsole API
|
||||
Andrey Bychkov work.a.b@yandex.ru
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Lesser General Public License as published by
|
||||
the Free Software Foundation, either version 3 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 Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef PISCREENCONSOLE_H
|
||||
#define PISCREENCONSOLE_H
|
||||
|
||||
#include "pip_console_export.h"
|
||||
#include "piscreentiles.h"
|
||||
|
||||
/// NOTE: incomplete class
|
||||
/// TODO: write TileVars
|
||||
|
||||
class PIP_CONSOLE_EXPORT TileVars: public PIScreenTile {
|
||||
public:
|
||||
TileVars(const PIString & n = PIString());
|
||||
|
||||
protected:
|
||||
struct PIP_CONSOLE_EXPORT Variable {
|
||||
Variable() {
|
||||
nx = ny = type = offset = bitFrom = bitCount = size = 0;
|
||||
format = PIScreenTypes::CellFormat();
|
||||
ptr = 0;
|
||||
}
|
||||
bool isEmpty() const { return (ptr == 0); }
|
||||
PIString name;
|
||||
PIScreenTypes::CellFormat format;
|
||||
int nx;
|
||||
int ny;
|
||||
int type;
|
||||
int offset;
|
||||
int bitFrom;
|
||||
int bitCount;
|
||||
int size;
|
||||
const void * ptr;
|
||||
/*void operator =(const Variable & src) {
|
||||
name = src.name;
|
||||
format = src.format;
|
||||
nx = src.nx;
|
||||
ny = src.ny;
|
||||
type = src.type;
|
||||
offset = src.offset;
|
||||
bitFrom = src.bitFrom;
|
||||
bitCount = src.bitCount;
|
||||
size = src.size;
|
||||
ptr = src.ptr;
|
||||
}*/
|
||||
};
|
||||
PIVector<Variable> variables;
|
||||
PIScreenTypes::Alignment alignment;
|
||||
void sizeHint(int & w, int & h) const override;
|
||||
void drawEvent(PIScreenDrawer * d) override;
|
||||
};
|
||||
|
||||
|
||||
class PIP_CONSOLE_EXPORT PIScreenConsoleTile: public PIScreenTile {
|
||||
public:
|
||||
PIScreenConsoleTile();
|
||||
};
|
||||
|
||||
#endif // PISCREENCONSOLE_H
|
||||
@@ -1,9 +1,8 @@
|
||||
/*! \file piscreendrawer.h
|
||||
* \ingroup Console
|
||||
* \~\brief
|
||||
* \~english Drawer for PIScreen
|
||||
* \~russian Отрисовщик для PIScreen
|
||||
*/
|
||||
//! \~\file piscreendrawer.h
|
||||
//! \~\ingroup Console
|
||||
//! \~\brief
|
||||
//! \~english Drawing helpers for %PIScreen cell buffers
|
||||
//! \~russian Вспомогательные средства рисования для буферов ячеек %PIScreen
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Drawer for PIScreen
|
||||
@@ -30,31 +29,54 @@
|
||||
#include "piscreentypes.h"
|
||||
#include "pistring.h"
|
||||
|
||||
//! \~\ingroup Console
|
||||
//! \~\brief
|
||||
//! \~english Helper that draws primitives and text into a %PIScreen cell buffer.
|
||||
//! \~russian Вспомогательный класс для рисования примитивов и текста в буфере ячеек %PIScreen.
|
||||
//! \~\details
|
||||
//! \~english Provides methods for drawing primitives such as pixels, lines, rectangles, and text on console screen.
|
||||
//! \~russian Предоставляет методы для рисования примитивов, таких как пиксели, линии, прямоугольники и текст на консольном экране.
|
||||
class PIP_CONSOLE_EXPORT PIScreenDrawer {
|
||||
friend class PIScreen;
|
||||
PIScreenDrawer(PIVector<PIVector<PIScreenTypes::Cell>> & c);
|
||||
|
||||
public:
|
||||
//! \~english Predefined pseudographic and widget-state symbols.
|
||||
//! \~russian Предопределенные псевдографические символы и символы состояний виджетов.
|
||||
//! \~\details
|
||||
//! \~english Defines available characters for drawing ASCII art primitives.
|
||||
//! \~russian Определяет доступные символы для рисования ASCII-арта примитивов.
|
||||
enum ArtChar {
|
||||
LineVertical = 1,
|
||||
LineHorizontal,
|
||||
Cross,
|
||||
CornerTopLeft,
|
||||
CornerTopRight,
|
||||
CornerBottomLeft,
|
||||
CornerBottomRight,
|
||||
Unchecked,
|
||||
Checked
|
||||
LineVertical = 1 /** \~english Vertical line symbol. \~russian Символ вертикальной линии. */,
|
||||
LineHorizontal /** \~english Horizontal line symbol. \~russian Символ горизонтальной линии. */,
|
||||
Cross /** \~english Line intersection symbol. \~russian Символ пересечения линий. */,
|
||||
CornerTopLeft /** \~english Top-left frame corner. \~russian Левый верхний угол рамки. */,
|
||||
CornerTopRight /** \~english Top-right frame corner. \~russian Правый верхний угол рамки. */,
|
||||
CornerBottomLeft /** \~english Bottom-left frame corner. \~russian Левый нижний угол рамки. */,
|
||||
CornerBottomRight /** \~english Bottom-right frame corner. \~russian Правый нижний угол рамки. */,
|
||||
Unchecked /** \~english Unchecked box symbol. \~russian Символ неотмеченного флажка. */,
|
||||
Checked /** \~english Checked box symbol. \~russian Символ отмеченного флажка. */
|
||||
};
|
||||
|
||||
//! \~english Clears the whole target buffer.
|
||||
//! \~russian Очищает весь целевой буфер.
|
||||
void clear();
|
||||
|
||||
//! \~english Clears a rectangular area in the target buffer with spaces.
|
||||
//! \~russian Очищает прямоугольную область целевого буфера пробелами.
|
||||
void clearRect(int x0, int y0, int x1, int y1) { fillRect(x0, y0, x1, y1, ' '); }
|
||||
|
||||
//! \~english Draws one cell at position `(x, y)`.
|
||||
//! \~russian Рисует одну ячейку в позиции `(x, y)`.
|
||||
void drawPixel(int x,
|
||||
int y,
|
||||
const PIChar & c,
|
||||
PIScreenTypes::Color col_char = PIScreenTypes::Default,
|
||||
PIScreenTypes::Color col_back = PIScreenTypes::Default,
|
||||
PIScreenTypes::CharFlags flags_char = 0);
|
||||
|
||||
//! \~english Draws a line between two points.
|
||||
//! \~russian Рисует линию между двумя точками.
|
||||
void drawLine(int x0,
|
||||
int y0,
|
||||
int x1,
|
||||
@@ -63,6 +85,9 @@ public:
|
||||
PIScreenTypes::Color col_char = PIScreenTypes::Default,
|
||||
PIScreenTypes::Color col_back = PIScreenTypes::Default,
|
||||
PIScreenTypes::CharFlags flags_char = 0);
|
||||
|
||||
//! \~english Draws a rectangular outline with the specified symbol.
|
||||
//! \~russian Рисует контур прямоугольника указанным символом.
|
||||
void drawRect(int x0,
|
||||
int y0,
|
||||
int x1,
|
||||
@@ -71,6 +96,9 @@ public:
|
||||
PIScreenTypes::Color col_char = PIScreenTypes::Default,
|
||||
PIScreenTypes::Color col_back = PIScreenTypes::Default,
|
||||
PIScreenTypes::CharFlags flags_char = 0);
|
||||
|
||||
//! \~english Draws a frame using predefined art symbols.
|
||||
//! \~russian Рисует рамку предопределенными псевдографическими символами.
|
||||
void drawFrame(int x0,
|
||||
int y0,
|
||||
int x1,
|
||||
@@ -78,12 +106,18 @@ public:
|
||||
PIScreenTypes::Color col_char = PIScreenTypes::Default,
|
||||
PIScreenTypes::Color col_back = PIScreenTypes::Default,
|
||||
PIScreenTypes::CharFlags flags_char = 0);
|
||||
|
||||
//! \~english Draws text starting at `(x, y)`.
|
||||
//! \~russian Рисует текст, начиная с позиции `(x, y)`.
|
||||
void drawText(int x,
|
||||
int y,
|
||||
const PIString & s,
|
||||
PIScreenTypes::Color col_char = PIScreenTypes::Default,
|
||||
PIScreenTypes::Color col_back = PIScreenTypes::Transparent,
|
||||
PIScreenTypes::CharFlags flags_char = 0);
|
||||
|
||||
//! \~english Fills a rectangular area with one symbol and cell format.
|
||||
//! \~russian Заполняет прямоугольную область одним символом и форматом ячейки.
|
||||
void fillRect(int x0,
|
||||
int y0,
|
||||
int x1,
|
||||
@@ -92,10 +126,17 @@ public:
|
||||
PIScreenTypes::Color col_char = PIScreenTypes::Default,
|
||||
PIScreenTypes::Color col_back = PIScreenTypes::Default,
|
||||
PIScreenTypes::CharFlags flags_char = 0);
|
||||
|
||||
//! \~english Copies a cell matrix into a rectangular area.
|
||||
//! \~russian Копирует матрицу ячеек в прямоугольную область.
|
||||
void fillRect(int x0, int y0, int x1, int y1, PIVector<PIVector<PIScreenTypes::Cell>> & content);
|
||||
|
||||
//! \~english Returns a predefined art symbol.
|
||||
//! \~russian Возвращает предопределенный псевдографический символ.
|
||||
PIChar artChar(const ArtChar type) const { return arts_.value(type, PIChar(' ')); }
|
||||
|
||||
//! \~english Fills an arbitrary cell buffer with default cells.
|
||||
//! \~russian Заполняет произвольный буфер ячеек значениями по умолчанию.
|
||||
static void clear(PIVector<PIVector<PIScreenTypes::Cell>> & cells);
|
||||
|
||||
private:
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/*! \file piscreentile.h
|
||||
* \ingroup Console
|
||||
* \~\brief
|
||||
* \~english Basic PIScreen tile
|
||||
* \~russian Базовый тайл для PIScreen
|
||||
*/
|
||||
//! \~\file piscreentile.h
|
||||
//! \~\ingroup Console
|
||||
//! \brief
|
||||
//! \~english Basic PIScreen tile
|
||||
//! \~russian Базовый тайл для PIScreen
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Basic PIScreen tile
|
||||
@@ -32,27 +31,74 @@
|
||||
|
||||
class PIScreenDrawer;
|
||||
|
||||
//! \~\ingroup Console
|
||||
//! \~\brief
|
||||
//! \~english Base tile in the console screen tree.
|
||||
//! \~russian Базовый тайл в дереве консольного экрана.
|
||||
//! \details
|
||||
//! \~english Base class for all screen tiles providing layout and event handling.
|
||||
//! \~russian Базовый класс для всех экранных тайлов, обеспечивающий компоновку и обработку событий.
|
||||
class PIP_CONSOLE_EXPORT PIScreenTile: public PIObject {
|
||||
friend class PIScreen;
|
||||
PIOBJECT_SUBCLASS(PIScreenTile, PIObject);
|
||||
|
||||
public:
|
||||
//! \~english Constructs a tile with name, child layout direction, and size policy.
|
||||
//! \~russian Создает тайл с именем, направлением раскладки дочерних элементов и политикой размера.
|
||||
PIScreenTile(const PIString & n = PIString(),
|
||||
PIScreenTypes::Direction d = PIScreenTypes::Vertical,
|
||||
PIScreenTypes::SizePolicy p = PIScreenTypes::Preferred);
|
||||
|
||||
//! \~english Destroys the tile and its owned child tiles.
|
||||
//! \~russian Уничтожает тайл и принадлежащие ему дочерние тайлы.
|
||||
virtual ~PIScreenTile();
|
||||
|
||||
//! \~english Adds child tile \a t, makes this tile its parent, and attaches the subtree to the same screen bridge.
|
||||
//! \~russian Добавляет дочерний тайл \a t, делает этот тайл его родителем и подключает поддерево к тому же экранному мосту.
|
||||
void addTile(PIScreenTile * t);
|
||||
|
||||
//! \~english Detaches child tile \a t without deleting it and removes its screen association.
|
||||
//! \~russian Отсоединяет дочерний тайл \a t без удаления и снимает его связь с экраном.
|
||||
void takeTile(PIScreenTile * t);
|
||||
|
||||
//! \~english Removes and deletes child tile \a t.
|
||||
//! \~russian Удаляет дочерний тайл \a t и уничтожает его.
|
||||
void removeTile(PIScreenTile * t);
|
||||
|
||||
//! \~english Returns the parent tile or \c nullptr for the root.
|
||||
//! \~russian Возвращает родительский тайл или \c nullptr для корня.
|
||||
PIScreenTile * parentTile() const { return parent; }
|
||||
|
||||
//! \~english Returns all descendant tiles. Hidden tiles can be skipped with \a only_visible.
|
||||
//! \~russian Возвращает все дочерние тайлы по дереву. Скрытые тайлы можно пропустить через \a only_visible.
|
||||
PIVector<PIScreenTile *> children(bool only_visible = false);
|
||||
|
||||
//! \~english Returns the first visible direct child covering screen point \a x, \a y.
|
||||
//! \~russian Возвращает первый видимый прямой дочерний тайл, покрывающий экранную точку \a x, \a y.
|
||||
PIScreenTile * childUnderMouse(int x, int y);
|
||||
|
||||
//! \~english Makes the tile visible for subsequent layout, hit-testing, and drawing passes.
|
||||
//! \~russian Делает тайл видимым для последующих проходов компоновки, проверки попадания и отрисовки.
|
||||
void show() { visible = true; }
|
||||
|
||||
//! \~english Hides the tile from layout, hit-testing, and drawing passes.
|
||||
//! \~russian Скрывает тайл из проходов компоновки, проверки попадания и отрисовки.
|
||||
void hide() { visible = false; }
|
||||
|
||||
//! \~english Requests focus for this tile if it is attached to a screen and allows focus.
|
||||
//! \~russian Запрашивает фокус для этого тайла, если он подключен к экрану и допускает получение фокуса.
|
||||
void setFocus();
|
||||
|
||||
//! \~english Returns whether this tile currently owns focus.
|
||||
//! \~russian Возвращает, принадлежит ли этому тайлу текущий фокус.
|
||||
bool hasFocus() const { return has_focus; }
|
||||
|
||||
//! \~english Sets all margins to \a m cells.
|
||||
//! \~russian Устанавливает все отступы в \a m ячеек.
|
||||
void setMargins(int m) { marginLeft = marginRight = marginTop = marginBottom = m; }
|
||||
|
||||
//! \~english Sets left, right, top, and bottom margins in cells.
|
||||
//! \~russian Устанавливает левый, правый, верхний и нижний отступы в ячейках.
|
||||
void setMargins(int l, int r, int t, int b) {
|
||||
marginLeft = l;
|
||||
marginRight = r;
|
||||
@@ -60,52 +106,129 @@ public:
|
||||
marginBottom = b;
|
||||
}
|
||||
|
||||
//! \~english Returns the tile X coordinate in screen space.
|
||||
//! \~russian Возвращает координату X тайла в экранном пространстве.
|
||||
int x() const { return x_; }
|
||||
|
||||
//! \~english Returns the tile Y coordinate in screen space.
|
||||
//! \~russian Возвращает координату Y тайла в экранном пространстве.
|
||||
int y() const { return y_; }
|
||||
|
||||
//! \~english Returns the current tile width in cells.
|
||||
//! \~russian Возвращает текущую ширину тайла в ячейках.
|
||||
int width() const { return width_; }
|
||||
|
||||
//! \~english Returns the current tile height in cells.
|
||||
//! \~russian Возвращает текущую высоту тайла в ячейках.
|
||||
int height() const { return height_; }
|
||||
|
||||
//! \~english Direction used to lay out child tiles.
|
||||
//! \~russian Направление раскладки дочерних тайлов.
|
||||
PIScreenTypes::Direction direction;
|
||||
|
||||
//! \~english Size policy used by the parent during layout.
|
||||
//! \~russian Политика размера, используемая родителем при компоновке.
|
||||
PIScreenTypes::SizePolicy size_policy;
|
||||
|
||||
//! \~english Focus and navigation flags for the tile.
|
||||
//! \~russian Флаги фокуса и навигации для тайла.
|
||||
PIScreenTypes::FocusFlags focus_flags;
|
||||
|
||||
//! \~english Background format used to prefill the tile area before drawing.
|
||||
//! \~russian Формат фона, которым предварительно заполняется область тайла перед отрисовкой.
|
||||
PIScreenTypes::CellFormat back_format;
|
||||
|
||||
//! \~english Background symbol used to prefill the tile area before drawing.
|
||||
//! \~russian Символ фона, которым предварительно заполняется область тайла перед отрисовкой.
|
||||
PIChar back_symbol;
|
||||
|
||||
//! \~english Minimum size limits accepted during layout.
|
||||
//! \~russian Минимальные ограничения размера, допускаемые при компоновке.
|
||||
int minimumWidth, minimumHeight;
|
||||
|
||||
//! \~english Maximum size limits accepted during layout.
|
||||
//! \~russian Максимальные ограничения размера, допускаемые при компоновке.
|
||||
int maximumWidth, maximumHeight;
|
||||
|
||||
//! \~english Outer margins in cells.
|
||||
//! \~russian Внешние отступы в ячейках.
|
||||
int marginLeft, marginRight, marginTop, marginBottom;
|
||||
|
||||
//! \~english Spacing between visible child tiles in cells.
|
||||
//! \~russian Интервал между видимыми дочерними тайлами в ячейках.
|
||||
int spacing;
|
||||
|
||||
//! \~english Whether the tile participates in layout, hit-testing, and drawing.
|
||||
//! \~russian Участвует ли тайл в компоновке, проверке попадания и отрисовке.
|
||||
bool visible;
|
||||
|
||||
protected:
|
||||
//! Returns desired tile size in "w" and "h"
|
||||
//! \~english Returns the preferred tile size in \a w and \a h. The base implementation derives it from visible children, spacing, and margins.
|
||||
//! \~russian Возвращает предпочтительный размер тайла в \a w и \a h. Базовая реализация вычисляет его по видимым дочерним тайлам, интервалам и отступам.
|
||||
virtual void sizeHint(int & w, int & h) const;
|
||||
|
||||
//! Tile has been resized to "w"x"h"
|
||||
//! \~english Called after the tile size changes to \a w by \a h during layout.
|
||||
//! \~russian Вызывается после изменения размера тайла до \a w на \a h во время компоновки.
|
||||
virtual void resizeEvent(int w, int h) {}
|
||||
|
||||
//! Draw tile with drawer "d" in world-space coordinates
|
||||
//! \~english Draws the tile with drawer \a d in screen coordinates.
|
||||
//! \~russian Отрисовывает тайл через рисовальщик \a d в экранных координатах.
|
||||
virtual void drawEvent(PIScreenDrawer * d) {}
|
||||
|
||||
//! Return "true" if you process key
|
||||
//! \~english Handles keyboard input and returns \b true when the event is consumed.
|
||||
//! \~russian Обрабатывает клавиатурный ввод и возвращает \b true, если событие поглощено.
|
||||
virtual bool keyEvent(PIKbdListener::KeyEvent key) { return false; }
|
||||
|
||||
//! Return "true" if you process event
|
||||
//! \~english Handles mouse input and returns \b true when the event is consumed.
|
||||
//! \~russian Обрабатывает событие мыши и возвращает \b true, если событие поглощено.
|
||||
virtual bool mouseEvent(PIKbdListener::MouseEvent me) { return false; }
|
||||
|
||||
//! Return "true" if you process wheel
|
||||
//! \~english Handles mouse wheel input and returns \b true when the event is consumed.
|
||||
//! \~russian Обрабатывает колесо мыши и возвращает \b true, если событие поглощено.
|
||||
virtual bool wheelEvent(PIKbdListener::WheelEvent we) { return false; }
|
||||
|
||||
//! \~english Raises tile event
|
||||
//! \~russian Вызывает событие тайла
|
||||
void raiseEvent(PIScreenTypes::TileEvent e);
|
||||
|
||||
//! \~english Sets screen reference
|
||||
//! \~russian Устанавливает ссылку на экран
|
||||
void setScreen(PIScreenTypes::PIScreenBase * s);
|
||||
|
||||
//! \~english Deletes all owned child tiles.
|
||||
//! \~russian Удаляет все принадлежащие дочерние тайлы.
|
||||
void deleteChildren();
|
||||
|
||||
//! \~english Draws background, tile contents, and then child tiles.
|
||||
//! \~russian Отрисовывает фон, содержимое тайла и затем дочерние тайлы.
|
||||
void drawEventInternal(PIScreenDrawer * d);
|
||||
|
||||
//! \~english Recomputes child geometry according to size hints, margins, and policies.
|
||||
//! \~russian Пересчитывает геометрию дочерних тайлов по предпочтительным размерам, отступам и политикам.
|
||||
void layout();
|
||||
|
||||
//! \~english Returns whether this tile should participate in automatic layout. Tiles with policy \a PIScreenTypes::Ignore are skipped.
|
||||
//! \~russian Возвращает, должен ли тайл участвовать в автоматической компоновке. Тайлы с политикой \a PIScreenTypes::Ignore пропускаются.
|
||||
bool needLayout() { return size_policy != PIScreenTypes::Ignore; }
|
||||
|
||||
//! \~english Owned direct child tiles.
|
||||
//! \~russian Принадлежащие прямые дочерние тайлы.
|
||||
PIVector<PIScreenTile *> tiles;
|
||||
|
||||
//! \~english Parent tile or \c nullptr for the root or detached tiles.
|
||||
//! \~russian Родительский тайл или \c nullptr для корня и отсоединенных тайлов.
|
||||
PIScreenTile * parent;
|
||||
|
||||
//! \~english Screen pointer, receiving tile notifications.
|
||||
//! \~russian Ссылка на экран, принимающий уведомления от тайла.
|
||||
PIScreenTypes::PIScreenBase * screen;
|
||||
|
||||
//! \~english Tile position and size in screen cells.
|
||||
//! \~russian Положение и размер тайла в экранных ячейках.
|
||||
int x_, y_, width_, height_;
|
||||
|
||||
//! \~english Whether this tile currently owns focus.
|
||||
//! \~russian Принадлежит ли этому тайлу текущий фокус.
|
||||
bool has_focus;
|
||||
|
||||
private:
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
/*! \file piscreentiles.h
|
||||
* \ingroup Console
|
||||
* \~\brief
|
||||
* \~english Various tiles for PIScreen
|
||||
* \~russian Различные тайлы для PIScreen
|
||||
*/
|
||||
//! \~\file piscreentiles.h
|
||||
//! \~\ingroup Console
|
||||
//! \brief
|
||||
//! \~english Various tiles for PIScreen
|
||||
//! \~russian Различные тайлы для PIScreen
|
||||
//! \details
|
||||
//! \~english Provides ready-to-use tile implementations for common UI elements.
|
||||
//! \~russian Обеспечивает готовые к использованию реализации тайлов для общих элементов UI.
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Various tiles for PIScreen
|
||||
@@ -30,15 +32,36 @@
|
||||
#include "piscreentile.h"
|
||||
|
||||
|
||||
//! \~\ingroup Console
|
||||
//! \~\brief
|
||||
//! \~english Simple text tile with per-row formatting.
|
||||
//! \~russian Простой текстовый тайл с форматированием по строкам.
|
||||
class PIP_CONSOLE_EXPORT TileSimple: public PIScreenTile {
|
||||
PIOBJECT_SUBCLASS(TileSimple, PIScreenTile);
|
||||
|
||||
public:
|
||||
//! \~english Row text with cell format.
|
||||
//! \~russian Текст строки с форматом ячеек.
|
||||
typedef PIPair<PIString, PIScreenTypes::CellFormat> Row;
|
||||
|
||||
//! \~english Constructs an empty text tile.
|
||||
//! \~russian Создает пустой текстовый тайл.
|
||||
TileSimple(const PIString & n = PIString());
|
||||
|
||||
//! \~english Constructs a text tile with one row.
|
||||
//! \~russian Создает текстовый тайл с одной строкой.
|
||||
TileSimple(const Row & r);
|
||||
|
||||
//! \~english Destroys the text tile.
|
||||
//! \~russian Уничтожает текстовый тайл.
|
||||
virtual ~TileSimple() {}
|
||||
|
||||
//! \~english Rows displayed by the tile.
|
||||
//! \~russian Строки, отображаемые тайлом.
|
||||
PIVector<Row> content;
|
||||
|
||||
//! \~english Horizontal text alignment inside the tile.
|
||||
//! \~russian Горизонтальное выравнивание текста внутри тайла.
|
||||
PIScreenTypes::Alignment alignment;
|
||||
|
||||
protected:
|
||||
@@ -49,19 +72,49 @@ protected:
|
||||
|
||||
class TileList;
|
||||
|
||||
//! \~\ingroup Console
|
||||
//! \~\brief
|
||||
//! \~english Scroll bar tile used by list-like widgets.
|
||||
//! \~russian Тайловая полоса прокрутки для списковых виджетов.
|
||||
class PIP_CONSOLE_EXPORT TileScrollBar: public PIScreenTile {
|
||||
PIOBJECT_SUBCLASS(TileScrollBar, PIScreenTile);
|
||||
friend class TileList;
|
||||
|
||||
public:
|
||||
//! \~english Constructs a scroll bar tile.
|
||||
//! \~russian Создает тайл полосы прокрутки.
|
||||
TileScrollBar(const PIString & n = PIString());
|
||||
|
||||
//! \~english Destroys the scroll bar tile.
|
||||
//! \~russian Уничтожает тайл полосы прокрутки.
|
||||
virtual ~TileScrollBar() {}
|
||||
|
||||
//! \~english Sets the minimum scroll value.
|
||||
//! \~russian Устанавливает минимальное значение прокрутки.
|
||||
void setMinimum(int v);
|
||||
|
||||
//! \~english Sets the maximum scroll value.
|
||||
//! \~russian Устанавливает максимальное значение прокрутки.
|
||||
void setMaximum(int v);
|
||||
|
||||
//! \~english Sets the current scroll value.
|
||||
//! \~russian Устанавливает текущее значение прокрутки.
|
||||
void setValue(int v);
|
||||
|
||||
//! \~english Returns the minimum scroll value.
|
||||
//! \~russian Возвращает минимальное значение прокрутки.
|
||||
int minimum() const { return minimum_; }
|
||||
|
||||
//! \~english Returns the maximum scroll value.
|
||||
//! \~russian Возвращает максимальное значение прокрутки.
|
||||
int maximum() const { return maximum_; }
|
||||
|
||||
//! \~english Returns the current scroll value.
|
||||
//! \~russian Возвращает текущее значение прокрутки.
|
||||
int value() const { return value_; }
|
||||
|
||||
//! \~english Thickness of the drawn bar in cells, perpendicular to the scroll direction.
|
||||
//! \~russian Толщина отрисовываемой полосы в ячейках поперек направления прокрутки.
|
||||
int thickness;
|
||||
|
||||
protected:
|
||||
@@ -74,29 +127,68 @@ protected:
|
||||
};
|
||||
|
||||
|
||||
//! \~\ingroup Console
|
||||
//! \~\brief
|
||||
//! \~english Scrollable list tile with optional row selection.
|
||||
//! \~russian Прокручиваемый тайл списка с необязательным выбором строк.
|
||||
class PIP_CONSOLE_EXPORT TileList: public PIScreenTile {
|
||||
PIOBJECT_SUBCLASS(TileList, PIScreenTile);
|
||||
|
||||
public:
|
||||
//! \~english Selection policy for list rows.
|
||||
//! \~russian Режим выбора строк списка.
|
||||
enum SelectionMode {
|
||||
NoSelection,
|
||||
SingleSelection,
|
||||
MultiSelection
|
||||
};
|
||||
enum EventType {
|
||||
SelectionChanged,
|
||||
RowPressed
|
||||
NoSelection /** \~english Rows are not selectable. \~russian Выбор строк отключен. */,
|
||||
SingleSelection /** \~english At most one row can be selected. \~russian Можно выбрать не более одной строки. */,
|
||||
MultiSelection /** \~english Multiple rows can be selected. \~russian Можно выбрать несколько строк. */
|
||||
};
|
||||
|
||||
//! \~english Events emitted by the list tile.
|
||||
//! \~russian События, генерируемые тайлом списка.
|
||||
enum EventType {
|
||||
SelectionChanged /** \~english Selection set changed. \~russian Изменился набор выбранных строк. */,
|
||||
RowPressed /** \~english Current row was activated; event data stores the row index. \~russian Текущая строка была активирована; данные события содержат индекс строки. */
|
||||
};
|
||||
|
||||
//! \~english Constructs a list tile with the specified selection mode.
|
||||
//! \~russian Создает тайл списка с указанным режимом выбора.
|
||||
TileList(const PIString & n = PIString(), SelectionMode sm = NoSelection);
|
||||
|
||||
//! \~english Destroys the list tile.
|
||||
//! \~russian Уничтожает тайл списка.
|
||||
virtual ~TileList() {}
|
||||
|
||||
//! \~english Row text with cell format.
|
||||
//! \~russian Текст строки с форматом ячеек.
|
||||
typedef PIPair<PIString, PIScreenTypes::CellFormat> Row;
|
||||
|
||||
//! \~english Rows displayed by the list.
|
||||
//! \~russian Строки, отображаемые списком.
|
||||
PIDeque<Row> content;
|
||||
|
||||
//! \~english Alignment used to draw row text.
|
||||
//! \~russian Выравнивание, используемое при рисовании текста строк.
|
||||
PIScreenTypes::Alignment alignment;
|
||||
|
||||
//! \~english Active row selection mode.
|
||||
//! \~russian Текущий режим выбора строк.
|
||||
SelectionMode selection_mode;
|
||||
|
||||
//! \~english Indexes of selected rows.
|
||||
//! \~russian Индексы выбранных строк.
|
||||
PISet<int> selected;
|
||||
int lhei, cur, offset;
|
||||
|
||||
//! \~english Cached count of visible content rows between the top and bottom scroll markers.
|
||||
//! \~russian Кэшированное количество видимых строк содержимого между верхней и нижней метками прокрутки.
|
||||
int lhei;
|
||||
|
||||
//! \~english Index of the current row used for focus and activation.
|
||||
//! \~russian Индекс текущей строки, используемой для фокуса и активации.
|
||||
int cur;
|
||||
|
||||
//! \~english Index of the first row currently visible in the viewport.
|
||||
//! \~russian Индекс первой строки, видимой в текущей области просмотра.
|
||||
int offset;
|
||||
|
||||
protected:
|
||||
void sizeHint(int & w, int & h) const override;
|
||||
@@ -110,16 +202,34 @@ protected:
|
||||
};
|
||||
|
||||
|
||||
//! \~\ingroup Console
|
||||
//! \~\brief
|
||||
//! \~english Push button tile.
|
||||
//! \~russian Тайл кнопки.
|
||||
class PIP_CONSOLE_EXPORT TileButton: public PIScreenTile {
|
||||
PIOBJECT_SUBCLASS(TileButton, PIScreenTile);
|
||||
|
||||
public:
|
||||
//! \~english Constructs a button tile.
|
||||
//! \~russian Создает тайл кнопки.
|
||||
TileButton(const PIString & n = PIString());
|
||||
|
||||
//! \~english Destroys the button tile.
|
||||
//! \~russian Уничтожает тайл кнопки.
|
||||
virtual ~TileButton() {}
|
||||
|
||||
//! \~english Events emitted by the button.
|
||||
//! \~russian События, генерируемые кнопкой.
|
||||
enum EventType {
|
||||
ButtonClicked
|
||||
ButtonClicked /** \~english Button was activated. \~russian Кнопка была активирована. */
|
||||
};
|
||||
|
||||
//! \~english Text format of the button label.
|
||||
//! \~russian Формат текста надписи кнопки.
|
||||
PIScreenTypes::CellFormat format;
|
||||
|
||||
//! \~english Button caption.
|
||||
//! \~russian Подпись кнопки.
|
||||
PIString text;
|
||||
|
||||
protected:
|
||||
@@ -130,18 +240,42 @@ protected:
|
||||
};
|
||||
|
||||
|
||||
//! \~\ingroup Console
|
||||
//! \~\brief
|
||||
//! \~english Group of selectable buttons arranged in one tile.
|
||||
//! \~russian Группа выбираемых кнопок, размещенных в одном тайле.
|
||||
class PIP_CONSOLE_EXPORT TileButtons: public PIScreenTile {
|
||||
PIOBJECT_SUBCLASS(TileButtons, PIScreenTile);
|
||||
|
||||
public:
|
||||
//! \~english Constructs a button group tile.
|
||||
//! \~russian Создает тайл группы кнопок.
|
||||
TileButtons(const PIString & n = PIString());
|
||||
|
||||
//! \~english Destroys the button group tile.
|
||||
//! \~russian Уничтожает тайл группы кнопок.
|
||||
virtual ~TileButtons() {}
|
||||
|
||||
//! \~english Events emitted by the button group.
|
||||
//! \~russian События, генерируемые группой кнопок.
|
||||
enum EventType {
|
||||
ButtonSelected
|
||||
ButtonSelected /** \~english A button was selected; event data stores the button index. \~russian Кнопка была выбрана; данные события содержат индекс кнопки. */
|
||||
};
|
||||
|
||||
//! \~english Button caption with cell format.
|
||||
//! \~russian Подпись кнопки с форматом ячеек.
|
||||
typedef PIPair<PIString, PIScreenTypes::CellFormat> Button;
|
||||
|
||||
//! \~english Alignment of the whole button group inside the tile bounds.
|
||||
//! \~russian Выравнивание всей группы кнопок внутри границ тайла.
|
||||
PIScreenTypes::Alignment alignment;
|
||||
|
||||
//! \~english Button definitions shown by the tile.
|
||||
//! \~russian Описания кнопок, отображаемых тайлом.
|
||||
PIVector<Button> content;
|
||||
|
||||
//! \~english Index of the currently highlighted button.
|
||||
//! \~russian Индекс текущей подсвеченной кнопки.
|
||||
int cur;
|
||||
|
||||
protected:
|
||||
@@ -157,17 +291,38 @@ protected:
|
||||
};
|
||||
|
||||
|
||||
//! \~\ingroup Console
|
||||
//! \~\brief
|
||||
//! \~english Check box tile.
|
||||
//! \~russian Тайл флажка.
|
||||
class PIP_CONSOLE_EXPORT TileCheck: public PIScreenTile {
|
||||
PIOBJECT_SUBCLASS(TileCheck, PIScreenTile);
|
||||
|
||||
public:
|
||||
//! \~english Constructs a check box tile.
|
||||
//! \~russian Создает тайл флажка.
|
||||
TileCheck(const PIString & n = PIString());
|
||||
|
||||
//! \~english Destroys the check box tile.
|
||||
//! \~russian Уничтожает тайл флажка.
|
||||
virtual ~TileCheck() {}
|
||||
|
||||
//! \~english Events emitted by the check box.
|
||||
//! \~russian События, генерируемые флажком.
|
||||
enum EventType {
|
||||
Toggled
|
||||
Toggled /** \~english Check state changed; event data stores the new boolean value. \~russian Состояние флажка изменилось; данные события содержат новое логическое значение. */
|
||||
};
|
||||
|
||||
//! \~english Text format of the caption.
|
||||
//! \~russian Формат текста подписи.
|
||||
PIScreenTypes::CellFormat format;
|
||||
|
||||
//! \~english Caption displayed after the check mark.
|
||||
//! \~russian Подпись, отображаемая после флажка.
|
||||
PIString text;
|
||||
|
||||
//! \~english Current check state.
|
||||
//! \~russian Текущее состояние флажка.
|
||||
bool toggled;
|
||||
|
||||
protected:
|
||||
@@ -178,16 +333,40 @@ protected:
|
||||
};
|
||||
|
||||
|
||||
//! \~\ingroup Console
|
||||
//! \~\brief
|
||||
//! \~english Progress indicator tile.
|
||||
//! \~russian Тайл индикатора прогресса.
|
||||
class PIP_CONSOLE_EXPORT TileProgress: public PIScreenTile {
|
||||
PIOBJECT_SUBCLASS(TileProgress, PIScreenTile);
|
||||
|
||||
public:
|
||||
//! \~english Constructs a progress tile.
|
||||
//! \~russian Создает тайл прогресса.
|
||||
TileProgress(const PIString & n = PIString());
|
||||
|
||||
//! \~english Destroys the progress tile.
|
||||
//! \~russian Уничтожает тайл прогресса.
|
||||
virtual ~TileProgress() {}
|
||||
|
||||
//! \~english Text format used for the overlaid label.
|
||||
//! \~russian Формат текста, используемый для наложенной подписи.
|
||||
PIScreenTypes::CellFormat format;
|
||||
|
||||
//! \~english Text shown before the numeric value.
|
||||
//! \~russian Текст, отображаемый перед числовым значением.
|
||||
PIString prefix;
|
||||
|
||||
//! \~english Text shown after the numeric value.
|
||||
//! \~russian Текст, отображаемый после числового значения.
|
||||
PIString suffix;
|
||||
|
||||
//! \~english Value treated as 100 percent.
|
||||
//! \~russian Значение, принимаемое за 100 процентов.
|
||||
double maximum;
|
||||
|
||||
//! \~english Current progress value.
|
||||
//! \~russian Текущее значение прогресса.
|
||||
double value;
|
||||
|
||||
protected:
|
||||
@@ -196,13 +375,28 @@ protected:
|
||||
};
|
||||
|
||||
|
||||
//! \~\ingroup Console
|
||||
//! \~\brief
|
||||
//! \~english Log view tile backed by the global %PICout buffer.
|
||||
//! \~russian Тайл журнала, использующий глобальный буфер %PICout.
|
||||
class PIP_CONSOLE_EXPORT TilePICout: public TileList {
|
||||
PIOBJECT_SUBCLASS(TilePICout, PIScreenTile);
|
||||
|
||||
public:
|
||||
//! \~english Constructs a %PICout viewer tile.
|
||||
//! \~russian Создает тайл просмотра %PICout.
|
||||
TilePICout(const PIString & n = PIString());
|
||||
|
||||
//! \~english Destroys the %PICout viewer tile.
|
||||
//! \~russian Уничтожает тайл просмотра %PICout.
|
||||
virtual ~TilePICout() {}
|
||||
|
||||
//! \~english Format applied to appended log lines.
|
||||
//! \~russian Формат, применяемый к добавляемым строкам журнала.
|
||||
PIScreenTypes::CellFormat format;
|
||||
|
||||
//! \~english Maximum number of lines retained from the %PICout buffer.
|
||||
//! \~russian Максимальное количество строк, сохраняемых из буфера %PICout.
|
||||
int max_lines;
|
||||
|
||||
protected:
|
||||
@@ -211,14 +405,32 @@ protected:
|
||||
};
|
||||
|
||||
|
||||
//! \~\ingroup Console
|
||||
//! \~\brief
|
||||
//! \~english Single-line editable text input tile.
|
||||
//! \~russian Однострочный тайл редактируемого текстового ввода.
|
||||
class PIP_CONSOLE_EXPORT TileInput: public PIScreenTile {
|
||||
PIOBJECT_SUBCLASS(TileInput, PIScreenTile);
|
||||
|
||||
public:
|
||||
//! \~english Constructs an input tile.
|
||||
//! \~russian Создает тайл ввода.
|
||||
TileInput(const PIString & n = PIString());
|
||||
|
||||
//! \~english Destroys the input tile.
|
||||
//! \~russian Уничтожает тайл ввода.
|
||||
virtual ~TileInput() {}
|
||||
|
||||
//! \~english Format of the entered text.
|
||||
//! \~russian Формат вводимого текста.
|
||||
PIScreenTypes::CellFormat format;
|
||||
|
||||
//! \~english Current input text.
|
||||
//! \~russian Текущий введенный текст.
|
||||
PIString text;
|
||||
|
||||
//! \~english Maximum input length setting reserved for the tile logic.
|
||||
//! \~russian Параметр максимальной длины ввода, зарезервированный для логики тайла.
|
||||
int max_length;
|
||||
|
||||
protected:
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
/*! \file piscreentypes.h
|
||||
* \ingroup Console
|
||||
* \~\brief
|
||||
* \~english Types for PIScreen
|
||||
* \~russian Типы для PIScreen
|
||||
*/
|
||||
//! \~\file piscreentypes.h
|
||||
//! \~\ingroup Console
|
||||
//! \brief
|
||||
//! \~english Types for PIScreen
|
||||
//! \~russian Типы для PIScreen
|
||||
//! \details
|
||||
//! \~english Provides common types used by screen tiles and drawer.
|
||||
//! \~russian Обеспечивает общие типы, используемые тайлами и отрисовщиком экрана.
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Types for PIScreen
|
||||
@@ -32,92 +34,160 @@
|
||||
|
||||
class PIScreenTile;
|
||||
|
||||
//! \relatesalso PIScreenTile
|
||||
//! \~english Namespace with shared screen cells, layout flags, and tile event types.
|
||||
//! \~russian Пространство имен с общими типами экранных ячеек, флагами компоновки и событиями тайлов.
|
||||
namespace PIScreenTypes {
|
||||
|
||||
//! Color for chars or background
|
||||
//! \~english Color for a character or its background.
|
||||
//! \~russian Цвет символа или его фона.
|
||||
enum Color {
|
||||
Default /** Default */,
|
||||
Black /** Black */,
|
||||
Red /** Red */,
|
||||
Green /** Green */,
|
||||
Blue /** Blue */,
|
||||
Cyan /** Cyan */,
|
||||
Magenta /** Magenta */,
|
||||
Yellow /** Yellow */,
|
||||
White /** White */,
|
||||
Transparent /** Save previous color */
|
||||
Default /** \~english Terminal default color \~russian Цвет терминала по умолчанию */,
|
||||
Black /** \~english Black \~russian Черный */,
|
||||
Red /** \~english Red \~russian Красный */,
|
||||
Green /** \~english Green \~russian Зеленый */,
|
||||
Blue /** \~english Blue \~russian Синий */,
|
||||
Cyan /** \~english Cyan \~russian Голубой */,
|
||||
Magenta /** \~english Magenta \~russian Пурпурный */,
|
||||
Yellow /** \~english Yellow \~russian Желтый */,
|
||||
White /** \~english White \~russian Белый */,
|
||||
Transparent /** \~english Preserve the background already stored in the target cell \~russian Сохранить фон, уже записанный в целевой
|
||||
ячейке */
|
||||
};
|
||||
|
||||
//! Flags for chars
|
||||
//! \~english Character formatting flags.
|
||||
//! \~russian Флаги оформления символа.
|
||||
enum CharFlag {
|
||||
Bold /** Bold or bright */ = 0x1,
|
||||
Blink /** Blink text */ = 0x2,
|
||||
Underline /** Underline text */ = 0x4,
|
||||
Inverse = 0x08
|
||||
Bold = 0x1 /** \~english Bold or bright text \~russian Жирный или яркий текст */,
|
||||
Blink = 0x2 /** \~english Blinking text \~russian Мигание текста */,
|
||||
Underline = 0x4 /** \~english Underlined text \~russian Подчеркнутый текст */,
|
||||
Inverse = 0x08 /** \~english Inverted foreground and background \~russian Инвертированные цвета текста и фона */
|
||||
};
|
||||
|
||||
//! Alignment
|
||||
//! \~english Horizontal text alignment inside a tile.
|
||||
//! \~russian Горизонтальное выравнивание текста внутри тайла.
|
||||
enum Alignment {
|
||||
Left /** Left */,
|
||||
Center /** Center */,
|
||||
Right /** Right */
|
||||
Left /** \~english Left alignment \~russian Выравнивание влево */,
|
||||
Center /** \~english Center alignment \~russian Выравнивание по центру */,
|
||||
Right /** \~english Right alignment \~russian Выравнивание вправо */
|
||||
};
|
||||
|
||||
//! Size policy
|
||||
//! \~english Layout policy used by parent tiles.
|
||||
//! \~russian Политика размера, используемая родительскими тайлами при компоновке.
|
||||
enum SizePolicy {
|
||||
Fixed /** Fixed size */,
|
||||
Preferred /** Preferred size */,
|
||||
Expanding /** Maximum available size */,
|
||||
Ignore /** Ignore layout logic */
|
||||
Fixed /** \~english Keep the requested size \~russian Сохранять запрошенный размер */,
|
||||
Preferred /** \~english Use preferred size first and share extra space after fixed tiles \~russian Сначала использовать предпочтительный
|
||||
размер и затем делить свободное место после фиксированных тайлов */
|
||||
,
|
||||
Expanding /** \~english Take extra space before preferred tiles when the parent can grow children \~russian Получать дополнительное
|
||||
пространство раньше тайлов с предпочтительным размером, если родитель может расширять дочерние элементы */
|
||||
,
|
||||
Ignore /** \~english Skip automatic layout; geometry must be managed manually \~russian Не участвовать в автоматической компоновке;
|
||||
геометрию нужно задавать вручную */
|
||||
};
|
||||
|
||||
//! Direction
|
||||
//! \~english Child layout direction.
|
||||
//! \~russian Направление раскладки дочерних тайлов.
|
||||
enum Direction {
|
||||
Horizontal /** Horizontal */,
|
||||
Vertical /** Vertical */
|
||||
Horizontal /** \~english Horizontal layout \~russian Горизонтальная раскладка */,
|
||||
Vertical /** \~english Vertical layout \~russian Вертикальная раскладка */
|
||||
};
|
||||
|
||||
//! Focus flags
|
||||
//! \~english Focus and navigation flags for tiles.
|
||||
//! \~russian Флаги фокуса и навигации для тайлов.
|
||||
enum FocusFlag {
|
||||
CanHasFocus /** Tile can has focus */ = 0x1,
|
||||
NextByTab /** Focus passed to next tile by tab key */ = 0x2,
|
||||
NextByArrowsHorizontal /** Focus passed to next tile by arrow keys left or right */ = 0x4,
|
||||
NextByArrowsVertical /** Focus passed to next tile by arrow keys up or down */ = 0x8,
|
||||
NextByArrowsAll /** Focus passed to next tile by any arrow key */ = NextByArrowsHorizontal | NextByArrowsVertical,
|
||||
FocusOnMouse /** Tile focused on mouse press */ = 0x10,
|
||||
FocusOnWheel /** Tile focused on wheel */ = 0x20,
|
||||
FocusOnMouseOrWheel /** Tile focused on mouse press or wheel */ = FocusOnMouse | FocusOnWheel
|
||||
CanHasFocus = 0x1 /** \~english Tile can receive focus \~russian Тайл может получать фокус */,
|
||||
NextByTab = 0x2 /** \~english Tab moves focus to the next tile \~russian Клавиша Tab переводит фокус к следующему тайлу */,
|
||||
NextByArrowsHorizontal = 0x4 /** \~english Left and right arrows move focus \~russian Стрелки влево и вправо переводят фокус */,
|
||||
NextByArrowsVertical = 0x8 /** \~english Up and down arrows move focus \~russian Стрелки вверх и вниз переводят фокус */,
|
||||
NextByArrowsAll /** \~english Any arrow key moves focus \~russian Любая стрелка переводит фокус */ =
|
||||
NextByArrowsHorizontal | NextByArrowsVertical,
|
||||
FocusOnMouse = 0x10 /** \~english Mouse press gives focus to the tile \~russian Нажатие мышью переводит фокус на тайл */,
|
||||
FocusOnWheel = 0x20 /** \~english Mouse wheel gives focus to the tile \~russian Колесо мыши переводит фокус на тайл */,
|
||||
FocusOnMouseOrWheel /** \~english Mouse press or wheel gives focus to the tile \~russian Нажатие мышью или колесо переводят фокус на
|
||||
тайл */
|
||||
= FocusOnMouse | FocusOnWheel
|
||||
};
|
||||
|
||||
//! \~english Combination of \a CharFlag values.
|
||||
//! \~russian Комбинация значений \a CharFlag.
|
||||
typedef PIFlags<CharFlag> CharFlags;
|
||||
|
||||
//! \~english Combination of \a FocusFlag values.
|
||||
//! \~russian Комбинация значений \a FocusFlag.
|
||||
typedef PIFlags<FocusFlag> FocusFlags;
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Packed character formatting used by screen cells.
|
||||
//! \~russian Упакованное описание оформления символа, используемое экранными ячейками.
|
||||
union PIP_CONSOLE_EXPORT CellFormat {
|
||||
//! \~english Constructs a format from the raw packed value.
|
||||
//! \~russian Создает формат из упакованного сырого значения.
|
||||
CellFormat(ushort f = 0) { raw_format = f; }
|
||||
|
||||
//! \~english Constructs a format from foreground color, background color, and character flags.
|
||||
//! \~russian Создает формат из цвета символа, цвета фона и флагов оформления.
|
||||
CellFormat(Color col_char, Color col_back = Default, CharFlags flags_ = 0) {
|
||||
color_char = col_char;
|
||||
color_back = col_back;
|
||||
flags = flags_;
|
||||
}
|
||||
|
||||
//! \~english Raw packed representation of the format.
|
||||
//! \~russian Сырое упакованное представление формата.
|
||||
ushort raw_format;
|
||||
struct {
|
||||
//! \~english Foreground color from \a Color.
|
||||
//! \~russian Цвет символа из \a Color.
|
||||
ushort color_char: 4;
|
||||
|
||||
//! \~english Background color from \a Color.
|
||||
//! \~russian Цвет фона из \a Color.
|
||||
ushort color_back: 4;
|
||||
|
||||
//! \~english Combination of \a CharFlag values.
|
||||
//! \~russian Комбинация значений \a CharFlag.
|
||||
ushort flags: 8;
|
||||
};
|
||||
|
||||
//! \~english Returns \b true when two formats are identical.
|
||||
//! \~russian Возвращает \b true, если два формата совпадают.
|
||||
bool operator==(const CellFormat & c) const { return raw_format == c.raw_format; }
|
||||
|
||||
//! \~english Returns \b true when two formats differ.
|
||||
//! \~russian Возвращает \b true, если форматы различаются.
|
||||
bool operator!=(const CellFormat & c) const { return raw_format != c.raw_format; }
|
||||
};
|
||||
|
||||
//! \~\brief
|
||||
//! \~english One character cell of the console screen.
|
||||
//! \~russian Одна символьная ячейка консольного экрана.
|
||||
struct PIP_CONSOLE_EXPORT Cell {
|
||||
//! \~english Constructs a cell from a symbol and its format.
|
||||
//! \~russian Создает ячейку из символа и его формата.
|
||||
Cell(PIChar c = PIChar(' '), CellFormat f = CellFormat()) {
|
||||
symbol = c;
|
||||
format = f;
|
||||
}
|
||||
|
||||
//! \~english Cell formatting.
|
||||
//! \~russian Формат ячейки.
|
||||
CellFormat format;
|
||||
|
||||
//! \~english Character stored in the cell.
|
||||
//! \~russian Символ, хранимый в ячейке.
|
||||
PIChar symbol;
|
||||
|
||||
//! \~english Returns \b true when symbol and format match.
|
||||
//! \~russian Возвращает \b true, если совпадают символ и формат.
|
||||
bool operator==(const Cell & c) const { return format == c.format && symbol == c.symbol; }
|
||||
|
||||
//! \~english Returns \b true when symbol or format differs.
|
||||
//! \~russian Возвращает \b true, если символ или формат различаются.
|
||||
bool operator!=(const Cell & c) const { return format != c.format || symbol != c.symbol; }
|
||||
|
||||
//! \~english Assigns a cell, preserving the current background when source background is \a Transparent.
|
||||
//! \~russian Присваивает ячейку, сохраняя текущий фон, если у источника фон равен \a Transparent.
|
||||
Cell & operator=(const Cell & c) {
|
||||
symbol = c.symbol;
|
||||
if (c.format.color_back == Transparent) {
|
||||
@@ -129,18 +199,46 @@ struct PIP_CONSOLE_EXPORT Cell {
|
||||
}
|
||||
};
|
||||
|
||||
//! \~\brief
|
||||
//! \~english User-defined event raised by a tile.
|
||||
//! \~russian Пользовательское событие, поднимаемое тайлом.
|
||||
struct PIP_CONSOLE_EXPORT TileEvent {
|
||||
//! \~english Constructs an event with numeric type and optional payload.
|
||||
//! \~russian Создает событие с числовым типом и необязательными данными.
|
||||
TileEvent(int t = -1, const PIVariant & d = PIVariant()): type(t), data(d) {}
|
||||
|
||||
//! \~english Event type chosen by the tile implementation.
|
||||
//! \~russian Тип события, выбираемый реализацией тайла.
|
||||
int type;
|
||||
|
||||
//! \~english Optional event payload.
|
||||
//! \~russian Необязательные данные события.
|
||||
PIVariant data;
|
||||
};
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Base interface used by tiles to notify the owning screen about focus, removal, and custom events.
|
||||
//! \~russian Базовый интерфейс, через который тайлы уведомляют владеющий экран о фокусе, удалении и пользовательских событиях.
|
||||
class PIP_CONSOLE_EXPORT PIScreenBase {
|
||||
public:
|
||||
//! \~english Constructs an empty screen bridge.
|
||||
//! \~russian Создает пустой мост к экрану.
|
||||
PIScreenBase() {}
|
||||
|
||||
//! \~english Destroys the screen bridge.
|
||||
//! \~russian Уничтожает мост к экрану.
|
||||
virtual ~PIScreenBase() {}
|
||||
|
||||
//! \~english Called when a tile raises a custom event.
|
||||
//! \~russian Вызывается, когда тайл поднимает пользовательское событие.
|
||||
virtual void tileEventInternal(PIScreenTile *, TileEvent) {}
|
||||
|
||||
//! \~english Called when a tile is removed from the screen tree.
|
||||
//! \~russian Вызывается при удалении тайла из дерева экрана.
|
||||
virtual void tileRemovedInternal(PIScreenTile *) {}
|
||||
|
||||
//! \~english Called when a tile requests focus.
|
||||
//! \~russian Вызывается, когда тайл запрашивает фокус.
|
||||
virtual void tileSetFocusInternal(PIScreenTile *) {}
|
||||
};
|
||||
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/*! \file piterminal.h
|
||||
* \ingroup Console
|
||||
* \~\brief
|
||||
* \~english Virtual terminal
|
||||
* \~russian Виртуальный терминал
|
||||
*/
|
||||
//! \~\file piterminal.h
|
||||
//! \~\ingroup Console
|
||||
//! \brief
|
||||
//! \~english Virtual terminal
|
||||
//! \~russian Виртуальный терминал
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Virtual terminal
|
||||
@@ -31,26 +30,65 @@
|
||||
#include "piscreentypes.h"
|
||||
|
||||
|
||||
//! \~\ingroup Console
|
||||
//! \~\brief
|
||||
//! \~english Virtual terminal that runs a shell and mirrors its screen into a cell buffer.
|
||||
//! \~russian Виртуальный терминал, который запускает оболочку и отражает ее экран в буфер ячеек.
|
||||
//! \details
|
||||
//! \~english Provides terminal emulation for reading console input and output. Supports ANSI escape sequences for cursor movement, colors,
|
||||
//! and text formatting.
|
||||
//! \~russian Обеспечивает эмуляцию терминала для чтения ввода и вывода консоли. Поддерживает ANSI escape-последовательности для перемещения
|
||||
//! курсора, цветов и форматирования текста.
|
||||
class PIP_CONSOLE_EXPORT PITerminal: public PIThread {
|
||||
PIOBJECT_SUBCLASS(PITerminal, PIThread);
|
||||
|
||||
public:
|
||||
//! Constructs %PITerminal
|
||||
//! \~english Constructs %PITerminal.
|
||||
//! \~russian Создает %PITerminal.
|
||||
PITerminal();
|
||||
|
||||
//! \~english Destroys the terminal and releases backend resources.
|
||||
//! \~russian Уничтожает терминал и освобождает внутренние ресурсы.
|
||||
~PITerminal();
|
||||
|
||||
//! \~english Returns terminal width in columns.
|
||||
//! \~russian Возвращает ширину терминала в столбцах.
|
||||
int columns() const { return size_x; }
|
||||
|
||||
//! \~english Returns terminal height in rows.
|
||||
//! \~russian Возвращает высоту терминала в строках.
|
||||
int rows() const { return size_y; }
|
||||
|
||||
//! \~english Resizes the terminal viewport and backing cell buffer.
|
||||
//! \~russian Изменяет размер области терминала и связанного буфера ячеек.
|
||||
bool resize(int cols, int rows);
|
||||
|
||||
//! \~english Sends raw byte data to the terminal input.
|
||||
//! \~russian Отправляет необработанные байты во входной поток терминала.
|
||||
void write(const PIByteArray & d);
|
||||
|
||||
//! \~english Sends a special key with modifiers to the terminal.
|
||||
//! \~russian Отправляет в терминал специальную клавишу с модификаторами.
|
||||
void write(PIKbdListener::SpecialKey k, PIKbdListener::KeyModifiers m);
|
||||
|
||||
//! \~english Sends a keyboard event to the terminal.
|
||||
//! \~russian Отправляет событие клавиатуры в терминал.
|
||||
void write(PIKbdListener::KeyEvent ke);
|
||||
|
||||
//! \~english Returns the current terminal screen snapshot, including cursor blink state.
|
||||
//! \~russian Возвращает текущий снимок экрана терминала с учетом состояния мигания курсора.
|
||||
PIVector<PIVector<PIScreenTypes::Cell>> content();
|
||||
|
||||
//! \~english Returns whether key code `k` is handled as a special terminal key.
|
||||
//! \~russian Возвращает, обрабатывается ли код `k` как специальная клавиша терминала.
|
||||
static bool isSpecialKey(int k);
|
||||
|
||||
//! \~english Initializes the terminal backend and starts the polling thread.
|
||||
//! \~russian Инициализирует внутренний терминал и запускает поток опроса.
|
||||
bool initialize();
|
||||
|
||||
//! \~english Stops the terminal and destroys the internal terminal backend instance.
|
||||
//! \~russian Останавливает терминал и уничтожает внутреннюю реализацию терминала.
|
||||
void destroy();
|
||||
|
||||
private:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! \addtogroup Containers
|
||||
//! \{
|
||||
//! \file picontainers.h
|
||||
//! \~\file picontainers.h
|
||||
//! \brief
|
||||
//! \~english Base macros for generic containers
|
||||
//! \~russian Базовые макросы для контейнеров
|
||||
@@ -74,17 +74,14 @@ public:
|
||||
template<typename T>
|
||||
class _PIContainerConstants {
|
||||
public:
|
||||
// minimum elements for container
|
||||
static size_t minCountPoT() {
|
||||
static const size_t ret = _PIContainerConstantsBase::calcMinCountPoT(sizeof(T));
|
||||
return ret;
|
||||
}
|
||||
// maximum elements for 2^n growth
|
||||
static size_t maxCountForPoT() {
|
||||
static const size_t ret = _PIContainerConstantsBase::calcMaxCountForPoT(sizeof(T));
|
||||
return ret;
|
||||
}
|
||||
// add elements after 2^n growth
|
||||
static size_t stepAfterPoT() {
|
||||
static const size_t ret = _PIContainerConstantsBase::calcStepAfterPoT(sizeof(T));
|
||||
return ret;
|
||||
@@ -112,9 +109,6 @@ public:
|
||||
};
|
||||
|
||||
|
||||
//! \brief
|
||||
//! \~english Template reverse wrapper over any container
|
||||
//! \~russian Шаблонная функция обертки любого контейнера для обратного доступа через итераторы
|
||||
template<typename C>
|
||||
_PIReverseWrapper<C> PIReverseWrap(C & c) {
|
||||
return _PIReverseWrapper<C>(c);
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
*/
|
||||
//! \defgroup Containers Containers
|
||||
//! \~\brief
|
||||
//! \~english Various standart containers realization
|
||||
//! \~russian Различные классы контейнеров
|
||||
//! \~english Container classes and related helpers
|
||||
//! \~russian Классы контейнеров и связанные вспомогательные сущности
|
||||
//!
|
||||
//! \~\details
|
||||
//! \~english \section cmake_module_Containers Building with CMake
|
||||
@@ -58,9 +58,8 @@
|
||||
//! \a PIVector2D | Линейный двумерный прямоугольный массив
|
||||
//!
|
||||
//!
|
||||
//! \~english \section stl_iterators STL-Style Iterators
|
||||
//! \~russian \section stl_iterators Итераторы в стиле STL
|
||||
//! \~english
|
||||
//! \section stl_iterators STL-Style Iterators
|
||||
//! \brief They are compatible with Qt's and STL's generic algorithms and are optimized for speed.
|
||||
//! \details
|
||||
//! For each container class, there are two STL-style iterator types:
|
||||
@@ -114,6 +113,7 @@
|
||||
//! can be used on the left side of the assignment operator.
|
||||
//!
|
||||
//! \~russian
|
||||
//! \section stl_iterators Итераторы в стиле STL
|
||||
//! \brief Они совместимы с базовыми алгоритмами Qt и STL и оптимизированы по скорости.
|
||||
//! \details
|
||||
//! Для каждого контейнерного класса есть два типа итераторов в стиле STL:
|
||||
@@ -167,6 +167,14 @@
|
||||
//! Для неконстантных итераторов, возвращаемое значение унарного оператора `*`
|
||||
//! может быть использовано с левой стороны от оператора присваивания.
|
||||
//!
|
||||
//! \~\file picontainersmodule.h
|
||||
//! \~\ingroup Containers
|
||||
//! \~\brief
|
||||
//! \~english Umbrella header for the Containers module.
|
||||
//! \~russian Общий заголовок модуля Containers.
|
||||
//! \~\details
|
||||
//! \~english Includes the primary public container headers.
|
||||
//! \~russian Подключает основные публичные заголовки контейнеров.
|
||||
//!
|
||||
//! \authors
|
||||
//! \~english
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! \addtogroup Containers
|
||||
//! \{
|
||||
//! \file pideque.h
|
||||
//! \~\file pideque.h
|
||||
//! \brief
|
||||
//! \~english Declares \a PIDeque
|
||||
//! \~russian Объявление \a PIDeque
|
||||
@@ -184,7 +184,7 @@ public:
|
||||
//! \endcode
|
||||
inline PIDeque(size_t piv_size, std::function<T(size_t i)> f) {
|
||||
PIINTROSPECTION_CONTAINER_NEW(T, sizeof(T))
|
||||
expand(piv_size, f);
|
||||
expand(piv_size, std::move(f));
|
||||
}
|
||||
|
||||
//! \~english Move constructor.
|
||||
@@ -729,7 +729,7 @@ public:
|
||||
//! заданному в передаваемой функции `test`, или `def` если такого элемента нет.
|
||||
//! \~\sa \a indexWhere()
|
||||
inline const T & atWhere(std::function<bool(const T & e)> test, ssize_t start = 0, const T & def = T()) const {
|
||||
const ssize_t i = indexWhere(test, start);
|
||||
const ssize_t i = indexWhere(std::move(test), start);
|
||||
if (i < 0)
|
||||
return def;
|
||||
else
|
||||
@@ -743,7 +743,7 @@ public:
|
||||
//! заданному в передаваемой функции `test`, или `def` если такого элемента нет.
|
||||
//! \~\sa \a lastIndexWhere()
|
||||
inline const T & lastAtWhere(std::function<bool(const T & e)> test, ssize_t start = -1, const T & def = T()) const {
|
||||
const ssize_t i = lastIndexWhere(test, start);
|
||||
const ssize_t i = lastIndexWhere(std::move(test), start);
|
||||
if (i < 0)
|
||||
return def;
|
||||
else
|
||||
@@ -1265,7 +1265,7 @@ public:
|
||||
deleteT(pid_data + pid_start + new_size, pid_size - new_size);
|
||||
pid_size = new_size;
|
||||
} else if (new_size > pid_size) {
|
||||
expand(new_size, f);
|
||||
expand(new_size, std::move(f));
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
@@ -1540,7 +1540,7 @@ public:
|
||||
//! \endcode
|
||||
//! \~\sa \a sort()
|
||||
inline PIDeque<T> & sort(std::function<bool(const T & a, const T & b)> comp) {
|
||||
std::stable_sort(begin(), end(), comp);
|
||||
std::stable_sort(begin(), end(), std::move(comp));
|
||||
return *this;
|
||||
}
|
||||
|
||||
@@ -1654,7 +1654,13 @@ public:
|
||||
//! \endcode
|
||||
//! \~\sa \a remove(), \a removeOne(), \a removeWhere()
|
||||
inline PIDeque<T> & removeWhere(std::function<bool(const T & e)> test) {
|
||||
ssize_t j = indexWhere(test);
|
||||
ssize_t j = -1;
|
||||
for (size_t i = pid_start; i < pid_start + pid_size; ++i) {
|
||||
if (test(pid_data[i])) {
|
||||
j = ssize_t(i) - pid_start;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (j != -1) {
|
||||
for (size_t i = j + 1; i < pid_size; ++i) {
|
||||
if (!test(pid_data[i + pid_start])) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! \addtogroup Containers
|
||||
//! \{
|
||||
//! \file pimap.h
|
||||
//! \brief
|
||||
//! \~\file pimap.h
|
||||
//! \~\brief
|
||||
//! \~english Declares \a PIMap
|
||||
//! \~russian Объявление \a PIMap
|
||||
//! \~\authors
|
||||
@@ -52,32 +52,23 @@ class PIMapIteratorReverse;
|
||||
//! \addtogroup Containers
|
||||
//! \{
|
||||
//! \class PIMap
|
||||
//! \brief
|
||||
//! \~english Associative array.
|
||||
//! \~russian Словарь.
|
||||
//! \~\brief
|
||||
//! \~english Map of unique keys and associated values.
|
||||
//! \~russian Словарь с уникальными ключами и связанными значениями.
|
||||
//! \~\}
|
||||
//! \details
|
||||
//! \~\details
|
||||
//! \~english
|
||||
//! A collection of key/value pairs, from which you retrieve a value using its associated key.
|
||||
//! There is a finite number of keys in the map, and each key has exactly one value associated with it.
|
||||
//! \a value() returns value for key and leave map
|
||||
//! unchaged in any case. \a operator [] create entry in map if
|
||||
//! there is no entry for given key. You can retrieve all
|
||||
//! keys by method \a keys() and all values by methos \a values().
|
||||
//! To iterate all entries use class PIMapIterator, or methods
|
||||
//! \a makeIterator() and \a makeReverseIterator().
|
||||
//! A key in the Map may only occur once.
|
||||
//! Stores key/value pairs and keeps keys unique.
|
||||
//! \a value() returns the value for a key or the provided default,
|
||||
//! while \a operator[] creates a default value for a missing key.
|
||||
//! Use \a keys() and \a values() to retrieve map contents,
|
||||
//! and \a makeIterator() or \a makeReverseIterator() to traverse entries.
|
||||
//! \~russian
|
||||
//! Словари, в принципе, похожи на обычные, используемые в повседневной жизни.
|
||||
//! Они хранят элементы одного и того же типа, индексируемые ключевыми значениями.
|
||||
//! Достоинство словаря в том, что он позволяет быстро получать значение,
|
||||
//! ассоциированное с заданным ключом.
|
||||
//! Ключи должны быть уникальными.
|
||||
//! Элемент
|
||||
//! В контейнеры этого типа заносятся элементы вместе с ключами,
|
||||
//! по которым их можно найти, которыми могут выступать значения любого типа.
|
||||
//! \a operator [] позволяет получить доступ к элементу по ключу,
|
||||
//! и если такого эелемента не было, то он будет создан.
|
||||
//! Хранит пары ключ/значение и поддерживает уникальность ключей.
|
||||
//! \a value() возвращает значение по ключу или значение по умолчанию,
|
||||
//! а \a operator[] создает значение по умолчанию для отсутствующего ключа.
|
||||
//! Для получения содержимого используйте \a keys() и \a values(),
|
||||
//! а для обхода элементов - \a makeIterator() или \a makeReverseIterator().
|
||||
template<typename Key, typename T>
|
||||
class PIMap {
|
||||
template<typename Key1, typename T1>
|
||||
@@ -240,12 +231,11 @@ public:
|
||||
inline const_iterator begin() const { return const_iterator(this, 0); }
|
||||
inline const_iterator end() const { return const_iterator(this, size()); }
|
||||
|
||||
//! \~english Returns a reverse iterator to the first element of the reversed array.
|
||||
//! \~english Returns a reverse iterator to the last map entry.
|
||||
//! \~russian Обратный итератор на первый элемент.
|
||||
inline reverse_iterator rbegin() { return reverse_iterator(this, size() - 1); }
|
||||
|
||||
//! \~english Returns a reverse iterator to the element.
|
||||
//! following the last element of the reversed array.
|
||||
//! \~english Returns a reverse iterator to the position before the first map entry.
|
||||
//! \~russian Обратный итератор на элемент,
|
||||
//! следующий за последним элементом.
|
||||
inline reverse_iterator rend() { return reverse_iterator(this, -1); }
|
||||
@@ -265,13 +255,13 @@ public:
|
||||
//! \relatesalso PIMapIteratorReverse
|
||||
inline PIMapIteratorReverse<Key, T> makeReverseIterator() { return PIMapIteratorReverse<Key, T>(*this); }
|
||||
|
||||
//! \~english Number of elements in the container.
|
||||
//! \~russian Количество элементов массива.
|
||||
//! \~english Number of entries in the map.
|
||||
//! \~russian Количество элементов в словаре.
|
||||
//! \~\sa \a size_s(), \a capacity(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve()
|
||||
inline size_t size() const { return pim_content.size(); }
|
||||
|
||||
//! \~english Number of elements in the container as signed value.
|
||||
//! \~russian Количество элементов массива в виде знакового числа.
|
||||
//! \~english Number of entries in the map as a signed value.
|
||||
//! \~russian Количество элементов в словаре в виде знакового числа.
|
||||
//! \~\sa \a size(), \a capacity(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve()
|
||||
inline int size_s() const { return pim_content.size_s(); }
|
||||
|
||||
@@ -280,19 +270,13 @@ public:
|
||||
//! \~\sa \a size(), \a size_s(), \a capacity(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve()
|
||||
inline size_t length() const { return pim_content.size(); }
|
||||
|
||||
//! \~english Checks if the container has no elements.
|
||||
//! \~russian Проверяет пуст ли массив.
|
||||
//! \~\return
|
||||
//! \~english **true** if the container is empty, **false** otherwise
|
||||
//! \~russian **true** если массив пуст, **false** иначе.
|
||||
//! \~english Checks whether the map is empty.
|
||||
//! \~russian Проверяет, пуст ли словарь.
|
||||
//! \~\sa \a size(), \a size_s(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve()
|
||||
inline bool isEmpty() const { return (pim_content.size() == 0); }
|
||||
|
||||
//! \~english Checks if the container has elements.
|
||||
//! \~russian Проверяет не пуст ли массив.
|
||||
//! \~\return
|
||||
//! \~english **true** if the container is not empty, **false** otherwise
|
||||
//! \~russian **true** если массив не пуст, **false** иначе.
|
||||
//! \~english Checks whether the map contains entries.
|
||||
//! \~russian Проверяет, содержит ли словарь элементы.
|
||||
//! \~\sa \a size(), \a size_s(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve()
|
||||
inline bool isNotEmpty() const { return (pim_content.size() > 0); }
|
||||
|
||||
@@ -304,7 +288,7 @@ public:
|
||||
//! the function inserts a default-constructed value into the map with key `key`,
|
||||
//! and returns a reference to it.
|
||||
//! \~russian Если элемента с таким ключом `key` не существует,
|
||||
//! то он будет создан конструктором по умолчанию и добавлен в массив
|
||||
//! то он будет создан конструктором по умолчанию и добавлен в словарь
|
||||
//! по ключу `key`, а затем возвращена ссылка на этот новый элемент.
|
||||
//! \~\code
|
||||
//! PIMap <PIString, int> m;
|
||||
@@ -339,8 +323,8 @@ public:
|
||||
return _value(i);
|
||||
}
|
||||
|
||||
//! \~english Remove element with key `key` from the array and return it.
|
||||
//! \~russian Удаляет элемент с ключом `key` из массива и возвращает его.
|
||||
//! \~english Removes entry with key `key` and returns its value.
|
||||
//! \~russian Удаляет элемент с ключом `key` и возвращает его значение.
|
||||
inline T take(const Key & key, const T & default_ = T()) {
|
||||
bool f(false);
|
||||
const ssize_t i = _find(key, f);
|
||||
@@ -350,8 +334,8 @@ public:
|
||||
return ret;
|
||||
}
|
||||
|
||||
//! \~english Inserts all elements in array `other` to this array with overwrite.
|
||||
//! \~russian Вставляет все элементы `other` этот массив с перезаписью.
|
||||
//! \~english Inserts all entries from `other`, overwriting existing keys.
|
||||
//! \~russian Добавляет все элементы из `other`, перезаписывая существующие ключи.
|
||||
inline PIMap<Key, T> & operator<<(const PIMap<Key, T> & other) {
|
||||
#ifndef NDEBUG
|
||||
if (&other == this) {
|
||||
@@ -365,8 +349,8 @@ public:
|
||||
return *this;
|
||||
}
|
||||
if (other.size() == 2) {
|
||||
insert(other.pim_index[0].key, other.pim_content[0]);
|
||||
insert(other.pim_index[1].key, other.pim_content[1]);
|
||||
insert(other.pim_index[0].key, other.pim_content[other.pim_index[0].index]);
|
||||
insert(other.pim_index[1].key, other.pim_content[other.pim_index[1].index]);
|
||||
return *this;
|
||||
}
|
||||
for (int i = 0; i < other.pim_index.size_s(); ++i) {
|
||||
@@ -375,24 +359,24 @@ public:
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Compare operator with array `m`.
|
||||
//! \~russian Оператор сравнения с массивом `m`.
|
||||
//! \~english Compares this map with `m`.
|
||||
//! \~russian Сравнивает этот словарь с `m`.
|
||||
inline bool operator==(const PIMap<Key, T> & m) const { return (pim_content == m.pim_content && pim_index == m.pim_index); }
|
||||
|
||||
//! \~english Compare operator with array `m`.
|
||||
//! \~russian Оператор сравнения с массивом `m`.
|
||||
//! \~english Compares this map with `m`.
|
||||
//! \~russian Сравнивает этот словарь с `m`.
|
||||
inline bool operator!=(const PIMap<Key, T> & m) const { return (pim_content != m.pim_content || pim_index != m.pim_index); }
|
||||
|
||||
//! \~english Tests if element with key `key` exists in the array.
|
||||
//! \~russian Проверяет наличие элемента с ключом `key` в массиве.
|
||||
//! \~english Checks whether the map contains key `key`.
|
||||
//! \~russian Проверяет, содержит ли словарь ключ `key`.
|
||||
inline bool contains(const Key & key) const {
|
||||
bool f(false);
|
||||
_find(key, f);
|
||||
return f;
|
||||
}
|
||||
|
||||
//! \~english Tests if element with value `value` exists in the array.
|
||||
//! \~russian Проверяет наличие элемента со значением `value` в массиве.
|
||||
//! \~english Checks whether the map contains value `value`.
|
||||
//! \~russian Проверяет, содержит ли словарь значение `value`.
|
||||
inline bool containsValue(const T & value) const { return pim_content.contains(value); }
|
||||
|
||||
//! \~english Attempts to allocate memory for at least `new_size` elements.
|
||||
@@ -403,8 +387,8 @@ public:
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Remove element with key `key` from the array.
|
||||
//! \~russian Удаляет элемент с ключом `key` из массива.
|
||||
//! \~english Removes entry with key `key`.
|
||||
//! \~russian Удаляет элемент с ключом `key`.
|
||||
inline PIMap<Key, T> & remove(const Key & key) {
|
||||
bool f(false);
|
||||
const ssize_t i = _find(key, f);
|
||||
@@ -413,7 +397,7 @@ public:
|
||||
}
|
||||
|
||||
|
||||
//! \~english Remove all elements in the array
|
||||
//! \~english Removes all entries
|
||||
//! passes the test implemented by the provided function `test`.
|
||||
//! \~russian Удаляет все элементы, удовлетворяющие условию,
|
||||
//! заданному в передаваемой функции `test`.
|
||||
@@ -433,8 +417,8 @@ public:
|
||||
inline PIMap<Key, T> & erase(const Key & key) { return remove(key); }
|
||||
|
||||
|
||||
//! \~english Clear array, remove all elements.
|
||||
//! \~russian Очищает массив, удаляет все элементы.
|
||||
//! \~english Clears the map.
|
||||
//! \~russian Очищает словарь.
|
||||
//! \~\details
|
||||
//! \~\note
|
||||
//! \~english Reserved memory will not be released.
|
||||
@@ -446,8 +430,8 @@ public:
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Swaps array `v` other with this array.
|
||||
//! \~russian Меняет местами массив `v` с этим массивом.
|
||||
//! \~english Swaps this map with `other`.
|
||||
//! \~russian Меняет местами этот словарь и `other`.
|
||||
//! \~\details
|
||||
//! \~english This operation is very fast and never fails.
|
||||
//! \~russian Эта операция выполняется мгновенно без копирования памяти и никогда не дает сбоев.
|
||||
@@ -456,8 +440,8 @@ public:
|
||||
pim_index.swap(other.pim_index);
|
||||
}
|
||||
|
||||
//! \~english Inserts value `value` with key `key` in the array.
|
||||
//! \~russian Вставляет значение `value` с ключом `key` в массив.
|
||||
//! \~english Inserts value `value` for key `key`.
|
||||
//! \~russian Вставляет значение `value` по ключу `key`.
|
||||
//! \~\details
|
||||
//! \~english If an element with the key `key` already exists, it will be overwritten with the value `value`.
|
||||
//! \~russian Если элемент с ключом `key` уже существует, то он будет перезаписан на значение `value`.
|
||||
@@ -485,8 +469,8 @@ public:
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Inserts value `pair` in the array.
|
||||
//! \~russian Вставляет пару `pair` в массив.
|
||||
//! \~english Inserts entry `pair`.
|
||||
//! \~russian Вставляет элемент `pair`.
|
||||
//! \~\details
|
||||
//! \~english The first element of the pair is the key, and the second is the value.
|
||||
//! \~russian Первый элемент пары является ключом, а второй значением.
|
||||
@@ -526,8 +510,8 @@ public:
|
||||
return _value(i);
|
||||
}
|
||||
|
||||
//! \~english Returns an array of values of all elements
|
||||
//! \~russian Возвращает массив значений всех эелметнов
|
||||
//! \~english Returns values of all map entries.
|
||||
//! \~russian Возвращает значения всех элементов словаря.
|
||||
inline PIVector<T> values() const { return pim_content; }
|
||||
|
||||
//! \~english Returns the key of the first element
|
||||
@@ -544,8 +528,8 @@ public:
|
||||
return default_;
|
||||
}
|
||||
|
||||
//! \~english Returns an array of keys of all elements
|
||||
//! \~russian Возвращает массив ключей всех элементов
|
||||
//! \~english Returns keys of all map entries.
|
||||
//! \~russian Возвращает ключи всех элементов словаря.
|
||||
inline PIVector<Key> keys() const {
|
||||
PIVector<Key> ret;
|
||||
ret.reserve(pim_index.size());
|
||||
@@ -555,8 +539,8 @@ public:
|
||||
return ret;
|
||||
}
|
||||
|
||||
//! \~english Execute function `void f(const Key & key, const T & value)` for every element in array.
|
||||
//! \~russian Выполняет функцию `void f(const Key & key, const T & value)` для каждого элемента массива.
|
||||
//! \~english Calls `f` for every map entry.
|
||||
//! \~russian Вызывает `f` для каждого элемента словаря.
|
||||
inline void forEach(std::function<void(const Key & key, const T & value)> f) const {
|
||||
for (int i = 0; i < pim_index.size_s(); ++i) {
|
||||
const auto & mi(pim_index[i]);
|
||||
@@ -564,10 +548,8 @@ public:
|
||||
}
|
||||
}
|
||||
|
||||
//! \~english Сreates a new map PIMap<Key2, T2> populated with the results
|
||||
//! of calling a provided function `PIPair<Key2, T2> f(const Key & key, const T & value)` on every element in the calling array.
|
||||
//! \~russian Создаёт новый словарь PIMap<Key2, T2> с результатом вызова указанной функции
|
||||
//! `PIPair<Key2, T2> f(const Key & key, const T & value)` для каждого элемента массива.
|
||||
//! \~english Creates a new \a PIMap from results of applying `f` to each map entry.
|
||||
//! \~russian Создает новый \a PIMap из результатов применения `f` к каждому элементу словаря.
|
||||
template<typename Key2, typename T2>
|
||||
inline PIMap<Key2, T2> map(std::function<PIPair<Key2, T2>(const Key & key, const T & value)> f) const {
|
||||
PIMap<Key2, T2> ret;
|
||||
@@ -579,10 +561,8 @@ public:
|
||||
return ret;
|
||||
}
|
||||
|
||||
//! \~english Сreates a new array PIVector<ST> populated with the results
|
||||
//! of calling a provided function `ST f(const Key & key, const T & value)` on every element in the calling array.
|
||||
//! \~russian Создаёт новый массив PIVector<ST> с результатом вызова указанной функции
|
||||
//! `ST f(const Key & key, const T & value)` для каждого элемента массива.
|
||||
//! \~english Creates a new \a PIVector from results of applying `f` to each map entry.
|
||||
//! \~russian Создает новый \a PIVector из результатов применения `f` к каждому элементу словаря.
|
||||
template<typename ST>
|
||||
inline PIVector<ST> map(std::function<ST(const Key & key, const T & value)> f) const {
|
||||
PIVector<ST> ret;
|
||||
@@ -594,9 +574,9 @@ public:
|
||||
return ret;
|
||||
}
|
||||
|
||||
//! \~english Returns a new array with all elements
|
||||
//! \~english Returns a new map with all entries
|
||||
//! that pass the test implemented by the provided function `bool test(const Key & key, const T & value)`.
|
||||
//! \~russian Возвращает новый массив со всеми элементами,
|
||||
//! \~russian Возвращает новый словарь со всеми элементами,
|
||||
//! прошедшими проверку, задаваемую в передаваемой функции `bool test(const Key & key, const T & value)`.
|
||||
inline PIMap<Key, T> filter(std::function<bool(const Key & key, const T & value)> test) const {
|
||||
PIMap<Key, T> ret;
|
||||
@@ -688,17 +668,17 @@ private:
|
||||
//! \addtogroup Containers
|
||||
//! \{
|
||||
//! \class PIMapIteratorConst
|
||||
//! \brief
|
||||
//! \~\brief
|
||||
//! \~english Java-style iterator for \a PIMap.
|
||||
//! \~russian Итератор Java стиля для \a PIMap.
|
||||
//! \~\}
|
||||
//! \details
|
||||
//! \~english
|
||||
//! This class used to easy serial access keys and values in PIMap with read only permitions.
|
||||
//! Use constructor to create iterator, or use \a PIMap::makeIterator()
|
||||
//! Provides sequential read-only access to keys and values in \a PIMap.
|
||||
//! Use the constructor directly or call \a PIMap::makeIterator().
|
||||
//! \~russian
|
||||
//! Этот класс используется для удобного перебора ключей и значений всего словаря только для чтения.
|
||||
//! Можно использовать конструктор, в который передаётся словарь, или функцию словаря \a PIMap::makeIterator().
|
||||
//! Используется для последовательного перебора ключей и значений \a PIMap только для чтения.
|
||||
//! Можно использовать конструктор или вызвать \a PIMap::makeIterator().
|
||||
//! \~
|
||||
//! \code
|
||||
//! PIMap<int, PIString> m;
|
||||
@@ -758,17 +738,17 @@ private:
|
||||
//! \addtogroup Containers
|
||||
//! \{
|
||||
//! \class PIMapIteratorConstReverse
|
||||
//! \brief
|
||||
//! \~\brief
|
||||
//! \~english Java-style reverse iterator for \a PIMap.
|
||||
//! \~russian Итератор Java стиля для \a PIMap в обратном порядке.
|
||||
//! \~\}
|
||||
//! \details
|
||||
//! \~english
|
||||
//! This class used to easy serial reverse access keys and values in PIMap with read only permitions.
|
||||
//! Use constructor to create iterator, or use \a PIMap::makeReverseIterator().
|
||||
//! Provides sequential reverse read-only access to keys and values in \a PIMap.
|
||||
//! Use the constructor directly or call \a PIMap::makeReverseIterator().
|
||||
//! \~russian
|
||||
//! Этот класс используется для удобного перебора ключей и значений всего словаря в обратном порядке только для чтения.
|
||||
//! Можно использовать конструктор, в который передаётся словарь, или функцию словаря \a PIMap::makeReverseIterator().
|
||||
//! Используется для последовательного обратного перебора ключей и значений \a PIMap только для чтения.
|
||||
//! Можно использовать конструктор или вызвать \a PIMap::makeReverseIterator().
|
||||
//! \~
|
||||
//! \code
|
||||
//! PIMap<int, PIString> m;
|
||||
@@ -827,17 +807,17 @@ private:
|
||||
//! \addtogroup Containers
|
||||
//! \{
|
||||
//! \class PIMapIterator
|
||||
//! \brief
|
||||
//! \~\brief
|
||||
//! \~english Java-style iterator for \a PIMap.
|
||||
//! \~russian Итератор Java стиля для \a PIMap.
|
||||
//! \~\}
|
||||
//! \details
|
||||
//! \~english
|
||||
//! This class used to easy serial access keys and values in PIMap with write permitions.
|
||||
//! Use constructor to create iterator, or use \a PIMap::makeIterator()
|
||||
//! Provides sequential access to keys and values in \a PIMap with write access to values.
|
||||
//! Use the constructor directly or call \a PIMap::makeIterator().
|
||||
//! \~russian
|
||||
//! Этот класс используется для удобного перебора ключей и значений всего словаря с доступом на запись.
|
||||
//! Можно использовать конструктор, в который передаётся словарь, или функцию словаря \a PIMap::makeIterator().
|
||||
//! Используется для последовательного перебора ключей и значений \a PIMap с доступом на запись.
|
||||
//! Можно использовать конструктор или вызвать \a PIMap::makeIterator().
|
||||
//! \~
|
||||
//! \code
|
||||
//! PIMap<int, PIString> m;
|
||||
@@ -897,17 +877,17 @@ private:
|
||||
//! \addtogroup Containers
|
||||
//! \{
|
||||
//! \class PIMapIteratorReverse
|
||||
//! \brief
|
||||
//! \~\brief
|
||||
//! \~english Java-style reverse iterator for \a PIMap.
|
||||
//! \~russian Итератор Java стиля для \a PIMap в обратном порядке.
|
||||
//! \~\}
|
||||
//! \details
|
||||
//! \~english
|
||||
//! This class used to easy serial reverse access keys and values in PIMap with write permitions.
|
||||
//! Use constructor to create iterator, or use \a PIMap::makeReverseIterator().
|
||||
//! Provides sequential reverse access to keys and values in \a PIMap with write access to values.
|
||||
//! Use the constructor directly or call \a PIMap::makeReverseIterator().
|
||||
//! \~russian
|
||||
//! Этот класс используется для удобного перебора ключей и значений всего словаря в обратном порядке с доступом на запись.
|
||||
//! Можно использовать конструктор, в который передаётся словарь, или функцию словаря \a PIMap::makeReverseIterator().
|
||||
//! Используется для последовательного обратного перебора ключей и значений \a PIMap с доступом на запись.
|
||||
//! Можно использовать конструктор или вызвать \a PIMap::makeReverseIterator().
|
||||
//! \~
|
||||
//! \code
|
||||
//! PIMap<int, PIString> m;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! \addtogroup Containers
|
||||
//! \{
|
||||
//! \file pipair.h
|
||||
//! \~\file pipair.h
|
||||
//! \brief
|
||||
//! \~english Declares \a PIPair
|
||||
//! \~russian Объявление \a PIPair
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! \addtogroup Containers
|
||||
//! \{
|
||||
//! \file piqueue.h
|
||||
//! \~\file piqueue.h
|
||||
//! \brief
|
||||
//! \~english Declares \a PIQueue
|
||||
//! \~russian Объявление \a PIQueue
|
||||
@@ -40,78 +40,76 @@
|
||||
//! \addtogroup Containers
|
||||
//! \{
|
||||
//! \class PIQueue
|
||||
//! \brief
|
||||
//! \~english A container class inherited from the \a PIDeque with queue functionality.
|
||||
//! \~russian Класс контейнера наследованый от \a PIDeque с функциональностью очереди.
|
||||
//! \~\brief
|
||||
//! \~english Queue container built on top of \a PIDeque.
|
||||
//! \~russian Контейнер очереди, построенный поверх \a PIDeque.
|
||||
//! \~\}
|
||||
//! \details
|
||||
//! \~english The container is a array of elements organized according to the FIFO principle (first in, first out).
|
||||
//! Adds \a enqueue() and \dequeue() functions to \a PIDeque.
|
||||
//! \~russian Контейнер представляющий массив элементов, организованных по принципу FIFO (первым пришёл — первым вышел).
|
||||
//! Добавляет к \a PIDeque функции \a enqueue() и \a dequeue().
|
||||
//! \~english Stores elements in FIFO order and adds \a enqueue() and \a dequeue() to \a PIDeque.
|
||||
//! \~russian Хранит элементы в порядке FIFO и добавляет к \a PIDeque функции \a enqueue() и \a dequeue().
|
||||
//! \~\sa \a PIDeque
|
||||
template<typename T>
|
||||
class PIQueue: public PIDeque<T> {
|
||||
public:
|
||||
//! \~english Constructs an empty array.
|
||||
//! \~russian Создает пустой массив.
|
||||
//! \~english Constructs an empty queue.
|
||||
//! \~russian Создает пустую очередь.
|
||||
PIQueue() {}
|
||||
|
||||
//! \~english Puts an element on the queue.
|
||||
//! \~russian Кладёт элемент в очередь.
|
||||
//! \~english Enqueues `v`.
|
||||
//! \~russian Добавляет `v` в очередь.
|
||||
PIDeque<T> & enqueue(const T & v) {
|
||||
PIDeque<T>::push_front(v);
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Move an element on the queue.
|
||||
//! \~russian Перемещает элемент в очередь.
|
||||
//! \~english Moves `v` into the queue.
|
||||
//! \~russian Перемещает `v` в очередь.
|
||||
PIDeque<T> & enqueue(T && v) {
|
||||
PIDeque<T>::push_front(std::move(v));
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Retrieves and returns an element from the queue.
|
||||
//! \~russian Забирает и возвращает элемент из очереди.
|
||||
//! \~english Dequeues and returns the head element.
|
||||
//! \~russian Извлекает и возвращает головной элемент очереди.
|
||||
//! \~\details
|
||||
//! \note
|
||||
//! \~english This function assumes that the array isn't empty.
|
||||
//! Otherwise will be undefined behavior.
|
||||
//! \~russian Эта функция предполагает, что массив не пустой.
|
||||
//! \~english This function assumes that the queue is not empty.
|
||||
//! Otherwise behavior is undefined.
|
||||
//! \~russian Эта функция предполагает, что очередь не пуста.
|
||||
//! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти.
|
||||
T dequeue() { return PIDeque<T>::take_back(); }
|
||||
|
||||
//! \~english Head element of the queue.
|
||||
//! \~russian Головной (верхний) элемент очереди.
|
||||
//! \~english Returns the head element.
|
||||
//! \~russian Возвращает головной элемент очереди.
|
||||
//! \~\details
|
||||
//! \note
|
||||
//! \~english Returns a reference to the head element of the queue.
|
||||
//! This function assumes that the array isn't empty.
|
||||
//! Otherwise will be undefined behavior.
|
||||
//! \~russian Возвращает ссылку на головной (верхний) элемент очереди.
|
||||
//! Эта функция предполагает, что массив не пустой.
|
||||
//! \~english Returns a reference to the head element.
|
||||
//! This function assumes that the queue is not empty.
|
||||
//! Otherwise behavior is undefined.
|
||||
//! \~russian Возвращает ссылку на головной элемент очереди.
|
||||
//! Эта функция предполагает, что очередь не пуста.
|
||||
//! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти.
|
||||
T & head() { return PIDeque<T>::back(); }
|
||||
const T & head() const { return PIDeque<T>::back(); }
|
||||
|
||||
//! \~english Tail element of the queue.
|
||||
//! \~russian Хвостовой (нижний) элемент очереди.
|
||||
//! \~english Returns the tail element.
|
||||
//! \~russian Возвращает хвостовой элемент очереди.
|
||||
//! \~\details
|
||||
//! \~english Returns a reference to the tail element of the queue.
|
||||
//! This function assumes that the array isn't empty.
|
||||
//! Otherwise will be undefined behavior.
|
||||
//! \~russian Возвращает ссылку на хвостовой (нижний) элемент очереди.
|
||||
//! Эта функция предполагает, что массив не пустой.
|
||||
//! \~english Returns a reference to the tail element.
|
||||
//! This function assumes that the queue is not empty.
|
||||
//! Otherwise behavior is undefined.
|
||||
//! \~russian Возвращает ссылку на хвостовой элемент очереди.
|
||||
//! Эта функция предполагает, что очередь не пуста.
|
||||
//! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти.
|
||||
T & tail() { return PIDeque<T>::front(); }
|
||||
const T & tail() const { return PIDeque<T>::front(); }
|
||||
|
||||
//! \~english Converts \a PIQueue to \a PIVector.
|
||||
//! \~russian Преобразует \a PIQueue в \a PIVector.
|
||||
//! \~english Returns queue contents as \a PIVector.
|
||||
//! \~russian Возвращает содержимое очереди в виде \a PIVector.
|
||||
PIVector<T> toVector() const { return PIVector<T>(PIDeque<T>::data(), PIDeque<T>::size()); }
|
||||
|
||||
//! \~english Converts \a PIQueue to \a PIDeque.
|
||||
//! \~russian Преобразует \a PIQueue в \a PIDeque.
|
||||
//! \~english Returns queue contents as \a PIDeque.
|
||||
//! \~russian Возвращает содержимое очереди в виде \a PIDeque.
|
||||
PIDeque<T> toDeque() const { return PIDeque<T>(*this); }
|
||||
};
|
||||
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
/*! \file piset.h
|
||||
* \brief Set container
|
||||
*
|
||||
* This file declare PISet
|
||||
*/
|
||||
//! \addtogroup Containers
|
||||
//! \{
|
||||
//! \~\file piset.h
|
||||
//! \~\brief
|
||||
//! \~english Declares \a PISet
|
||||
//! \~russian Объявление \a PISet
|
||||
//! \~\}
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Set container
|
||||
@@ -27,13 +29,33 @@
|
||||
|
||||
#include "pimap.h"
|
||||
|
||||
/*! \brief Set of any type
|
||||
* \details This class used to store collection of unique elements
|
||||
* of any type. You can only add values to set with \a operator<< or
|
||||
* with function \a insert(). You can discover if value already in
|
||||
* set with \a operator[] or with function \a find(). These function
|
||||
* has logarithmic complexity.
|
||||
*/
|
||||
//! \addtogroup Containers
|
||||
//! \{
|
||||
//! \class PISet
|
||||
//! \~\brief
|
||||
//! \~english Set of unique values.
|
||||
//! \~russian Множество уникальных значений.
|
||||
//! \~\}
|
||||
//! \~\details
|
||||
//! \~english
|
||||
//! This class is used to store a collection of unique elements of any type.
|
||||
//! You can add values to the set using \a operator<< or the \a insert() function.
|
||||
//! You can check if a value already exists in the set using \a operator[] or the \a contains() function.
|
||||
//! These operations have logarithmic complexity.
|
||||
//! To iterate over all elements, use STL-style iterators \a begin() and \a end().
|
||||
//!
|
||||
//! The set is implemented as a wrapper around \a PIMap, where keys are the elements
|
||||
//! and values are dummy byte values (used only for storage).
|
||||
//! \~russian
|
||||
//! Этот класс используется для хранения коллекции уникальных элементов любого типа.
|
||||
//! Вы можете добавлять значения в множество с помощью \a operator<< или функции \a insert().
|
||||
//! Вы можете проверить, существует ли значение в множестве, используя \a operator[] или функцию \a contains().
|
||||
//! Эти операции имеют логарифмическую сложность.
|
||||
//! Для перебора всех элементов используйте итераторы в стиле STL \a begin() и \a end().
|
||||
//!
|
||||
//! Множество реализовано как обёртка над \a PIMap, где ключами являются элементы,
|
||||
//! а значениями являются фиктивные байтовые значения (используются только для хранения).
|
||||
//! \~\sa \a PIMap, \a PIVector
|
||||
template<typename T>
|
||||
class PISet: public PIMap<T, uchar> {
|
||||
typedef PIMap<T, uchar> _CSet;
|
||||
@@ -43,26 +65,31 @@ class PISet: public PIMap<T, uchar> {
|
||||
friend PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, PISet<T1> & v);
|
||||
|
||||
public:
|
||||
//! Contructs an empty set
|
||||
//! \~english Constructs an empty set.
|
||||
//! \~russian Создает пустое множество.
|
||||
PISet() {}
|
||||
|
||||
//! Contructs set with one element "value"
|
||||
//! \~english Constructs a set containing `value`.
|
||||
//! \~russian Создает множество, содержащее `value`.
|
||||
explicit PISet(const T & value) { _CSet::insert(value, 0); }
|
||||
|
||||
//! Contructs set with elements "v0" and "v1"
|
||||
//! \~english Constructs a set containing `v0` and `v1`.
|
||||
//! \~russian Создает множество, содержащее `v0` и `v1`.
|
||||
PISet(const T & v0, const T & v1) {
|
||||
_CSet::insert(v0, 0);
|
||||
_CSet::insert(v1, 0);
|
||||
}
|
||||
|
||||
//! Contructs set with elements "v0", "v1" and "v2"
|
||||
//! \~english Constructs a set containing `v0`, `v1` and `v2`.
|
||||
//! \~russian Создает множество, содержащее `v0`, `v1` и `v2`.
|
||||
PISet(const T & v0, const T & v1, const T & v2) {
|
||||
_CSet::insert(v0, 0);
|
||||
_CSet::insert(v1, 0);
|
||||
_CSet::insert(v2, 0);
|
||||
}
|
||||
|
||||
//! Contructs set with elements "v0", "v1", "v2" and "v3"
|
||||
//! \~english Constructs a set containing `v0`, `v1`, `v2` and `v3`.
|
||||
//! \~russian Создает множество, содержащее `v0`, `v1`, `v2` и `v3`.
|
||||
PISet(const T & v0, const T & v1, const T & v2, const T & v3) {
|
||||
_CSet::insert(v0, 0);
|
||||
_CSet::insert(v1, 0);
|
||||
@@ -71,6 +98,9 @@ public:
|
||||
}
|
||||
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Constant iterator over \a PISet elements.
|
||||
//! \~russian Константный итератор по элементам \a PISet.
|
||||
class const_iterator {
|
||||
friend class PISet<T>;
|
||||
|
||||
@@ -86,75 +116,140 @@ public:
|
||||
typedef std::ptrdiff_t difference_type;
|
||||
typedef std::random_access_iterator_tag iterator_category;
|
||||
|
||||
//! \~english Constructs an invalid iterator.
|
||||
//! \~russian Создает недействительный итератор.
|
||||
inline const_iterator(): parent(0), pos(0) {}
|
||||
|
||||
//! \~english Returns the current element.
|
||||
//! \~russian Возвращает текущий элемент.
|
||||
inline const T & operator*() const { return parent->pim_index[pos].key; }
|
||||
|
||||
//! \~english Provides access to the current element.
|
||||
//! \~russian Предоставляет доступ к текущему элементу.
|
||||
inline const T & operator->() const { return parent->pim_index[pos].key; }
|
||||
|
||||
//! \~english Moves iterator to the next element.
|
||||
//! \~russian Перемещает итератор к следующему элементу.
|
||||
inline const_iterator & operator++() {
|
||||
++pos;
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Returns iterator before incrementing.
|
||||
//! \~russian Возвращает итератор до увеличения.
|
||||
inline const_iterator operator++(int) {
|
||||
const auto tmp = *this;
|
||||
++*this;
|
||||
return tmp;
|
||||
}
|
||||
|
||||
//! \~english Moves iterator to the previous element.
|
||||
//! \~russian Перемещает итератор к предыдущему элементу.
|
||||
inline const_iterator & operator--() {
|
||||
--pos;
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Returns iterator before decrementing.
|
||||
//! \~russian Возвращает итератор до уменьшения.
|
||||
inline const_iterator operator--(int) {
|
||||
const auto tmp = *this;
|
||||
--*this;
|
||||
return tmp;
|
||||
}
|
||||
|
||||
//! \~english Adds offset of iterator `it`.
|
||||
//! \~russian Добавляет смещение итератора `it`.
|
||||
inline const_iterator & operator+=(const const_iterator & it) {
|
||||
pos += it.pos;
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Advances iterator by `p` elements.
|
||||
//! \~russian Сдвигает итератор вперед на `p` элементов.
|
||||
inline const_iterator & operator+=(size_t p) {
|
||||
pos += p;
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Subtracts offset of iterator `it`.
|
||||
//! \~russian Вычитает смещение итератора `it`.
|
||||
inline const_iterator & operator-=(const const_iterator & it) {
|
||||
pos -= it.pos;
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Moves iterator back by `p` elements.
|
||||
//! \~russian Сдвигает итератор назад на `p` элементов.
|
||||
inline const_iterator & operator-=(size_t p) {
|
||||
pos -= p;
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Returns iterator shifted back by `p`.
|
||||
//! \~russian Возвращает итератор, сдвинутый назад на `p`.
|
||||
friend inline const_iterator operator-(size_t p, const const_iterator & it) { return it - p; }
|
||||
|
||||
//! \~english Returns iterator shifted back by `p`.
|
||||
//! \~russian Возвращает итератор, сдвинутый назад на `p`.
|
||||
friend inline const_iterator operator-(const const_iterator & it, size_t p) {
|
||||
auto tmp = it;
|
||||
tmp -= p;
|
||||
return tmp;
|
||||
}
|
||||
|
||||
//! \~english Returns distance between iterators.
|
||||
//! \~russian Возвращает расстояние между итераторами.
|
||||
friend inline std::ptrdiff_t operator-(const const_iterator & it1, const const_iterator & it2) { return it1.pos - it2.pos; }
|
||||
|
||||
//! \~english Returns iterator shifted forward by `p`.
|
||||
//! \~russian Возвращает итератор, сдвинутый вперед на `p`.
|
||||
friend inline const_iterator operator+(size_t p, const const_iterator & it) { return it + p; }
|
||||
|
||||
//! \~english Returns iterator shifted forward by `p`.
|
||||
//! \~russian Возвращает итератор, сдвинутый вперед на `p`.
|
||||
friend inline const_iterator operator+(const const_iterator & it, size_t p) {
|
||||
auto tmp = it;
|
||||
tmp += p;
|
||||
return tmp;
|
||||
}
|
||||
|
||||
//! \~english Checks iterator equality.
|
||||
//! \~russian Проверяет равенство итераторов.
|
||||
inline bool operator==(const const_iterator & it) const { return (pos == it.pos); }
|
||||
|
||||
//! \~english Checks iterator inequality.
|
||||
//! \~russian Проверяет неравенство итераторов.
|
||||
inline bool operator!=(const const_iterator & it) const { return (pos != it.pos); }
|
||||
|
||||
//! \~english Checks whether `it1` is before `it2`.
|
||||
//! \~russian Проверяет, находится ли `it1` перед `it2`.
|
||||
friend inline bool operator<(const const_iterator & it1, const const_iterator & it2) { return it1.pos < it2.pos; }
|
||||
|
||||
//! \~english Checks whether `it1` is before or equal to `it2`.
|
||||
//! \~russian Проверяет, находится ли `it1` перед `it2` или совпадает с ним.
|
||||
friend inline bool operator<=(const const_iterator & it1, const const_iterator & it2) { return it1.pos <= it2.pos; }
|
||||
|
||||
//! \~english Checks whether `it1` is after `it2`.
|
||||
//! \~russian Проверяет, находится ли `it1` после `it2`.
|
||||
friend inline bool operator>(const const_iterator & it1, const const_iterator & it2) { return it1.pos > it2.pos; }
|
||||
|
||||
//! \~english Checks whether `it1` is after or equal to `it2`.
|
||||
//! \~russian Проверяет, находится ли `it1` после `it2` или совпадает с ним.
|
||||
friend inline bool operator>=(const const_iterator & it1, const const_iterator & it2) { return it1.pos >= it2.pos; }
|
||||
};
|
||||
|
||||
|
||||
//! \~english Returns iterator to the first element.
|
||||
//! \~russian Возвращает итератор на первый элемент.
|
||||
inline const_iterator begin() const { return const_iterator(this, 0); }
|
||||
|
||||
//! \~english Returns iterator following the last element.
|
||||
//! \~russian Возвращает итератор на элемент, следующий за последним.
|
||||
inline const_iterator end() const { return const_iterator(this, _CSet::size()); }
|
||||
|
||||
//! Contructs set from vector of elements
|
||||
//! \~english Constructs a set from vector `values`.
|
||||
//! \~russian Создает множество из вектора `values`.
|
||||
explicit PISet(const PIVector<T> & values) {
|
||||
if (values.isEmpty()) return;
|
||||
for (int i = 0; i < values.size_s(); ++i) {
|
||||
@@ -162,7 +257,8 @@ public:
|
||||
}
|
||||
}
|
||||
|
||||
//! Contructs set from deque of elements
|
||||
//! \~english Constructs a set from deque `values`.
|
||||
//! \~russian Создает множество из дека `values`.
|
||||
explicit PISet(const PIDeque<T> & values) {
|
||||
if (values.isEmpty()) return;
|
||||
for (int i = 0; i < values.size_s(); ++i) {
|
||||
@@ -172,65 +268,83 @@ public:
|
||||
|
||||
typedef T key_type;
|
||||
|
||||
//! \~english Inserts `t` into the set.
|
||||
//! \~russian Добавляет `t` в множество.
|
||||
PISet<T> & operator<<(const T & t) {
|
||||
_CSet::insert(t, 0);
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Moves `t` into the set.
|
||||
//! \~russian Перемещает `t` в множество.
|
||||
PISet<T> & operator<<(T && t) {
|
||||
_CSet::insert(std::move(t), 0);
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Inserts all elements from `other`.
|
||||
//! \~russian Добавляет все элементы из `other`.
|
||||
PISet<T> & operator<<(const PISet<T> & other) {
|
||||
(*(_CSet *)this) << *((_CSet *)&other);
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Tests if element `key` exists in the set.
|
||||
//! \~russian Проверяет наличие элемента `key` в массиве.
|
||||
//! \~english Tests whether element `t` exists in the set.
|
||||
//! \~russian Проверяет наличие элемента `t` в множестве.
|
||||
inline bool contains(const T & t) const { return _CSet::contains(t); }
|
||||
|
||||
//! Returns if element "t" exists in this set
|
||||
//! \~english Checks whether element `t` exists in the set.
|
||||
//! \~russian Проверяет наличие элемента `t` в множестве.
|
||||
bool operator[](const T & t) const { return _CSet::contains(t); }
|
||||
|
||||
//! Returns if element "t" exists in this set
|
||||
//! \~english Removes element `t` from the set.
|
||||
//! \~russian Удаляет элемент `t` из множества.
|
||||
PISet<T> & remove(const T & t) {
|
||||
_CSet::remove(t);
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! Unite set with "v"
|
||||
//! \~english Unites the set with `v`.
|
||||
//! \~russian Объединяет множество с `v`.
|
||||
PISet<T> & unite(const PISet<T> & v) {
|
||||
for (const auto & i: v)
|
||||
_CSet::insert(i, 0);
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! Subtract set with "v"
|
||||
//! \~english Removes all elements present in `v`.
|
||||
//! \~russian Удаляет все элементы, присутствующие в `v`.
|
||||
PISet<T> & subtract(const PISet<T> & v) {
|
||||
for (const auto & i: v)
|
||||
_CSet::remove(i);
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! Intersect set with "v"
|
||||
//! \~english Leaves only elements also present in `v`.
|
||||
//! \~russian Оставляет только элементы, которые есть и в `v`.
|
||||
PISet<T> & intersect(const PISet<T> & v) {
|
||||
_CSet::removeWhere([&v](const T & k, uchar) { return !v.contains(k); });
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! Unite set with "v"
|
||||
//! \~english Same as \a unite().
|
||||
//! \~russian Синоним \a unite().
|
||||
PISet<T> & operator+=(const PISet<T> & v) { return unite(v); }
|
||||
|
||||
//! Unite set with "v"
|
||||
//! \~english Same as \a unite().
|
||||
//! \~russian Синоним \a unite().
|
||||
PISet<T> & operator|=(const PISet<T> & v) { return unite(v); }
|
||||
|
||||
//! Subtract set with "v"
|
||||
//! \~english Same as \a subtract().
|
||||
//! \~russian Синоним \a subtract().
|
||||
PISet<T> & operator-=(const PISet<T> & v) { return subtract(v); }
|
||||
|
||||
//! Intersect set with "v"
|
||||
//! \~english Same as \a intersect().
|
||||
//! \~russian Синоним \a intersect().
|
||||
PISet<T> & operator&=(const PISet<T> & v) { return intersect(v); }
|
||||
|
||||
//! Returns content of set as PIVector
|
||||
//! \~english Returns set contents as \a PIVector.
|
||||
//! \~russian Возвращает содержимое множества в виде \a PIVector.
|
||||
PIVector<T> toVector() const {
|
||||
PIVector<T> ret;
|
||||
for (const auto & i: *this)
|
||||
@@ -238,7 +352,8 @@ public:
|
||||
return ret;
|
||||
}
|
||||
|
||||
//! Returns content of set as PIDeque
|
||||
//! \~english Returns set contents as \a PIDeque.
|
||||
//! \~russian Возвращает содержимое множества в виде \a PIDeque.
|
||||
PIDeque<T> toDeque() const {
|
||||
PIDeque<T> ret;
|
||||
for (const auto & i: *this)
|
||||
@@ -248,7 +363,9 @@ public:
|
||||
};
|
||||
|
||||
|
||||
//! \relatesalso PISet \brief Returns unite of two sets
|
||||
//! \relatesalso PISet
|
||||
//! \~english Returns union of two sets.
|
||||
//! \~russian Возвращает объединение двух множеств.
|
||||
template<typename T>
|
||||
PISet<T> operator+(const PISet<T> & v0, const PISet<T> & v1) {
|
||||
PISet<T> ret(v0);
|
||||
@@ -256,7 +373,9 @@ PISet<T> operator+(const PISet<T> & v0, const PISet<T> & v1) {
|
||||
return ret;
|
||||
}
|
||||
|
||||
//! \relatesalso PISet \brief Returns subtraction of two sets
|
||||
//! \relatesalso PISet
|
||||
//! \~english Returns difference of two sets.
|
||||
//! \~russian Возвращает разность двух множеств.
|
||||
template<typename T>
|
||||
PISet<T> operator-(const PISet<T> & v0, const PISet<T> & v1) {
|
||||
PISet<T> ret(v0);
|
||||
@@ -264,7 +383,9 @@ PISet<T> operator-(const PISet<T> & v0, const PISet<T> & v1) {
|
||||
return ret;
|
||||
}
|
||||
|
||||
//! \relatesalso PISet \brief Returns unite of two sets
|
||||
//! \relatesalso PISet
|
||||
//! \~english Returns union of two sets.
|
||||
//! \~russian Возвращает объединение двух множеств.
|
||||
template<typename T>
|
||||
PISet<T> operator|(const PISet<T> & v0, const PISet<T> & v1) {
|
||||
PISet<T> ret(v0);
|
||||
@@ -272,7 +393,9 @@ PISet<T> operator|(const PISet<T> & v0, const PISet<T> & v1) {
|
||||
return ret;
|
||||
}
|
||||
|
||||
//! \relatesalso PISet \brief Returns intersetion of two sets
|
||||
//! \relatesalso PISet
|
||||
//! \~english Returns intersection of two sets.
|
||||
//! \~russian Возвращает пересечение двух множеств.
|
||||
template<typename T>
|
||||
PISet<T> operator&(const PISet<T> & v0, const PISet<T> & v1) {
|
||||
PISet<T> ret(v0);
|
||||
@@ -281,6 +404,9 @@ PISet<T> operator&(const PISet<T> & v0, const PISet<T> & v1) {
|
||||
}
|
||||
|
||||
|
||||
//! \relatesalso PISet
|
||||
//! \~english Output operator to \a PICout.
|
||||
//! \~russian Оператор вывода в \a PICout.
|
||||
template<typename Type>
|
||||
inline PICout operator<<(PICout s, const PISet<Type> & v) {
|
||||
s.space();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! \addtogroup Containers
|
||||
//! \{
|
||||
//! \file pistack.h
|
||||
//! \~\file pistack.h
|
||||
//! \brief
|
||||
//! \~english Declares \a PIStack
|
||||
//! \~russian Объявление \a PIStack
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! \addtogroup Containers
|
||||
//! \{
|
||||
//! \file pivector.h
|
||||
//! \~\file pivector.h
|
||||
//! \brief
|
||||
//! \~english Declares \a PIVector
|
||||
//! \~russian Объявление \a PIVector
|
||||
@@ -184,7 +184,7 @@ public:
|
||||
//! \endcode
|
||||
inline PIVector(size_t size, std::function<T(size_t i)> f) {
|
||||
PIINTROSPECTION_CONTAINER_NEW(T, sizeof(T))
|
||||
expand(size, f);
|
||||
expand(size, std::move(f));
|
||||
}
|
||||
|
||||
//! \~english Move constructor.
|
||||
@@ -725,7 +725,7 @@ public:
|
||||
//! заданному в передаваемой функции `test`, или `def` если такого элемента нет.
|
||||
//! \~\sa \a indexWhere()
|
||||
inline const T & atWhere(std::function<bool(const T & e)> test, ssize_t start = 0, const T & def = T()) const {
|
||||
const ssize_t i = indexWhere(test, start);
|
||||
const ssize_t i = indexWhere(std::move(test), start);
|
||||
if (i < 0)
|
||||
return def;
|
||||
else
|
||||
@@ -739,7 +739,7 @@ public:
|
||||
//! заданному в передаваемой функции `test`, или `def` если такого элемента нет.
|
||||
//! \~\sa \a lastIndexWhere()
|
||||
inline const T & lastAtWhere(std::function<bool(const T & e)> test, ssize_t start = -1, const T & def = T()) const {
|
||||
const ssize_t i = lastIndexWhere(test, start);
|
||||
const ssize_t i = lastIndexWhere(std::move(test), start);
|
||||
if (i < 0)
|
||||
return def;
|
||||
else
|
||||
@@ -835,8 +835,8 @@ public:
|
||||
//! piCout << v.contains({1,4}); // true
|
||||
//! piCout << v.contains({1,5}); // false
|
||||
//! \endcode
|
||||
//! \~\sa \a every(), \a any(), \a entries(), \a forEach()
|
||||
inline bool contains(const PIVector<T> & v, ssize_t start = 0) const {
|
||||
//! \~\sa \a every(), \a any(), \a entries(), \a forEach(), \a contains()
|
||||
inline bool containsAll(const PIVector<T> & v, ssize_t start = 0) const {
|
||||
if (start < 0) {
|
||||
start = piv_size + start;
|
||||
if (start < 0) start = 0;
|
||||
@@ -854,6 +854,24 @@ public:
|
||||
return true;
|
||||
}
|
||||
|
||||
//! \~english Tests if any element of `v` exists in the array.
|
||||
//! \~russian Проверяет наличие хотя бы одного из элементов `v` в массиве.
|
||||
//! \~\sa \a containsAll(), \a contains()
|
||||
inline bool containsAny(const PIVector<T> & v, ssize_t start = 0) const {
|
||||
if (start < 0) {
|
||||
start = piv_size + start;
|
||||
if (start < 0) start = 0;
|
||||
}
|
||||
for (const T & e: v) {
|
||||
for (size_t i = start; i < piv_size; ++i) {
|
||||
if (e == piv_data[i]) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
//! \~english Count elements equal `e` in the array.
|
||||
//! \~russian Подсчитывает количество элементов, совпадающих с элементом `e` в массиве.
|
||||
//! \~\details
|
||||
@@ -1249,7 +1267,7 @@ public:
|
||||
deleteT(piv_data + new_size, piv_size - new_size);
|
||||
piv_size = new_size;
|
||||
} else if (new_size > piv_size) {
|
||||
expand(new_size, f);
|
||||
expand(new_size, std::move(f));
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
@@ -1303,14 +1321,16 @@ public:
|
||||
//! piCout << v; // {1, 3, 7, 5}
|
||||
//! \endcode
|
||||
//! \~\sa \a append(), \a prepend(), \a remove()
|
||||
inline PIVector<T> & insert(size_t index, const T & e = T()) {
|
||||
alloc(piv_size + 1);
|
||||
if (index < piv_size - 1) {
|
||||
const size_t os = piv_size - index - 1;
|
||||
memmove(reinterpret_cast<void *>(piv_data + index + 1), reinterpret_cast<const void *>(piv_data + index), os * sizeof(T));
|
||||
inline PIVector<T> & insert(size_t index, const T & e = T(), size_t count = 1) {
|
||||
alloc(piv_size + count);
|
||||
if (index < piv_size - count) {
|
||||
const size_t os = piv_size - index - count;
|
||||
memmove(reinterpret_cast<void *>(piv_data + index + count), reinterpret_cast<const void *>(piv_data + index), os * sizeof(T));
|
||||
}
|
||||
PIINTROSPECTION_CONTAINER_USED(T, count)
|
||||
for (size_t i = 0; i < count; ++i) {
|
||||
elementNew(piv_data + index + i, e);
|
||||
}
|
||||
PIINTROSPECTION_CONTAINER_USED(T, 1)
|
||||
elementNew(piv_data + index, e);
|
||||
return *this;
|
||||
}
|
||||
|
||||
@@ -1466,7 +1486,7 @@ public:
|
||||
//! \endcode
|
||||
//! \~\sa \a sort()
|
||||
inline PIVector<T> & sort(std::function<bool(const T & a, const T & b)> comp) {
|
||||
std::stable_sort(begin(), end(), comp);
|
||||
std::stable_sort(begin(), end(), std::move(comp));
|
||||
return *this;
|
||||
}
|
||||
|
||||
@@ -1579,7 +1599,13 @@ public:
|
||||
//! \endcode
|
||||
//! \~\sa \a remove(), \a removeOne(), \a removeWhere()
|
||||
inline PIVector<T> & removeWhere(std::function<bool(const T & e)> test) {
|
||||
ssize_t j = indexWhere(test);
|
||||
ssize_t j = -1;
|
||||
for (size_t i = 0; i < piv_size; ++i) {
|
||||
if (test(piv_data[i])) {
|
||||
j = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (j != -1) {
|
||||
for (size_t i = j + 1; i < piv_size; ++i) {
|
||||
if (!test(piv_data[i])) {
|
||||
|
||||
@@ -1,8 +1,15 @@
|
||||
/*! \file pivector2d.h
|
||||
* \brief 2D wrapper around PIVector
|
||||
*
|
||||
* This file declares PIVector
|
||||
*/
|
||||
//! \addtogroup Containers
|
||||
//! \{
|
||||
//! \~\file pivector2d.h
|
||||
//! \brief
|
||||
//! \~english Declares \a PIVector2D
|
||||
//! \~russian Объявление \a PIVector2D
|
||||
//! \~\authors
|
||||
//! \~english
|
||||
//! Andrey Bychkov work.a.b@yandex.ru;
|
||||
//! \~russian
|
||||
//! Андрей Бычков work.a.b@yandex.ru;
|
||||
//! \~\}
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
2D wrapper around PIVector
|
||||
@@ -27,29 +34,111 @@
|
||||
|
||||
#include "pivector.h"
|
||||
|
||||
/*! \brief 2D array,
|
||||
* \details This class used to store 2D array of any type elements as plain vector.
|
||||
* You can read/write any element via operators [][], first dimension - row, second - column.
|
||||
* The first dimension is Row, and you can operate with Row as PIVector<T>: modify any element, assign to another Row and etc.
|
||||
* You can't add values to array, but you can modify any elements or create another PIVector2D.
|
||||
* PIVector2D has constructors from PIVector<T> and PIVector<PIVector<T> >
|
||||
*/
|
||||
//! \addtogroup Containers
|
||||
//! \{
|
||||
//! \class PIVector2D
|
||||
//! \brief
|
||||
//! \~english 2D array container.
|
||||
//! \~russian Двумерный контейнер-массив.
|
||||
//! \details
|
||||
//! \~english
|
||||
//! This class is used to store a 2D array of elements of any type as a single continuous block of memory (a plain PIVector).
|
||||
//! Elements can be accessed using the `[][]` operators, where the first index is the row and the second is the column.
|
||||
//! Rows can be manipulated as \a PIVector objects, allowing modification of individual elements or assignment of entire rows.
|
||||
//! You cannot directly add or remove elements to change the dimensions of the array after construction
|
||||
//! (use \a resize(), \a addRow(), \a removeRow(), \a removeColumn() instead), but you can modify the values of existing elements.
|
||||
//! \~russian
|
||||
//! Этот класс используется для хранения двумерного массива элементов любого типа в виде единого непрерывного блока памяти (обычного
|
||||
//! \a PIVector). Доступ к элементам осуществляется с помощью операторов `[][]`, где первый индекс — это строка, а второй — столбец. Со
|
||||
//! строками можно работать как с объектами \a PIVector, что позволяет изменять отдельные элементы или присваивать целые строки. Нельзя
|
||||
//! напрямую добавлять или удалять элементы, чтобы изменить размеры массива после создания (используйте \a resize(), \a addRow(), \a
|
||||
//! removeRow(), \a removeColumn() для этого), но можно изменять значения существующих элементов.
|
||||
|
||||
|
||||
template<typename T>
|
||||
class PIVector2D {
|
||||
public:
|
||||
//! \brief
|
||||
//! \~english Index structure for 2D array elements (row, column).
|
||||
//! \~russian Структура индекса для элементов двумерного массива (строка, столбец).
|
||||
struct Index {
|
||||
//! \~english Row index in the 2D array.
|
||||
//! \~russian Индекс строки в двумерном массиве.
|
||||
ssize_t row = -1;
|
||||
//! \~english Column index in the 2D array.
|
||||
//! \~russian Индекс столбца в двумерном массиве.
|
||||
ssize_t col = -1;
|
||||
|
||||
//! \~english Default constructor. Initializes row and col to -1 (invalid index).
|
||||
//! \~russian Конструктор по умолчанию. Инициализирует row и col значениями -1 (некорректный индекс).
|
||||
inline Index() = default;
|
||||
//! \~english Constructs an Index with the given row and column values.
|
||||
//! \~russian Создаёт Index с заданными значениями строки и столбца.
|
||||
inline Index(ssize_t r, ssize_t c): row(r), col(c) {}
|
||||
|
||||
//! \~english Checks if the index is valid (both row and column are non-negative).
|
||||
//! \~russian Проверяет, является ли индекс корректным (строка и столбец неотрицательны).
|
||||
//! \~\sa isNotValid()
|
||||
inline bool isValid() const { return row >= 0 && col >= 0; }
|
||||
|
||||
//! \~english Checks if the index is invalid (either row or column is negative).
|
||||
//! \~russian Проверяет, является ли индекс некорректным (строка или столбец отрицательны).
|
||||
//! \~\sa isValid()
|
||||
inline bool isNotValid() const { return !isValid(); }
|
||||
};
|
||||
|
||||
//! \~english Constructs an empty 2D array. No memory is allocated.
|
||||
//! \~russian Создаёт пустой двумерный массив. Память не выделяется.
|
||||
//! \details
|
||||
//! \~english After this constructor, \a rows() and \a cols() return 0, and \a isEmpty() returns true.
|
||||
//! \~russian После этого конструктора \a rows() и \a cols() возвращают 0, а \a isEmpty() возвращает true.
|
||||
//! \~\sa PIVector::PIVector()
|
||||
inline PIVector2D() { rows_ = cols_ = 0; }
|
||||
|
||||
//! \~english Constructs a 2D array with the given dimensions, filled with copies of `f`.
|
||||
//! \~russian Создаёт двумерный массив заданного размера, заполненный копиями `f`.
|
||||
//! \details
|
||||
//! \~english The underlying storage is a single contiguous block of memory of size `rows * cols`.
|
||||
//! All elements are initialized with the value `f`.
|
||||
//! \~russian Внутреннее хранилище представляет собой единый непрерывный блок памяти размером `rows * cols`.
|
||||
//! Все элементы инициализируются значением `f`.
|
||||
//! \~\sa PIVector::PIVector(size_t, const T&)
|
||||
inline PIVector2D(size_t rows, size_t cols, const T & f = T()) {
|
||||
rows_ = rows;
|
||||
cols_ = cols;
|
||||
mat.resize(rows * cols, f);
|
||||
}
|
||||
|
||||
//! \~english Constructs a 2D array from an existing 1D vector, reshaping it.
|
||||
//! \~russian Создаёт двумерный массив из существующего одномерного вектора, изменяя его форму.
|
||||
//! \details
|
||||
//! \~english The constructor copies the data from `v` into the internal flat vector.
|
||||
//! If `v` is larger than `rows * cols`, the excess elements are ignored (the vector is truncated).
|
||||
//! If `v` is smaller, other values filled whith default cunstructor T()
|
||||
//! \~russian Конструктор копирует данные из `v` во внутренний плоский вектор.
|
||||
//! Если `v` больше, чем `rows * cols`, лишние элементы игнорируются (вектор обрезается).
|
||||
//! Если `v` меньше, остальные значения будут заполнены из конструктора по умолчанию T()
|
||||
//! \~\sa PIVector::PIVector(const PIVector&), reshape()
|
||||
inline PIVector2D(size_t rows, size_t cols, const PIVector<T> & v): rows_(rows), cols_(cols), mat(v) { mat.resize(rows * cols); }
|
||||
|
||||
//! \~english Move constructs a 2D array from an existing 1D vector, reshaping it.
|
||||
//! \~russian Конструктор перемещения из существующего одномерного вектора, изменяя его форму.
|
||||
//! \details
|
||||
//! \~english The data is moved from `v` into the internal flat vector, avoiding a copy.
|
||||
//! After construction, `v` is left in a valid but unspecified state.
|
||||
//! \~russian Данные перемещаются из `v` во внутренний плоский вектор, что позволяет избежать копирования.
|
||||
//! После завершения конструктора `v` остаётся в корректном, но неопределённом состоянии.
|
||||
//! \~\sa PIVector::PIVector(PIVector&&)
|
||||
inline PIVector2D(size_t rows, size_t cols, PIVector<T> && v): rows_(rows), cols_(cols), mat(std::move(v)) { mat.resize(rows * cols); }
|
||||
|
||||
//! \~english Constructs a 2D array from a vector of vectors (jagged array). Assumes all inner vectors have the same size.
|
||||
//! \~russian Создаёт двумерный массив из вектора векторов (рваного массива). Предполагается, что все внутренние векторы имеют
|
||||
//! одинаковый размер.
|
||||
//! \details
|
||||
//! \~english If the input is empty, the constructed array is also empty. Otherwise, the number of columns is taken from the size of the
|
||||
//! first inner vector. All inner vectors are concatenated in the internal flat storage.
|
||||
//! \~russian Если входной массив пуст, создаётся пустой двумерный массив. В противном случае количество столбцов берётся из размера
|
||||
//! первого внутреннего вектора. Все внутренние векторы конкатенируются во внутреннем плоском хранилище. \sa PIVector::append()
|
||||
inline PIVector2D(const PIVector<PIVector<T>> & v) {
|
||||
rows_ = v.size();
|
||||
if (rows_) {
|
||||
@@ -63,219 +152,858 @@ public:
|
||||
if (mat.isEmpty()) rows_ = cols_ = 0;
|
||||
}
|
||||
|
||||
//! \~english Returns the number of rows in the 2D array.
|
||||
//! \~russian Возвращает количество строк в двумерном массиве.
|
||||
//! \return Number of rows.
|
||||
//! \details
|
||||
//! \~english The result is always non-negative. If the array is empty, returns 0.
|
||||
//! \~russian Результат всегда неотрицательный. Если массив пуст, возвращает 0.
|
||||
//! \~\sa cols(), size(), PIVector::size()
|
||||
inline size_t rows() const { return rows_; }
|
||||
|
||||
//! \~english Returns the number of columns in the 2D array.
|
||||
//! \~russian Возвращает количество столбцов в двумерном массиве.
|
||||
//! \return Number of columns.
|
||||
//! \details
|
||||
//! \~english The result is always non-negative. If the array is empty, returns 0.
|
||||
//! \~russian Результат всегда неотрицательный. Если массив пуст, возвращает 0.
|
||||
//! \~\sa rows(), size(), PIVector::size()
|
||||
inline size_t cols() const { return cols_; }
|
||||
|
||||
//! \~english Returns the total number of elements (`rows * cols`).
|
||||
//! \~russian Возвращает общее количество элементов (`строки * столбцы`).
|
||||
//! \return Total number of elements.
|
||||
//! \details
|
||||
//! \~english This is equivalent to the size of the underlying flat vector.
|
||||
//! \~russian Это эквивалентно размеру внутреннего плоского вектора.
|
||||
//! \~\sa rows(), cols(), PIVector::size()
|
||||
inline size_t size() const { return mat.size(); }
|
||||
|
||||
//! \~english Returns the total number of elements as a signed value.
|
||||
//! \~russian Возвращает общее количество элементов в виде знакового числа.
|
||||
//! \return Signed size.
|
||||
//! \~\sa size(), PIVector::size_s()
|
||||
inline ssize_t size_s() const { return mat.size_s(); }
|
||||
|
||||
//! \~english Returns the total number of elements (same as \a size()).
|
||||
//! \~russian Возвращает общее количество элементов (то же, что и \a size()).
|
||||
//! \return Total number of elements.
|
||||
//! \~\sa size(), PIVector::length()
|
||||
inline size_t length() const { return mat.length(); }
|
||||
|
||||
//! \~english Returns the number of elements that the underlying container has currently allocated space for.
|
||||
//! \~russian Возвращает количество элементов, для которого сейчас выделена память во внутреннем контейнере.
|
||||
//! \return Capacity of the flat vector.
|
||||
//! \details
|
||||
//! \~english This value may be larger than \a size(). It indicates how many elements can be added before a reallocation is needed.
|
||||
//! \~russian Это значение может быть больше, чем \a size(). Оно показывает, сколько элементов можно добавить до того, как потребуется
|
||||
//! перераспределение памяти. \sa reserve(), PIVector::capacity()
|
||||
inline size_t capacity() const { return mat.capacity(); }
|
||||
|
||||
//! \~english Checks if the array has no elements.
|
||||
//! \~russian Проверяет, пуст ли массив.
|
||||
//! \return \c true if the array is empty, \c false otherwise.
|
||||
//! \details
|
||||
//! \~english An empty array has both rows and columns equal to 0.
|
||||
//! \~russian Пустой массив имеет и строки, и столбцы равные 0.
|
||||
//! \~\sa isNotEmpty(), PIVector::isEmpty()
|
||||
inline bool isEmpty() const { return mat.isEmpty(); }
|
||||
|
||||
//! \~english Checks if the array has at least one element.
|
||||
//! \~russian Проверяет, не пуст ли массив.
|
||||
//! \return \c true if the array is not empty, \c false otherwise.
|
||||
//! \~\sa isEmpty(), PIVector::isNotEmpty()
|
||||
inline bool isNotEmpty() const { return mat.isNotEmpty(); }
|
||||
|
||||
class Row {
|
||||
friend class PIVector2D<T>;
|
||||
class RowConst;
|
||||
class ColConst;
|
||||
class Row;
|
||||
class Col;
|
||||
|
||||
private:
|
||||
inline Row(PIVector2D<T> * p, size_t row): p_(&(p->mat)) {
|
||||
st_ = p->cols_ * row;
|
||||
sz_ = p->cols_;
|
||||
}
|
||||
PIVector<T> * p_;
|
||||
size_t st_, sz_;
|
||||
|
||||
public:
|
||||
inline size_t size() const { return sz_; }
|
||||
inline T & operator[](size_t index) { return (*p_)[st_ + index]; }
|
||||
inline const T & operator[](size_t index) const { return (*p_)[st_ + index]; }
|
||||
inline T * data(size_t index = 0) { return p_->data(st_ + index); }
|
||||
inline const T * data(size_t index = 0) const { return p_->data(st_ + index); }
|
||||
inline Row & operator=(const Row & other) {
|
||||
if (p_ == other.p_ && st_ == other.st_) return *this;
|
||||
const size_t sz = piMin<size_t>(sz_, other.sz_);
|
||||
p_->_copyRaw(p_->data(st_), other.data(), sz);
|
||||
return *this;
|
||||
}
|
||||
inline Row & operator=(const PIVector<T> & other) {
|
||||
const size_t sz = piMin<size_t>(sz_, other.size());
|
||||
p_->_copyRaw(p_->data(st_), other.data(), sz);
|
||||
return *this;
|
||||
}
|
||||
inline PIVector<T> toVector() const { return PIVector<T>(p_->data(st_), sz_); }
|
||||
};
|
||||
|
||||
class Col {
|
||||
friend class PIVector2D<T>;
|
||||
|
||||
private:
|
||||
inline Col(PIVector2D<T> * p, size_t row): p_(&(p->mat)) {
|
||||
step_ = p->cols_;
|
||||
row_ = row;
|
||||
sz_ = p->rows_;
|
||||
}
|
||||
PIVector<T> * p_;
|
||||
size_t step_, row_, sz_;
|
||||
|
||||
public:
|
||||
inline size_t size() const { return sz_; }
|
||||
inline T & operator[](size_t index) { return (*p_)[index * step_ + row_]; }
|
||||
inline const T & operator[](size_t index) const { return (*p_)[index * step_ + row_]; }
|
||||
inline T * data(size_t index = 0) { return p_->data(index * step_ + row_); }
|
||||
inline const T * data(size_t index = 0) const { return p_->data(index * step_ + row_); }
|
||||
inline Col & operator=(const Col & other) {
|
||||
if (p_ == other.p_ && row_ == other.row_) return *this;
|
||||
const size_t sz = piMin<size_t>(sz_, other.sz_);
|
||||
for (int i = 0; i < sz; ++i)
|
||||
(*p_)[i * step_ + row_] = other[i];
|
||||
return *this;
|
||||
}
|
||||
inline Row & operator=(const PIVector<T> & other) {
|
||||
const size_t sz = piMin<size_t>(sz_, other.size());
|
||||
for (int i = 0; i < sz; ++i)
|
||||
(*p_)[i * step_ + row_] = other[i];
|
||||
return *this;
|
||||
}
|
||||
inline PIVector<T> toVector() const {
|
||||
PIVector<T> ret;
|
||||
ret.reserve(sz_);
|
||||
for (size_t i = 0; i < sz_; i++)
|
||||
ret << (*p_)[i * step_ + row_];
|
||||
return ret;
|
||||
}
|
||||
};
|
||||
|
||||
//! \class RowConst
|
||||
//! \brief
|
||||
//! \~english Proxy class representing a single read-only row in a \a PIVector2D.
|
||||
//! \~russian Прокси-класс, представляющий одну строку в \a PIVector2D только для чтения.
|
||||
//! \details
|
||||
//! \~english Returned by const \a operator[] or \a row(). Provides const access to row elements.
|
||||
//! \~russian Возвращается константными версиями \a operator[] или \a row(). Предоставляет константный доступ к элементам строки.
|
||||
//! \~\sa Row, ColConst
|
||||
class RowConst {
|
||||
friend class PIVector2D<T>;
|
||||
|
||||
private:
|
||||
inline RowConst(const PIVector2D<T> * p, size_t row): p_(&(p->mat)) {
|
||||
st_ = p->cols_ * row;
|
||||
sz_ = p->cols_;
|
||||
}
|
||||
protected:
|
||||
inline RowConst(const PIVector2D<T> * p, size_t row): p_(&(p->mat)), st_(p->cols_ * row), sz_(p->cols_) {}
|
||||
const PIVector<T> * p_;
|
||||
size_t st_, sz_;
|
||||
const size_t st_, sz_;
|
||||
|
||||
public:
|
||||
//! \~english Copy constructor from modifiable Row to read-only RowConst.
|
||||
//! \~russian Конструктор копирования из модифицируемого класса Row в константный RowConst.
|
||||
//! \~\sa Row
|
||||
inline RowConst(const PIVector2D<T>::Row & r): p_(r.p_), st_(r.st_), sz_(r.sz_) {}
|
||||
|
||||
//! \~english Size of the row (number of columns).
|
||||
//! \~russian Размер строки (количество столбцов).
|
||||
inline size_t size() const { return sz_; }
|
||||
|
||||
//! \~english Const access to the element at the given column index within the row.
|
||||
//! \~russian Константный доступ к элементу по заданному индексу столбца в строке.
|
||||
inline const T & operator[](size_t index) const { return (*p_)[st_ + index]; }
|
||||
|
||||
//! \~english Returns a const pointer to the row data starting at an optional offset.
|
||||
//! \~russian Возвращает константный указатель на данные строки, начиная с опционального смещения.
|
||||
inline const T * data(size_t index = 0) const { return p_->data(st_ + index); }
|
||||
|
||||
//! \~english Converts the row to a \a PIVector.
|
||||
//! \~russian Преобразует строку в \a PIVector.
|
||||
inline PIVector<T> toVector() const { return PIVector<T>(p_->data(st_), sz_); }
|
||||
|
||||
//! \~english Returns the first index of element `e` in the row, starting from `start`.
|
||||
//! \~russian Возвращает первый индекс элемента `e` в строке, начиная с позиции `start`.
|
||||
//! \details
|
||||
//! \~english See \a PIVector::indexOf() for details on negative start handling.
|
||||
//! \~russian Подробнее об обработке отрицательного `start` см. \a PIVector::indexOf().
|
||||
//! \~\sa PIVector::indexOf()
|
||||
inline ssize_t indexOf(const T & e, ssize_t start = 0) const {
|
||||
if (start < 0) start = 0;
|
||||
for (size_t i = (size_t)start; i < sz_; ++i) {
|
||||
if ((*p_)[st_ + i] == e) return (ssize_t)i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
//! \~english Returns the last index of element `e` in the row, searching backwards from `start`.
|
||||
//! \~russian Возвращает последний индекс элемента `e` в строке, выполняя поиск в обратном направлении от `start`.
|
||||
//! \return Index if found, -1 otherwise.
|
||||
//! \~\sa PIVector::lastIndexOf()
|
||||
inline ssize_t lastIndexOf(const T & e, ssize_t start = -1) const {
|
||||
ssize_t from = (start < 0 || (size_t)start >= sz_) ? (ssize_t)sz_ - 1 : start;
|
||||
for (ssize_t i = from; i >= 0; --i) {
|
||||
if ((*p_)[st_ + i] == e) return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
//! \~english Returns the first index where the predicate `test` returns true, starting from `start`.
|
||||
//! \~russian Возвращает первый индекс, для которого предикат `test` возвращает true, начиная с `start`.
|
||||
//! \~\sa PIVector::indexWhere()
|
||||
inline ssize_t indexWhere(std::function<bool(const T & e)> test, ssize_t start = 0) const {
|
||||
if (start < 0) start = 0;
|
||||
for (size_t i = (size_t)start; i < sz_; ++i) {
|
||||
if (test((*p_)[st_ + i])) return (ssize_t)i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
//! \~english Returns the last index where the predicate `test` returns true, searching backwards from `start`.
|
||||
//! \~russian Возвращает последний индекс, для которого предикат `test` возвращает true,
|
||||
//! выполняя поиск в обратном направлении от `start`.
|
||||
//! \~\sa PIVector::lastIndexWhere()
|
||||
inline ssize_t lastIndexWhere(std::function<bool(const T & e)> test, ssize_t start = -1) const {
|
||||
ssize_t from = (start < 0 || (size_t)start >= sz_) ? (ssize_t)sz_ - 1 : start;
|
||||
for (ssize_t i = from; i >= 0; --i) {
|
||||
if (test((*p_)[st_ + i])) return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
//! \~english Applies a function to each element of the row (read-only).
|
||||
//! \~russian Применяет функцию к каждому элементу строки (только чтение).
|
||||
//! \details
|
||||
//! \~english The function can't modify the elements.
|
||||
//! \~russian Функция не может изменять элементы.
|
||||
//! \~\sa forEach (modifiable)
|
||||
inline void forEach(std::function<void(const T &)> func) const {
|
||||
for (size_t i = 0; i < sz_; ++i) {
|
||||
func((*p_)[st_ + i]);
|
||||
}
|
||||
}
|
||||
|
||||
//! \~english Checks if the row contains the element `e`.
|
||||
//! \~russian Проверяет, содержит ли строка элемент `e`.
|
||||
//! \~\sa PIVector::contains()
|
||||
inline bool contains(const T & e, ssize_t start = 0) const { return indexOf(e, start) != -1; }
|
||||
|
||||
//! \~english Counts occurrences of `e` in the row.
|
||||
//! \~russian Подсчитывает количество вхождений `e` в строке.
|
||||
//! \~\sa PIVector::entries()
|
||||
inline int entries(const T & e, ssize_t start = 0) const {
|
||||
if (start < 0) start = 0;
|
||||
int count = 0;
|
||||
for (size_t i = (size_t)start; i < sz_; ++i) {
|
||||
if ((*p_)[st_ + i] == e) ++count;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
//! \~english Counts elements in the row that pass the `test`.
|
||||
//! \~russian Подсчитывает элементы в строке, проходящие `test`.
|
||||
//! \~\sa PIVector::entries(std::function)
|
||||
inline int entries(std::function<bool(const T & e)> test, ssize_t start = 0) const {
|
||||
if (start < 0) start = 0;
|
||||
int count = 0;
|
||||
for (size_t i = (size_t)start; i < sz_; ++i) {
|
||||
if (test((*p_)[st_ + i])) ++count;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
//! \~english Tests if any element in the row passes the `test`.
|
||||
//! \~russian Проверяет, проходит ли какой-либо элемент в строке `test`.
|
||||
//! \~\sa PIVector::any()
|
||||
inline bool any(std::function<bool(const T & e)> test) const {
|
||||
for (size_t i = 0; i < sz_; ++i) {
|
||||
if (test((*p_)[st_ + i])) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
//! \~english Tests if all elements in the row pass the `test`.
|
||||
//! \~russian Проверяет, проходят ли все элементы в строке `test`.
|
||||
//! \~\sa PIVector::every()
|
||||
inline bool every(std::function<bool(const T & e)> test) const {
|
||||
for (size_t i = 0; i < sz_; ++i) {
|
||||
if (!test((*p_)[st_ + i])) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
//! \class ColConst
|
||||
//! \brief
|
||||
//! \~english Proxy class representing a single read-only column in a \a PIVector2D.
|
||||
//! \~russian Прокси-класс, представляющий один столбец в \a PIVector2D только для чтения.
|
||||
//! \details
|
||||
//! \~english Returned by const \a col(). Provides const access to column elements.
|
||||
//! \~russian Возвращается константной версией \a col(). Предоставляет константный доступ к элементам столбца.
|
||||
//! \~\sa Col, RowConst
|
||||
class ColConst {
|
||||
friend class PIVector2D<T>;
|
||||
|
||||
private:
|
||||
inline ColConst(const PIVector2D<T> * p, size_t row): p_(&(p->mat)) {
|
||||
step_ = p->cols_;
|
||||
row_ = row;
|
||||
sz_ = p->rows_;
|
||||
}
|
||||
protected:
|
||||
inline ColConst(const PIVector2D<T> * p, size_t col): p_(&(p->mat)), step_(p->cols_), col_(col), sz_(p->rows_) {}
|
||||
const PIVector<T> * p_;
|
||||
size_t step_, row_, sz_;
|
||||
const size_t step_, col_, sz_;
|
||||
|
||||
public:
|
||||
inline size_t size() const { return p_->rows_; }
|
||||
inline const T & operator[](size_t index) const { return (*p_)[index * step_ + row_]; }
|
||||
inline const T * data(size_t index = 0) const { return p_->data(index * step_ + row_); }
|
||||
//! \~english Copy constructor from modifiable Col to read-only ColConst.
|
||||
//! \~russian Конструктор копирования из модифицируемого класса Col в константный ColConst.
|
||||
//! \~\sa Col
|
||||
inline ColConst(const PIVector2D<T>::Col & c): p_(c.p_), step_(c.step_), col_(c.col_), sz_(c.sz_) {}
|
||||
|
||||
//! \~english Size of the column (number of rows).
|
||||
//! \~russian Размер столбца (количество строк).
|
||||
inline size_t size() const { return sz_; }
|
||||
|
||||
//! \~english Const access to the element at the given row index within the column.
|
||||
//! \~russian Константный доступ к элементу по заданному индексу строки в столбце.
|
||||
inline const T & operator[](size_t index) const { return (*p_)[index * step_ + col_]; }
|
||||
|
||||
//! \~english Returns a const pointer to the column data starting at an optional row offset.
|
||||
//! \~russian Возвращает константный указатель на данные столбца, начиная с опционального смещения по строкам.
|
||||
inline const T * data(size_t index = 0) const { return p_->data(index * step_ + col_); }
|
||||
|
||||
//! \~english Converts the column to a \a PIVector.
|
||||
//! \~russian Преобразует столбец в \a PIVector.
|
||||
inline PIVector<T> toVector() const {
|
||||
PIVector<T> ret;
|
||||
ret.reserve(sz_);
|
||||
for (int i = 0; i < size(); i++)
|
||||
ret << (*p_)[i * step_ + row_];
|
||||
for (size_t i = 0; i < size(); i++)
|
||||
ret << (*p_)[i * step_ + col_];
|
||||
return ret;
|
||||
}
|
||||
|
||||
//! \~english Returns the first index of element `e` in the row, starting from `start`.
|
||||
//! \~russian Возвращает первый индекс элемента `e` в строке, начиная с позиции `start`.
|
||||
//! \details
|
||||
//! \~english See \a PIVector::indexOf() for details on negative start handling.
|
||||
//! \~russian Подробнее об обработке отрицательного `start` см. \a PIVector::indexOf().
|
||||
//! \~\sa PIVector::indexOf()
|
||||
inline ssize_t indexOf(const T & e, ssize_t start = 0) const {
|
||||
if (start < 0) start = 0;
|
||||
for (size_t i = (size_t)start; i < sz_; ++i) {
|
||||
if ((*p_)[i * step_ + col_] == e) return (ssize_t)i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
//! \~english Returns the last index of element `e` in the row, searching backwards from `start`.
|
||||
//! \~russian Возвращает последний индекс элемента `e` в строке, выполняя поиск в обратном направлении от `start`.
|
||||
//! \~\sa PIVector::lastIndexOf()
|
||||
inline ssize_t lastIndexOf(const T & e, ssize_t start = -1) const {
|
||||
ssize_t from = (start < 0 || (size_t)start >= sz_) ? (ssize_t)sz_ - 1 : start;
|
||||
for (ssize_t i = from; i >= 0; --i) {
|
||||
if ((*p_)[i * step_ + col_] == e) return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
//! \~english Returns the first index where the predicate `test` returns true, starting from `start`.
|
||||
//! \~russian Возвращает первый индекс, для которого предикат `test` возвращает true, начиная с `start`.
|
||||
//! \~\sa PIVector::indexWhere()
|
||||
inline ssize_t indexWhere(std::function<bool(const T & e)> test, ssize_t start = 0) const {
|
||||
if (start < 0) start = 0;
|
||||
for (size_t i = (size_t)start; i < sz_; ++i) {
|
||||
if (test((*p_)[i * step_ + col_])) return (ssize_t)i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
//! \~english Returns the last index where the predicate `test` returns true, searching backwards from `start`.
|
||||
//! \~russian Возвращает последний индекс, для которого предикат `test` возвращает true,
|
||||
//! выполняя поиск в обратном направлении от `start`.
|
||||
//! \~\sa PIVector::lastIndexWhere()
|
||||
inline ssize_t lastIndexWhere(std::function<bool(const T & e)> test, ssize_t start = -1) const {
|
||||
ssize_t from = (start < 0 || (size_t)start >= sz_) ? (ssize_t)sz_ - 1 : start;
|
||||
for (ssize_t i = from; i >= 0; --i) {
|
||||
if (test((*p_)[i * step_ + col_])) return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
//! \~english Applies a function to each element of the column (read-only).
|
||||
//! \~russian Применяет функцию к каждому элементу столбца (только чтение).
|
||||
//! \details
|
||||
//! \~english The function can't modify the elements.
|
||||
//! \~russian Функция не может изменять элементы.
|
||||
//! \~\sa forEach (modifiable)
|
||||
inline void forEach(std::function<void(const T &)> func) const {
|
||||
for (size_t i = 0; i < sz_; ++i) {
|
||||
func((*p_)[i * step_ + col_]);
|
||||
}
|
||||
}
|
||||
|
||||
//! \~english Checks if the column contains the element `e`.
|
||||
//! \~russian Проверяет, содержит ли столбец элемент `e`.
|
||||
//! \~\sa PIVector::contains()
|
||||
inline bool contains(const T & e, ssize_t start = 0) const { return indexOf(e, start) != -1; }
|
||||
|
||||
//! \~english Counts occurrences of `e` in the column.
|
||||
//! \~russian Подсчитывает количество вхождений `e` в столбце.
|
||||
//! \~\sa PIVector::entries()
|
||||
inline int entries(const T & e, ssize_t start = 0) const {
|
||||
if (start < 0) start = 0;
|
||||
int count = 0;
|
||||
for (size_t i = (size_t)start; i < sz_; ++i) {
|
||||
if ((*p_)[i * step_ + col_] == e) ++count;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
//! \~english Counts elements in the column that pass the `test`.
|
||||
//! \~russian Подсчитывает элементы в столбце, проходящие `test`.
|
||||
//! \~\sa PIVector::entries(std::function)
|
||||
inline int entries(std::function<bool(const T & e)> test, ssize_t start = 0) const {
|
||||
if (start < 0) start = 0;
|
||||
int count = 0;
|
||||
for (size_t i = (size_t)start; i < sz_; ++i) {
|
||||
if (test((*p_)[i * step_ + col_])) ++count;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
//! \~english Tests if any element in the column passes the `test`.
|
||||
//! \~russian Проверяет, проходит ли какой-либо элемент в столбце `test`.
|
||||
//! \~\sa PIVector::any()
|
||||
inline bool any(std::function<bool(const T & e)> test) const {
|
||||
for (size_t i = 0; i < sz_; ++i) {
|
||||
if (test((*p_)[i * step_ + col_])) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
//! \~english Tests if all elements in the column pass the `test`.
|
||||
//! \~russian Проверяет, проходят ли все элементы в столбце `test`.
|
||||
//! \~\sa PIVector::every()
|
||||
inline bool every(std::function<bool(const T & e)> test) const {
|
||||
for (size_t i = 0; i < sz_; ++i) {
|
||||
if (!test((*p_)[i * step_ + col_])) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
inline T & element(size_t row, size_t col) { return mat[row * cols_ + col]; }
|
||||
inline const T & element(size_t row, size_t col) const { return mat[row * cols_ + col]; }
|
||||
inline const T & at(size_t row, size_t col) const { return mat[row * cols_ + col]; }
|
||||
inline Row operator[](size_t index) { return Row(this, index); }
|
||||
inline RowConst operator[](size_t index) const { return RowConst(this, index); }
|
||||
inline T * data(size_t index = 0) { return mat.data(index); }
|
||||
inline const T * data(size_t index = 0) const { return mat.data(index); }
|
||||
//! \class Row
|
||||
//! \brief
|
||||
//! \~english Proxy class representing a single row in a \a PIVector2D for modification.
|
||||
//! \~russian Прокси-класс, представляющий одну строку в \a PIVector2D для модификации.
|
||||
//! \details
|
||||
//! \~english Objects of this class are returned by non-const \a operator[] or \a row().
|
||||
//! They provide array-like access to the elements of a specific row and allow operations such as assignment from another row or a \a
|
||||
//! PIVector, searching, filling, and iteration.
|
||||
//! \~russian Объекты этого класса возвращаются неконстантными операторами \a operator[] или методом \a row().
|
||||
//! Они предоставляют доступ к элементам конкретной строки, подобный массиву, и позволяют выполнять такие операции, как присваивание из
|
||||
//! другой строки или \a PIVector, поиск, заполнение и итерацию. \sa Col, RowConst
|
||||
class Row: public RowConst {
|
||||
friend class PIVector2D<T>;
|
||||
|
||||
inline Row row(size_t index) { return Row(this, index); }
|
||||
inline RowConst row(size_t index) const { return RowConst(this, index); }
|
||||
inline Col col(size_t index) { return Col(this, index); }
|
||||
inline ColConst col(size_t index) const { return ColConst(this, index); }
|
||||
inline PIVector2D<T> & setRow(size_t row, const Row & other) {
|
||||
const size_t sz = piMin<size_t>(cols_, other.sz_);
|
||||
mat._copyRaw(mat.data(cols_ * row), other.data(), sz);
|
||||
private:
|
||||
inline Row(PIVector2D<T> * p, size_t row): RowConst(p, row), p_(&(p->mat)) {}
|
||||
PIVector<T> * p_;
|
||||
|
||||
public:
|
||||
using RowConst::operator[];
|
||||
using RowConst::data;
|
||||
using RowConst::size;
|
||||
|
||||
//! \~english Accesses the element at the given column index within the row.
|
||||
//! \~russian Доступ к элементу по заданному индексу столбца в строке.
|
||||
//! \details
|
||||
//! \~english No bounds checking is performed; use with caution.
|
||||
//! \~russian Проверка границ не выполняется; используйте с осторожностью.
|
||||
//! \~\sa PIVector::operator[]
|
||||
inline T & operator[](size_t index) { return (*p_)[this->st_ + index]; }
|
||||
|
||||
//! \~english Returns a pointer to the row data starting at an optional offset.
|
||||
//! \~russian Возвращает указатель на данные строки, начиная с опционального смещения.
|
||||
//! \details
|
||||
//! \~english The pointer can be used for direct memory operations. It remains valid as long as the underlying 2D array is not
|
||||
//! reallocated.
|
||||
//! \~russian Указатель можно использовать для прямых операций с памятью. Он остаётся действительным, пока не произойдёт
|
||||
//! перераспределение памяти внутреннего двумерного массива. \sa PIVector::data()
|
||||
inline T * data(size_t index = 0) { return p_->data(this->st_ + index); }
|
||||
|
||||
//! \~english Assigns the contents of another Row to this row.
|
||||
//! \~russian Присваивает этой строке содержимое другой строки.
|
||||
//! \details
|
||||
//! \~english Only the minimum of the two row sizes is copied; if this row is shorter, excess elements in `other` are ignored.
|
||||
//! \~russian Копируется только минимум из размеров двух строк; если эта строка короче, лишние элементы из `other` игнорируются.
|
||||
//! \~\sa PIVector::operator=
|
||||
inline Row & operator=(const Row & other) {
|
||||
if (p_ == other.p_ && this->st_ == other.st_) return *this;
|
||||
const size_t sz = piMin<size_t>(this->sz_, other.sz_);
|
||||
p_->_copyRaw(p_->data(this->st_), other.data(), sz);
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Assigns the contents of a \a PIVector to this row.
|
||||
//! \~russian Присваивает этой строке содержимое \a PIVector.
|
||||
//! \details
|
||||
//! \~english Only the minimum of the row size and vector size is copied.
|
||||
//! \~russian Копируется только минимум из размера строки и размера вектора.
|
||||
//! \~\sa PIVector::operator=
|
||||
inline Row & operator=(const PIVector<T> & other) {
|
||||
const size_t sz = piMin<size_t>(this->sz_, other.size());
|
||||
p_->_copyRaw(p_->data(this->st_), other.data(), sz);
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Applies a function to each element of the row (modifiable).
|
||||
//! \~russian Применяет функцию к каждому элементу строки (с возможностью изменения).
|
||||
//! \param func Function that takes a reference to T.
|
||||
//! \details
|
||||
//! \~english The function can modify the elements.
|
||||
//! \~russian Функция может изменять элементы.
|
||||
//! \~\sa PIVector::forEach()
|
||||
inline void forEach(std::function<void(T &)> func) {
|
||||
for (size_t i = 0; i < this->sz_; ++i) {
|
||||
func((*p_)[this->st_ + i]);
|
||||
}
|
||||
}
|
||||
|
||||
//! \~english Fills the row with copies of `value`.
|
||||
//! \~russian Заполняет строку копиями `value`.
|
||||
//! \~\sa PIVector::fill()
|
||||
inline void fill(const T & value) {
|
||||
for (size_t i = 0; i < this->sz_; ++i) {
|
||||
(*p_)[this->st_ + i] = value;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
//! \class Col
|
||||
//! \brief
|
||||
//! \~english Proxy class representing a single column in a \a PIVector2D for modification.
|
||||
//! \~russian Прокси-класс, представляющий один столбец в \a PIVector2D для модификации.
|
||||
//! \details
|
||||
//! \~english Objects of this class are returned by non-const \a col(). They provide column-wise access and operations similar to \a
|
||||
//! Row.
|
||||
//! \~russian Объекты этого класса возвращаются неконстантным методом \a col(). Они предоставляют доступ к столбцам и операции,
|
||||
//! аналогичные \a Row. \sa Row, ColConst
|
||||
class Col: public ColConst {
|
||||
friend class PIVector2D<T>;
|
||||
|
||||
private:
|
||||
inline Col(PIVector2D<T> * p, size_t col): ColConst(p, col), p_(&(p->mat)) {}
|
||||
PIVector<T> * p_;
|
||||
|
||||
public:
|
||||
using ColConst::operator[];
|
||||
using ColConst::data;
|
||||
using ColConst::size;
|
||||
|
||||
//! \~english Accesses the element at the given row index within the column.
|
||||
//! \~russian Доступ к элементу по заданному индексу строки в столбце.
|
||||
//! \return Reference to the element.
|
||||
inline T & operator[](size_t index) { return (*p_)[index * this->step_ + this->col_]; }
|
||||
|
||||
//! \~english Returns a pointer to the column data starting at an optional row offset.
|
||||
//! \~russian Возвращает указатель на данные столбца, начиная с опционального смещения по строкам.
|
||||
//! \details
|
||||
//! \~english Note that column elements are not stored contiguously in memory, so this pointer cannot be used to iterate over the
|
||||
//! whole column.
|
||||
//! \~russian Обратите внимание, что элементы столбца не хранятся в памяти непрерывно, поэтому этот указатель нельзя использовать
|
||||
//! для итерации по всему столбцу.
|
||||
inline T * data(size_t index = 0) { return p_->data(index * this->step_ + this->col_); }
|
||||
|
||||
//! \~english Assigns the contents of another Col to this column.
|
||||
//! \~russian Присваивает этому столбцу содержимое другого столбца.
|
||||
inline Col & operator=(const Col & other) {
|
||||
if (p_ == other.p_ && this->col_ == other.col_) return *this;
|
||||
const size_t sz = piMin<size_t>(this->sz_, other.sz_);
|
||||
for (size_t i = 0; i < sz; ++i)
|
||||
(*p_)[i * this->step_ + this->col_] = other[i];
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Assigns the contents of a \a PIVector to this column.
|
||||
//! \~russian Присваивает этому столбцу содержимое \a PIVector.
|
||||
inline Col & operator=(const PIVector<T> & other) {
|
||||
const size_t sz = piMin<size_t>(this->sz_, other.size());
|
||||
for (size_t i = 0; i < sz; ++i)
|
||||
(*p_)[i * this->step_ + this->col_] = other[i];
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Applies a function to each element of the column (modifiable).
|
||||
//! \~russian Применяет функцию к каждому элементу столбца (с возможностью изменения).
|
||||
//! \details
|
||||
//! \~english The function can modify the elements.
|
||||
//! \~russian Функция может изменять элементы.
|
||||
//! \~\sa PIVector::forEach()
|
||||
inline void forEach(std::function<void(T &)> func) {
|
||||
for (size_t i = 0; i < this->sz_; ++i) {
|
||||
func((*p_)[i * this->step_ + this->col_]);
|
||||
}
|
||||
}
|
||||
|
||||
//! \~english Fills the column with copies of `value`.
|
||||
//! \~russian Заполняет столбец копиями `value`.
|
||||
//! \~\sa PIVector::fill()
|
||||
inline void fill(const T & value) {
|
||||
for (size_t i = 0; i < this->sz_; ++i) {
|
||||
(*p_)[i * this->step_ + this->col_] = value;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
//! \~english Returns a reference to the element at the given row and column.
|
||||
//! \~russian Возвращает ссылку на элемент по заданной строке и столбцу.
|
||||
//! \details
|
||||
//! \~english No bounds checking is performed.
|
||||
//! \~russian Проверка границ не выполняется.
|
||||
//! \~\sa at() (const version), PIVector::operator[]
|
||||
inline T & element(size_t row, size_t col) { return mat[row * cols_ + col]; }
|
||||
|
||||
//! \~english Returns a const reference to the element at the given row and column.
|
||||
//! \~russian Возвращает константную ссылку на элемент по заданной строке и столбцу.
|
||||
inline const T & element(size_t row, size_t col) const { return mat[row * cols_ + col]; }
|
||||
|
||||
//! \~english Returns a const reference to the element at the given row and column
|
||||
//! \~russian Возвращает константную ссылку на элемент по заданной строке и столбцу
|
||||
//! \details
|
||||
//! \~english No bounds checking is performed.
|
||||
//! \~russian Проверка границ не выполняется.
|
||||
inline const T & at(size_t row, size_t col) const { return mat[row * cols_ + col]; }
|
||||
|
||||
//! \~english Returns a reference to the element at the given Index.
|
||||
//! \~russian Возвращает ссылку на элемент по заданному Index.
|
||||
inline T & operator[](const Index & idx) { return element(idx.row, idx.col); }
|
||||
|
||||
//! \~english Returns a const reference to the element at the given Index.
|
||||
//! \~russian Возвращает константную ссылку на элемент по заданному Index.
|
||||
inline const T & operator[](const Index & idx) const { return element(idx.row, idx.col); }
|
||||
|
||||
//! \~english Returns a reference to the element at the given Index.
|
||||
//! \~russian Возвращает ссылку на элемент по заданному Index.
|
||||
inline T & element(const Index & idx) { return element(idx.row, idx.col); }
|
||||
|
||||
//! \~english Returns a const reference to the element at the given Index.
|
||||
//! \~russian Возвращает константную ссылку на элемент по заданному Index.
|
||||
inline const T & element(const Index & idx) const { return element(idx.row, idx.col); }
|
||||
|
||||
//! \~english Returns a const reference to the element at the given Index (bounds-checked only in debug).
|
||||
//! \~russian Возвращает константную ссылку на элемент по заданному Index (проверка границ только в отладочном режиме).
|
||||
inline const T & at(const Index & idx) const { return at(idx.row, idx.col); }
|
||||
|
||||
//! \~english Returns a proxy object for the row at the given index for modification.
|
||||
//! \~russian Возвращает прокси-объект для строки по заданному индексу для модификации.
|
||||
//! \~\sa row(), Col
|
||||
inline Row operator[](size_t index) { return Row(this, index); }
|
||||
|
||||
//! \~english Returns a proxy object for the row at the given index for read-only access.
|
||||
//! \~russian Возвращает прокси-объект для строки по заданному индексу только для чтения.
|
||||
inline RowConst operator[](size_t index) const { return RowConst(this, index); }
|
||||
|
||||
//! \~english Returns a pointer to the underlying flat data starting at an optional offset.
|
||||
//! \~russian Возвращает указатель на внутренние плоские данные, начиная с опционального смещения.
|
||||
//! \~\sa PIVector::data()
|
||||
inline T * data(size_t index = 0) { return mat.data(index); }
|
||||
|
||||
//! \~english Returns a const pointer to the underlying flat data starting at an optional offset.
|
||||
//! \~russian Возвращает константный указатель на внутренние плоские данные, начиная с опционального смещения.
|
||||
inline const T * data(size_t index = 0) const { return mat.data(index); }
|
||||
|
||||
|
||||
//! \~english Returns a proxy object for the row at the given index for modification.
|
||||
//! \~russian Возвращает прокси-объект для строки по заданному индексу для модификации.
|
||||
//! \~\sa operator[]
|
||||
inline Row row(size_t index) { return Row(this, index); }
|
||||
|
||||
//! \~english Returns a proxy object for the row at the given index for read-only access.
|
||||
//! \~russian Возвращает прокси-объект для строки по заданному индексу только для чтения.
|
||||
inline RowConst row(size_t index) const { return RowConst(this, index); }
|
||||
|
||||
//! \~english Returns a proxy object for the column at the given index for modification.
|
||||
//! \~russian Возвращает прокси-объект для столбца по заданному индексу для модификации.
|
||||
//! \~\sa col() const
|
||||
inline Col col(size_t index) { return Col(this, index); }
|
||||
|
||||
//! \~english Returns a proxy object for the column at the given index for read-only access.
|
||||
//! \~russian Возвращает прокси-объект для столбца по заданному индексу только для чтения.
|
||||
inline ColConst col(size_t index) const { return ColConst(this, index); }
|
||||
|
||||
//! \~english Replaces a row with the contents of a read-only RowConst object.
|
||||
//! \~russian Заменяет строку содержимым объекта RowConst только для чтения.
|
||||
inline PIVector2D<T> & setRow(size_t row, const RowConst & other) {
|
||||
const size_t sz = piMin<size_t>(cols_, other.sz_);
|
||||
mat._copyRaw(mat.data(cols_ * row), other.data(), sz);
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Replaces a row with the contents of a \a PIVector.
|
||||
//! \~russian Заменяет строку содержимым \a PIVector.
|
||||
inline PIVector2D<T> & setRow(size_t row, const PIVector<T> & other) {
|
||||
const size_t sz = piMin<size_t>(cols_, other.size());
|
||||
mat._copyRaw(mat.data(cols_ * row), other.data(), sz);
|
||||
return *this;
|
||||
}
|
||||
inline PIVector2D<T> & addRow(const Row & other) {
|
||||
if (cols_ == 0) cols_ = other.sz_;
|
||||
const size_t sz = piMin<size_t>(cols_, other.sz_);
|
||||
const size_t ps = mat.size();
|
||||
mat.resize(mat.size() + cols_);
|
||||
mat._copyRaw(mat.data(ps), other.data(), sz);
|
||||
rows_++;
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Appends a new row to the bottom of the array from another Row object.
|
||||
//! \~russian Добавляет новую строку в конец массива из другого объекта Row.
|
||||
//! \details
|
||||
//! \~english If the array was empty, its column count is set to the size of the source row.
|
||||
//! Otherwise, only `min(cols(), other.size())` elements are copied; the rest of the new row is default-initialized.
|
||||
//! \~russian Если массив был пуст, количество столбцов устанавливается равным размеру исходной строки.
|
||||
//! В противном случае копируется только `min(cols(), other.size())` элементов; остальные элементы новой строки инициализируются по
|
||||
//! умолчанию.
|
||||
//! \~\sa PIVector::push_back()
|
||||
inline PIVector2D<T> & addRow(const RowConst & other) {
|
||||
if (cols_ == 0) cols_ = other.sz_;
|
||||
const size_t sz = piMin<size_t>(cols_, other.sz_);
|
||||
const size_t ps = mat.size();
|
||||
mat.resize(mat.size() + cols_);
|
||||
mat._copyRaw(mat.data(ps), other.data(), sz);
|
||||
rows_++;
|
||||
return *this;
|
||||
}
|
||||
inline PIVector2D<T> & addRow(const PIVector<T> & other) {
|
||||
if (cols_ == 0) cols_ = other.size();
|
||||
const size_t sz = piMin<size_t>(cols_, other.size());
|
||||
const size_t ps = mat.size();
|
||||
mat.resize(mat.size() + cols_);
|
||||
mat._copyRaw(mat.data(ps), other.data(), sz);
|
||||
mat.append(other.toVector());
|
||||
rows_++;
|
||||
mat.resize(rows_ * cols_);
|
||||
return *this;
|
||||
}
|
||||
|
||||
inline PIVector2D<T> & resize(size_t rows, size_t cols, const T & f = T()) {
|
||||
mat.resize(rows * cols_, f);
|
||||
rows_ = rows;
|
||||
const int cs = (cols - cols_);
|
||||
if (cs < 0) {
|
||||
for (size_t r = 0; r < rows; ++r) {
|
||||
mat.remove(r * cols + cols, -cs);
|
||||
//! \~english Appends a new row to the bottom of the array from a \a PIVector.
|
||||
//! \~russian Добавляет новую строку в конец массива из \a PIVector.
|
||||
inline PIVector2D<T> & addRow(const PIVector<T> & other) {
|
||||
if (cols_ == 0) cols_ = other.size();
|
||||
mat.append(other);
|
||||
rows_++;
|
||||
mat.resize(rows_ * cols_);
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Appends \a count new empty rows to the bottom of the array, filled with value \a f.
|
||||
//! \~russian Добавляет \a count новых пустых строк в конец массива, заполненных значением \a f.
|
||||
//! \details
|
||||
//! \~english If the array was empty (no columns defined), the column count is set to 1.
|
||||
//! The new rows are filled with the default value \a f.
|
||||
//! \~russian Если массив был пуст (количество столбцов не определено), количество столбцов устанавливается равным 1.
|
||||
//! Новые строки заполняются значением по умолчанию \a f.
|
||||
//! \~\sa addRow(), appendColumns()
|
||||
inline PIVector2D<T> & appendRows(size_t count, const T & f = T()) {
|
||||
if (count == 0) return *this;
|
||||
if (cols_ == 0) ++cols_;
|
||||
mat.resize(mat.size() + count * cols_, f);
|
||||
rows_ += count;
|
||||
return *this;
|
||||
}
|
||||
mat.resize(rows * cols, f);
|
||||
if (!mat.isEmpty()) {
|
||||
if (cs > 0) {
|
||||
|
||||
//! \~english Appends \a count new empty columns to the end of each row of the array.
|
||||
//! \~russian Добавляет \a count новых пустых столбцов в конец каждой строки массива.
|
||||
//! \details
|
||||
//! \~english If the array was empty (rows not defined), the array becomes a single row with \a count columns.
|
||||
//! If the array already has rows, new elements are inserted at the end of each existing row.
|
||||
//! \~russian Если массив был пуст (строки не определены), массив становится одной строкой с \a count столбцов.
|
||||
//! Если массив уже содержит строки, новые элементы добавляются в конец каждой существующей строки.
|
||||
//! \~\sa appendRows(), addColumn()
|
||||
inline PIVector2D<T> & appendColumns(size_t count, const T & f = T()) {
|
||||
if (count == 0) return *this;
|
||||
if (rows_ == 0) {
|
||||
mat.resize(count, f);
|
||||
rows_ = 1;
|
||||
cols_ = count;
|
||||
return *this;
|
||||
}
|
||||
|
||||
const size_t newCols = cols_ + count;
|
||||
mat.reserve(rows_ * newCols);
|
||||
for (size_t r = rows_; r > 0; --r) {
|
||||
mat.insert(r * cols_, f, count);
|
||||
}
|
||||
|
||||
cols_ = newCols;
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Deletes `count` rows starting from the specified row index.
|
||||
//! \~russian Удаляет `count` строк, начиная с указанного индекса строки.
|
||||
//! \details
|
||||
//! \~english Removes the specified rows from the array and updates the row count. If all elements are deleted (array becomes empty),
|
||||
//! both rows and columns are set to 0.
|
||||
//! \~russian Удаляет указанные строки из массива и обновляет количество строк. Если все элементы удалены (массив становится пустым),
|
||||
//! количество строк и столбцов устанавливается в 0.
|
||||
//! \~\sa deleteColumns()
|
||||
inline PIVector2D<T> & deleteRows(size_t row_start, size_t count) {
|
||||
if (row_start >= rows_ || count == 0) return *this;
|
||||
mat.remove(row_start * cols_, cols_ * count);
|
||||
if (isEmpty()) {
|
||||
cols_ = 0;
|
||||
rows_ = 0;
|
||||
} else {
|
||||
rows_ -= count;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Removes the specified columns from the array and updates the column count.
|
||||
//! \~russian Удаляет указанные столбцы из массива и обновляет количество столбцов.
|
||||
//! \details
|
||||
//! \~english Removes \a count columns starting from \a col_start. If \a col_start is out of range or \a count is 0,
|
||||
//! the function does nothing. If \a count extends beyond the last column, only available columns are deleted.
|
||||
//! \~russian Удаляет \a count столбцов начиная с \a col_start. Если \a col_start выходит за границы или \a count равен 0,
|
||||
//! функция ничего не делает. Если \a count выходит за последний столбец, удаляются только доступные столбцы.
|
||||
//! \~\sa removeColumn(), deleteRows()
|
||||
inline PIVector2D<T> & deleteColumns(size_t col_start, size_t count) {
|
||||
if (col_start >= cols_ || rows_ == 0) return *this;
|
||||
count = piMin(count, cols_ - col_start);
|
||||
if (count == 0) return *this;
|
||||
for (size_t r = 0; r < rows_; ++r) {
|
||||
for (int i = 0; i < cs; ++i)
|
||||
mat.insert(r * cols + cols_, mat.take_back());
|
||||
mat.remove(r * (cols_ - count) + col_start, count);
|
||||
}
|
||||
cols_ -= count;
|
||||
mat.resize(rows_ * cols_);
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Appends a new column to the right of the array from a \a ColConst.
|
||||
//! \~russian Добавляет новую строку в конец массива из \a ColConst.
|
||||
inline PIVector2D<T> & addColumn(const ColConst & other) {
|
||||
if (other.size() == 0) return *this;
|
||||
if (isEmpty()) {
|
||||
mat.reserve(other.size());
|
||||
for (size_t r = 0; r < other.size(); ++r) {
|
||||
mat.append(other[r]);
|
||||
}
|
||||
rows_ = mat.size();
|
||||
cols_ = 1;
|
||||
return *this;
|
||||
}
|
||||
|
||||
const size_t newCols = cols_ + 1;
|
||||
mat.reserve(rows_ * newCols);
|
||||
for (size_t r = rows_; r > 0; --r) {
|
||||
if (r - 1 < other.size()) {
|
||||
mat.insert(r * cols_, other[r - 1]);
|
||||
} else {
|
||||
mat.insert(r * cols_);
|
||||
}
|
||||
}
|
||||
|
||||
cols_ = newCols;
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Appends a new column to the right of the array from a \a PIVector.
|
||||
//! \~russian Добавляет новую строку в конец массива из \a PIVector.
|
||||
inline PIVector2D<T> & addColumn(const PIVector<T> & other) {
|
||||
if (other.size() == 0) return *this;
|
||||
if (isEmpty()) {
|
||||
mat.append(other);
|
||||
rows_ = mat.size();
|
||||
cols_ = 1;
|
||||
return *this;
|
||||
}
|
||||
|
||||
const size_t newCols = cols_ + 1;
|
||||
mat.reserve(rows_ * newCols);
|
||||
for (size_t r = rows_; r > 0; --r) {
|
||||
if (r - 1 < other.size()) {
|
||||
mat.insert(r * cols_, other[r - 1]);
|
||||
} else {
|
||||
mat.insert(r * cols_);
|
||||
}
|
||||
}
|
||||
|
||||
cols_ = newCols;
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Resizes the 2D array to new dimensions.
|
||||
//! \~russian Изменяет размер двумерного массива.
|
||||
//! \details
|
||||
//! \~english If the new dimensions are larger, new elements are appended and filled with copies of `f`.
|
||||
//! If they are smaller, the array is truncated (excess elements are destroyed). The underlying memory may be reallocated.
|
||||
//! \~russian Если новые размеры больше текущих, новые элементы добавляются в конец и заполняются копиями `f`.
|
||||
//! Если новые размеры меньше, массив усекается (лишние элементы уничтожаются). Внутренняя память может быть перераспределена.
|
||||
//! \code
|
||||
//! PIVector2D<int> mat(2, 3, 0); // 2x3 matrix filled with 0
|
||||
//! mat.resize(3, 4, 1); // becomes 3x4, new elements filled with 1
|
||||
//! \endcode
|
||||
//! \~\sa PIVector::resize()
|
||||
inline PIVector2D<T> & resize(size_t rows, size_t cols, const T & f = T()) {
|
||||
if (rows == rows_ && cols == cols_) return *this;
|
||||
if (rows_ == 0 || cols_ == 0) {
|
||||
mat.resize(rows * cols, f);
|
||||
rows_ = rows;
|
||||
cols_ = cols;
|
||||
return *this;
|
||||
}
|
||||
if (rows != rows_ && cols == cols_) {
|
||||
mat.resize(rows * cols_, f);
|
||||
rows_ = rows;
|
||||
return *this;
|
||||
}
|
||||
if (cols > cols_) {
|
||||
appendColumns(cols - cols_, f);
|
||||
}
|
||||
if (rows > rows_) {
|
||||
appendRows(rows - rows_, f);
|
||||
}
|
||||
if (cols < cols_) {
|
||||
deleteColumns(cols, cols_ - cols);
|
||||
}
|
||||
if (rows < rows_) {
|
||||
deleteRows(rows, rows_ - rows);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Equality operator.
|
||||
//! \~russian Оператор равенства.
|
||||
//! \~\sa PIVector::operator==
|
||||
inline bool operator==(const PIVector2D<T> & t) const {
|
||||
if (cols_ != t.cols_ || rows_ != t.rows_) return false;
|
||||
return mat == t.mat;
|
||||
}
|
||||
|
||||
//! \~english Inequality operator.
|
||||
//! \~russian Оператор неравенства.
|
||||
inline bool operator!=(const PIVector2D<T> & t) const { return !(*this == t); }
|
||||
|
||||
//! \~english Converts the 2D array to a vector of vectors (PIVector<PIVector<T>>).
|
||||
//! \~russian Преобразует двумерный массив в вектор векторов (PIVector<PIVector<T>>).
|
||||
//! \details
|
||||
//! \~english Each row vector is a copy of the corresponding row.
|
||||
//! \~russian Каждый вектор-строка является копией соответствующей строки.
|
||||
//! \~\sa fromVectors(), PIVector::PIVector(const T*, size_t)
|
||||
inline PIVector<PIVector<T>> toVectors() const {
|
||||
PIVector<PIVector<T>> ret;
|
||||
ret.reserve(rows_);
|
||||
@@ -284,18 +1012,31 @@ public:
|
||||
return ret;
|
||||
}
|
||||
|
||||
//! \~english Returns a const reference to the underlying flat \a PIVector.
|
||||
//! \~russian Возвращает константную ссылку на внутренний плоский \a PIVector.
|
||||
inline const PIVector<T> & asPlainVector() const { return mat; }
|
||||
|
||||
//! \~english Returns a reference to the underlying flat \a PIVector.
|
||||
//! \~russian Возвращает ссылку на внутренний плоский \a PIVector.
|
||||
inline PIVector<T> & asPlainVector() { return mat; }
|
||||
|
||||
//! \~english Returns a copy of the underlying flat \a PIVector.
|
||||
//! \~russian Возвращает копию внутреннего плоского \a PIVector.
|
||||
inline PIVector<T> toPlainVector() const { return mat; }
|
||||
|
||||
inline PIVector<T> & plainVector() { return mat; }
|
||||
|
||||
inline const PIVector<T> & plainVector() const { return mat; }
|
||||
|
||||
//! \~english Swaps this 2D array with another.
|
||||
//! \~russian Меняет местами этот двумерный массив с другим.
|
||||
//! \details
|
||||
//! \~english Swaps the flat vectors and the dimension members. Very fast, no memory allocation.
|
||||
//! \~russian Обменивает внутренние плоские векторы и члены, хранящие размеры. Очень быстро, без выделения памяти.
|
||||
//! \~\sa PIVector::swap()
|
||||
inline void swap(PIVector2D<T> & other) {
|
||||
mat.swap(other.mat);
|
||||
piSwap<size_t>(rows_, other.rows_);
|
||||
piSwap<size_t>(cols_, other.cols_);
|
||||
}
|
||||
|
||||
//! \internal
|
||||
template<typename T1 = T, typename std::enable_if<std::is_trivially_copyable<T1>::value, int>::type = 0>
|
||||
inline PIVector2D<T> & _resizeRaw(size_t r, size_t c) {
|
||||
rows_ = r;
|
||||
@@ -304,29 +1045,352 @@ public:
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Clears the array, removing all elements and setting dimensions to 0.
|
||||
//! \~russian Очищает массив, удаляя все элементы и устанавливая размеры в 0.
|
||||
//! \details
|
||||
//! \~english The capacity of the underlying flat vector may remain unchanged.
|
||||
//! \~russian Ёмкость внутреннего плоского вектора может остаться неизменной.
|
||||
//! \~\sa PIVector::clear()
|
||||
inline void clear() {
|
||||
rows_ = cols_ = 0;
|
||||
mat.clear();
|
||||
}
|
||||
|
||||
template<typename ST>
|
||||
inline PIVector2D<ST> map(std::function<ST(const T & e)> f) const {
|
||||
return PIVector2D<ST>(rows_, cols_, mat.map(f));
|
||||
|
||||
//! \~english Checks if the underlying flat vector contains the element `e`.
|
||||
//! \~russian Проверяет, содержит ли внутренний плоский вектор элемент `e`.
|
||||
//! \~\sa PIVector::contains()
|
||||
inline bool contains(const T & e) const { return mat.contains(e); }
|
||||
|
||||
//! \~english Counts occurrences of `e` in the underlying flat vector.
|
||||
//! \~russian Подсчитывает количество вхождений `e` во внутреннем плоском векторе.
|
||||
//! \~\sa PIVector::entries()
|
||||
inline int entries(const T & e) const { return mat.entries(e); }
|
||||
|
||||
//! \~english Counts elements in the flat vector that pass the `test`.
|
||||
//! \~russian Подсчитывает элементы в плоском векторе, проходящие `test`.
|
||||
//! \~\sa PIVector::entries(std::function)
|
||||
inline int entries(std::function<bool(const T & e)> test) const { return mat.entries(std::move(test)); }
|
||||
|
||||
|
||||
//! \~english Returns the first index (row, col) of `e` in the 2D array.
|
||||
//! \~russian Возвращает первый индекс (строка, столбец) элемента `e` в двумерном массиве.
|
||||
//! \~\sa PIVector::indexOf()
|
||||
inline Index indexOf(const T & e) const {
|
||||
ssize_t flat = mat.indexOf(e);
|
||||
if (flat < 0 || cols_ == 0) return Index{-1, -1};
|
||||
return Index{flat / static_cast<ssize_t>(cols_), flat % static_cast<ssize_t>(cols_)};
|
||||
}
|
||||
|
||||
inline void forEach(std::function<void(const T &)> f) const { mat.forEach(f); }
|
||||
//! \~english Returns the first index (row, col) in the 2D array that passes the `test`.
|
||||
//! \~russian Возвращает первый индекс (строка, столбец) в двумерном массиве, проходящий `test`.
|
||||
//! \~\sa PIVector::indexWhere()
|
||||
inline Index indexWhere(std::function<bool(const T & e)> test, ssize_t start = 0) const {
|
||||
ssize_t flat = mat.indexWhere(std::move(test), start);
|
||||
if (flat < 0 || cols_ == 0) return Index{-1, -1};
|
||||
return Index{flat / static_cast<ssize_t>(cols_), flat % static_cast<ssize_t>(cols_)};
|
||||
}
|
||||
|
||||
inline PIVector2D<T> & forEach(std::function<void(T &)> f) {
|
||||
mat.forEach(f);
|
||||
//! \~english Returns the last index (row, col) of `e` in the 2D array.
|
||||
//! \~russian Возвращает последний индекс (строка, столбец) элемента `e` в двумерном массиве.
|
||||
//! \~\sa PIVector::lastIndexOf()
|
||||
inline Index lastIndexOf(const T & e, ssize_t start = -1) const {
|
||||
ssize_t flat = mat.lastIndexOf(e, start);
|
||||
if (flat < 0 || cols_ == 0) return Index{-1, -1};
|
||||
return Index{flat / static_cast<ssize_t>(cols_), flat % static_cast<ssize_t>(cols_)};
|
||||
}
|
||||
|
||||
//! \~english Returns the last index (row, col) in the 2D array that passes the `test`.
|
||||
//! \~russian Возвращает последний индекс (строка, столбец) в двумерном массиве, проходящий `test`.
|
||||
//! \~\sa PIVector::lastIndexWhere()
|
||||
inline Index lastIndexWhere(std::function<bool(const T & e)> test, ssize_t start = -1) const {
|
||||
ssize_t flat = mat.lastIndexWhere(std::move(test), start);
|
||||
if (flat < 0 || cols_ == 0) return Index{-1, -1};
|
||||
return Index{flat / static_cast<ssize_t>(cols_), flat % static_cast<ssize_t>(cols_)};
|
||||
}
|
||||
|
||||
|
||||
//! \~english Tests if any element in the flat vector passes the `test`.
|
||||
//! \~russian Проверяет, проходит ли какой-либо элемент в плоском векторе `test`.
|
||||
//! \~\sa PIVector::any()
|
||||
inline bool any(std::function<bool(const T & e)> test) const { return mat.any(std::move(test)); }
|
||||
|
||||
//! \~english Tests if all elements in the flat vector pass the `test`.
|
||||
//! \~russian Проверяет, проходят ли все элементы в плоском векторе `test`.
|
||||
//! \~\sa PIVector::every()
|
||||
inline bool every(std::function<bool(const T & e)> test) const { return mat.every(std::move(test)); }
|
||||
|
||||
//! \~english Fills the entire 2D array with copies of `e`.
|
||||
//! \~russian Заполняет весь двумерный массив копиями `e`.
|
||||
//! \~\sa PIVector::fill()
|
||||
inline PIVector2D<T> & fill(const T & e = T()) {
|
||||
mat.fill(e);
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Fills the entire 2D array using a generator function `f` based on flat index.
|
||||
//! \~russian Заполняет весь двумерный массив, используя функцию-генератор `f` на основе плоского индекса.
|
||||
//! \~\sa PIVector::fill(std::function)
|
||||
inline PIVector2D<T> & fill(std::function<T(size_t i)> f) {
|
||||
mat.fill(std::move(f));
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Same as \a fill().
|
||||
//! \~russian То же, что и \a fill().
|
||||
inline PIVector2D<T> & assign(const T & e = T()) { return fill(e); }
|
||||
|
||||
//! \~english Assigns new size and fills with value.
|
||||
//! \~russian Задаёт новый размер и заполняет значением.
|
||||
//! \~\sa PIVector::assign(size_t, const T&)
|
||||
inline PIVector2D<T> & assign(size_t rows, size_t cols, const T & f = T()) {
|
||||
mat.assign(rows * cols, f);
|
||||
rows_ = rows;
|
||||
cols_ = cols;
|
||||
return *this;
|
||||
}
|
||||
|
||||
|
||||
//! \~english Returns a transposed 2D array (rows become columns and vice versa).
|
||||
//! \~russian Возвращает транспонированный двумерный массив (строки становятся столбцами и наоборот).
|
||||
//! \details
|
||||
//! \~english The element at (r, c) in the original becomes at (c, r) in the result.
|
||||
//! \~russian Элемент (r, c) исходного массива становится элементом (c, r) в результате.
|
||||
//! \code
|
||||
//! PIVector2D<int> mat(2, 3, ...);
|
||||
//! auto t = mat.transposed(); // now 3x2
|
||||
//! \endcode
|
||||
inline PIVector2D<T> transposed() const {
|
||||
if (isEmpty()) return PIVector2D<T>();
|
||||
PIVector2D<T> result(cols_, rows_);
|
||||
for (size_t r = 0; r < rows_; ++r) {
|
||||
for (size_t c = 0; c < cols_; ++c) {
|
||||
result.element(c, r) = element(r, c);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
//! \~english Reverses the order of rows in place.
|
||||
//! \~russian Изменяет порядок строк на обратный на месте.
|
||||
//! \~\sa reverseColumns(), PIVector::reverse()
|
||||
inline PIVector2D<T> & reverseRows() {
|
||||
const size_t half = rows_ / 2;
|
||||
for (size_t i = 0; i < half; ++i) {
|
||||
T * row1 = data(i * cols_);
|
||||
T * row2 = data((rows_ - 1 - i) * cols_);
|
||||
for (size_t j = 0; j < cols_; ++j) {
|
||||
piSwap(row1[j], row2[j]);
|
||||
}
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Reverses the order of columns in each row in place.
|
||||
//! \~russian Изменяет порядок столбцов в каждой строке на обратный на месте.
|
||||
//! \~\sa reverseRows(), PIVector::reverse()
|
||||
inline PIVector2D<T> & reverseColumns() {
|
||||
for (size_t r = 0; r < rows_; ++r) {
|
||||
Row currentRow = row(r);
|
||||
const size_t half = cols_ / 2;
|
||||
for (size_t c = 0; c < half; ++c) {
|
||||
piSwap<T>(currentRow[c], currentRow[cols_ - 1 - c]);
|
||||
}
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Returns a sub-2D array (a range of rows and columns).
|
||||
//! \~russian Возвращает подмассив (диапазон строк и столбцов).
|
||||
//! \details
|
||||
//! \~english If the range exceeds the array boundaries, it is clipped. If rowCount or colCount is 0, an empty array is returned.
|
||||
//! \~russian Если диапазон выходит за границы массива, он обрезается. Если rowCount или colCount равны 0, возвращается пустой массив.
|
||||
//! \~\sa PIVector::getRange()
|
||||
inline PIVector2D<T> getRange(size_t rowStart, size_t rowCount, size_t colStart, size_t colCount) const {
|
||||
if (rowStart >= rows_ || colStart >= cols_ || rowCount == 0 || colCount == 0) return PIVector2D<T>();
|
||||
const size_t actualRowCount = piMin<size_t>(rowCount, rows_ - rowStart);
|
||||
const size_t actualColCount = piMin<size_t>(colCount, cols_ - colStart);
|
||||
|
||||
PIVector2D<T> result(actualRowCount, actualColCount);
|
||||
for (size_t r = 0; r < actualRowCount; ++r) {
|
||||
for (size_t c = 0; c < actualColCount; ++c) {
|
||||
result.element(r, c) = element(rowStart + r, colStart + c);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
//! \~english Applies a function to each element and returns a new 2D array of a different type.
|
||||
//! \~russian Применяет функцию к каждому элементу и возвращает новый двумерный массив другого типа.
|
||||
//! \details
|
||||
//! \~english The original array is not modified.
|
||||
//! \~russian Исходный массив не изменяется.
|
||||
//! \~\sa PIVector::map()
|
||||
template<typename ST>
|
||||
inline PIVector2D<ST> map(std::function<ST(const T & e)> f) const {
|
||||
return PIVector2D<ST>(rows_, cols_, mat.template map<ST>(std::move(f)));
|
||||
}
|
||||
|
||||
//! \~english Applies a function (with row and col indices) to each element and returns a new 2D array.
|
||||
//! \~russian Применяет функцию (с индексами строки и столбца) к каждому элементу и возвращает новый двумерный массив.
|
||||
//! \~\sa PIVector::mapIndexed()
|
||||
template<typename ST>
|
||||
inline PIVector2D<ST> mapIndexed(std::function<ST(size_t row, size_t col, const T & e)> f) const {
|
||||
PIVector<ST> mappedMat;
|
||||
mappedMat.reserve(size());
|
||||
for (size_t r = 0; r < rows_; ++r) {
|
||||
for (size_t c = 0; c < cols_; ++c) {
|
||||
mappedMat << f(r, c, element(r, c));
|
||||
}
|
||||
}
|
||||
return PIVector2D<ST>(rows_, cols_, std::move(mappedMat));
|
||||
}
|
||||
|
||||
//! \~english Applies a function to each row (modifiable).
|
||||
//! \~russian Применяет функцию к каждой строке (с возможностью изменения).
|
||||
//! \~\sa forEachRow() const, PIVector::forEach()
|
||||
inline PIVector2D<T> & forEachRow(std::function<void(Row)> f) {
|
||||
for (size_t r = 0; r < rows_; ++r) {
|
||||
f(row(r));
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Applies a function to each row (read-only).
|
||||
//! \~russian Применяет функцию к каждой строке (только чтение).
|
||||
inline void forEachRow(std::function<void(RowConst)> f) const {
|
||||
for (size_t r = 0; r < rows_; ++r) {
|
||||
f(row(r));
|
||||
}
|
||||
}
|
||||
|
||||
//! \~english Applies a function to each column (modifiable).
|
||||
//! \~russian Применяет функцию к каждому столбцу (с возможностью изменения).
|
||||
inline PIVector2D<T> & forEachColumn(std::function<void(Col)> f) {
|
||||
for (size_t c = 0; c < cols_; ++c) {
|
||||
f(col(c));
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Applies a function to each column (read-only).
|
||||
//! \~russian Применяет функцию к каждому столбцу (только чтение).
|
||||
//! \param f Function taking a \a ColConst.
|
||||
inline void forEachColumn(std::function<void(ColConst)> f) const {
|
||||
for (size_t c = 0; c < cols_; ++c) {
|
||||
f(col(c));
|
||||
}
|
||||
}
|
||||
|
||||
//! \~english Accumulates a value across all elements.
|
||||
//! \~russian Аккумулирует значение по всем элементам.
|
||||
//! \~\sa PIVector::reduce()
|
||||
template<typename ST>
|
||||
inline ST reduce(std::function<ST(const T & e, const ST & acc)> f, const ST & initial = ST()) const {
|
||||
return mat.template reduce<ST>(std::move(f), initial);
|
||||
}
|
||||
|
||||
//! \~english Accumulates a value across all elements with indices.
|
||||
//! \~russian Аккумулирует значение по всем элементам с индексами.
|
||||
//! \~\sa PIVector::reduceIndexed()
|
||||
template<typename ST>
|
||||
inline ST reduceIndexed(std::function<ST(size_t row, size_t col, const T & e, const ST & acc)> f, const ST & initial = ST()) const {
|
||||
ST ret(initial);
|
||||
for (size_t r = 0; r < rows_; ++r) {
|
||||
for (size_t c = 0; c < cols_; ++c) {
|
||||
ret = f(r, c, element(r, c), ret);
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
//! \~english Removes a row from the 2D array.
|
||||
//! \~russian Удаляет строку из двумерного массива.
|
||||
//! \details
|
||||
//! \~english If the last row is removed and the array becomes empty, \a cols() is set to 0.
|
||||
//! \~russian Если удаляется последняя строка и массив становится пустым, \a cols() устанавливается в 0.
|
||||
//! \~\sa removeColumn(), PIVector::remove()
|
||||
inline PIVector2D<T> & removeRow(size_t row) { return deleteRows(row, 1); }
|
||||
|
||||
//! \~english Removes a column from the 2D array.
|
||||
//! \~russian Удаляет столбец из двумерного массива.
|
||||
//! \details
|
||||
//! \~english This operation is more expensive than removing a row because elements must be moved.
|
||||
//! \~russian Эта операция дороже, чем удаление строки, поскольку требуется перемещение элементов.
|
||||
//! \~\sa removeRow(), PIVector::remove()
|
||||
inline PIVector2D<T> & removeColumn(size_t col) { return deleteColumns(col, 1); }
|
||||
|
||||
//! \~english Removes all rows that satisfy a condition.
|
||||
//! \~russian Удаляет все строки, удовлетворяющие условию.
|
||||
//! \details
|
||||
//! \~english Rows are removed from the bottom to avoid index shifting issues.
|
||||
//! \~russian Строки удаляются снизу вверх, чтобы избежать проблем со смещением индексов.
|
||||
//! \~\sa removeColumnsWhere(), PIVector::removeWhere()
|
||||
inline PIVector2D<T> & removeRowsWhere(std::function<bool(const RowConst &)> test) {
|
||||
ssize_t r = rows_;
|
||||
while (--r >= 0) {
|
||||
if (test(RowConst(this, r))) {
|
||||
removeRow(r);
|
||||
}
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Removes all columns that satisfy a condition.
|
||||
//! \~russian Удаляет все столбцы, удовлетворяющие условию.
|
||||
//! \~\sa removeRowsWhere()
|
||||
inline PIVector2D<T> & removeColumnsWhere(std::function<bool(const ColConst &)> test) {
|
||||
ssize_t c = cols_;
|
||||
while (--c >= 0) {
|
||||
if (test(ColConst(this, c))) {
|
||||
removeColumn(c);
|
||||
}
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
|
||||
//! \~english Returns a new 2D array containing only the rows that pass the test.
|
||||
//! \~russian Возвращает новый двумерный массив, содержащий только строки, прошедшие проверку.
|
||||
//! \~\sa filterColumns(), PIVector::filter()
|
||||
inline PIVector2D<T> filterRows(std::function<bool(const RowConst &)> test) const {
|
||||
PIVector2D<T> result;
|
||||
for (size_t r = 0; r < rows_; ++r) {
|
||||
RowConst currentRow = row(r);
|
||||
if (test(currentRow)) {
|
||||
result.addRow(currentRow);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
//! \~english Returns a new 2D array containing only the columns that pass the test.
|
||||
//! \~russian Возвращает новый двумерный массив, содержащий только столбцы, прошедшие проверку.
|
||||
//! \~\sa filterRows()
|
||||
inline PIVector2D<T> filterColumns(std::function<bool(const ColConst &)> test) const {
|
||||
if (isEmpty()) return PIVector2D<T>();
|
||||
PIVector<size_t> goodCols;
|
||||
for (size_t c = 0; c < cols_; ++c) {
|
||||
if (test(col(c))) {
|
||||
goodCols << c;
|
||||
}
|
||||
}
|
||||
PIVector2D<T> result;
|
||||
for (size_t gc = 0; gc < goodCols.size(); ++gc) {
|
||||
result.addColumn(col(goodCols[gc]));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
protected:
|
||||
size_t rows_, cols_;
|
||||
PIVector<T> mat;
|
||||
};
|
||||
|
||||
|
||||
//! \relatesalso PICout
|
||||
//! \~english Output operator for \a PIVector2D to \a PICout.
|
||||
//! \~russian Оператор вывода \a PIVector2D в \a PICout.
|
||||
template<typename T>
|
||||
inline PICout operator<<(PICout s, const PIVector2D<T> & v) {
|
||||
s.saveAndSetControls(0);
|
||||
@@ -346,5 +1410,6 @@ inline PICout operator<<(PICout s, const PIVector2D<T> & v) {
|
||||
return s;
|
||||
}
|
||||
|
||||
//! \}
|
||||
|
||||
#endif // PIVECTOR2D_H
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
/*! \file pibase.h
|
||||
* \ingroup Core
|
||||
* \~\brief
|
||||
* \~english Base types and functions
|
||||
* \~russian Базовые типы и методы
|
||||
*
|
||||
* \~\details
|
||||
* \~english
|
||||
* This file implements first layer above the system and
|
||||
* declares some basic useful functions
|
||||
* \~russian
|
||||
* Этот файл реализует первый слой после системы и объявляет
|
||||
* несколько базовых полезных методов
|
||||
*/
|
||||
//! \addtogroup Core
|
||||
//! \{
|
||||
//! \~\file pibase.h
|
||||
//! \brief
|
||||
//! \~english Base types and functions
|
||||
//! \~russian Базовые типы и методы
|
||||
//! \details
|
||||
//! \~english
|
||||
//! This file implements first layer above the system and
|
||||
//! declares some basic useful functions
|
||||
//! \~russian
|
||||
//! Этот файл реализует первый слой после системы и объявляет
|
||||
//! несколько базовых полезных методов
|
||||
//! \~\}
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Base types and functions
|
||||
@@ -245,6 +245,9 @@ inline constexpr T piAbs(const T & v) {
|
||||
}
|
||||
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Templated function return minimum of two values
|
||||
//! \~russian Шаблонный метод, возвращающий минимум из двух значений
|
||||
template<typename T>
|
||||
constexpr T piMin(const T & f, const T & s) {
|
||||
return ((f > s) ? s : f);
|
||||
@@ -282,6 +285,9 @@ constexpr T piMin(const T & f, const T & s, const Args &... args) {
|
||||
}
|
||||
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Templated function return maximum of two values
|
||||
//! \~russian Шаблонный метод, возвращающий максимум из двух значений
|
||||
template<typename T>
|
||||
constexpr T piMax(const T & f, const T & s) {
|
||||
return ((f < s) ? s : f);
|
||||
@@ -509,51 +515,87 @@ inline uint piHashData(const uchar * data, uint len, uint seed = 0) {
|
||||
}
|
||||
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Generic hash function, returns 0 for unknown types
|
||||
//! \~russian Хэш-функция общего назначения, возвращает 0 для неизвестных типов
|
||||
template<typename T>
|
||||
inline uint piHash(const T & v) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Hash function specialization for char type
|
||||
//! \~russian Специализация хэш-функции для типа char
|
||||
template<>
|
||||
inline uint piHash(const char & v) {
|
||||
return (uint)v;
|
||||
}
|
||||
//! \~\brief
|
||||
//! \~english Hash function specialization for uchar type
|
||||
//! \~russian Специализация хэш-функции для типа uchar
|
||||
template<>
|
||||
inline uint piHash(const uchar & v) {
|
||||
return (uint)v;
|
||||
}
|
||||
//! \~\brief
|
||||
//! \~english Hash function specialization for short type
|
||||
//! \~russian Специализация хэш-функции для типа short
|
||||
template<>
|
||||
inline uint piHash(const short & v) {
|
||||
return (uint)v;
|
||||
}
|
||||
//! \~\brief
|
||||
//! \~english Hash function specialization for ushort type
|
||||
//! \~russian Специализация хэш-функции для типа ushort
|
||||
template<>
|
||||
inline uint piHash(const ushort & v) {
|
||||
return (uint)v;
|
||||
}
|
||||
//! \~\brief
|
||||
//! \~english Hash function specialization for int type
|
||||
//! \~russian Специализация хэш-функции для типа int
|
||||
template<>
|
||||
inline uint piHash(const int & v) {
|
||||
return (uint)v;
|
||||
}
|
||||
//! \~\brief
|
||||
//! \~english Hash function specialization for uint type
|
||||
//! \~russian Специализация хэш-функции для типа uint
|
||||
template<>
|
||||
inline uint piHash(const uint & v) {
|
||||
return (uint)v;
|
||||
}
|
||||
//! \~\brief
|
||||
//! \~english Hash function specialization for llong type using piHashData
|
||||
//! \~russian Специализация хэш-функции для типа llong с использованием piHashData
|
||||
template<>
|
||||
inline uint piHash(const llong & v) {
|
||||
return piHashData((const uchar *)&v, sizeof(v));
|
||||
}
|
||||
//! \~\brief
|
||||
//! \~english Hash function specialization for ullong type using piHashData
|
||||
//! \~russian Специализация хэш-функции для типа ullong с использованием piHashData
|
||||
template<>
|
||||
inline uint piHash(const ullong & v) {
|
||||
return piHashData((const uchar *)&v, sizeof(v));
|
||||
}
|
||||
//! \~\brief
|
||||
//! \~english Hash function specialization for float type
|
||||
//! \~russian Специализация хэш-функции для типа float
|
||||
template<>
|
||||
inline uint piHash(const float & v) {
|
||||
return (uint)v;
|
||||
}
|
||||
//! \~\brief
|
||||
//! \~english Hash function specialization for double type using piHashData
|
||||
//! \~russian Специализация хэш-функции для типа double с использованием piHashData
|
||||
template<>
|
||||
inline uint piHash(const double & v) {
|
||||
return piHashData((const uchar *)&v, sizeof(v));
|
||||
}
|
||||
//! \~\brief
|
||||
//! \~english Hash function specialization for ldouble type using piHashData
|
||||
//! \~russian Специализация хэш-функции для типа ldouble с использованием piHashData
|
||||
template<>
|
||||
inline uint piHash(const ldouble & v) {
|
||||
return piHashData((const uchar *)&v, sizeof(v));
|
||||
@@ -684,11 +726,12 @@ inline bool piDeleteSafety(T *& pointer) {
|
||||
//! \~english In this example "Error!" will be printed on every \b false function return.
|
||||
//! \~russian В данном примере будет выведен "Error!" при каждом \b false возврате из функции.
|
||||
class PIP_EXPORT PIScopeExitCall {
|
||||
NO_COPY_CLASS(PIScopeExitCall)
|
||||
public:
|
||||
//! \~\brief
|
||||
//! \~english Constructor that takes a function to execute
|
||||
//! \~russian Конструктор, который принимает функцию для выполнения
|
||||
explicit PIScopeExitCall(std::function<void()> f): func(f) {}
|
||||
explicit PIScopeExitCall(std::function<void()> f): func(std::move(f)) {}
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Destructor that executes the function if it exists
|
||||
@@ -716,8 +759,6 @@ public:
|
||||
}
|
||||
|
||||
private:
|
||||
NO_COPY_CLASS(PIScopeExitCall)
|
||||
|
||||
std::function<void()> func;
|
||||
};
|
||||
|
||||
@@ -726,26 +767,40 @@ private:
|
||||
//! \~english Inherit from this class to make your class non-trivially copyable.
|
||||
//! \~russian Наследуйтесь от этого класса чтобы сделать свой класс нетривиально копируемым.
|
||||
struct PIP_EXPORT PINonTriviallyCopyable {
|
||||
PINonTriviallyCopyable() noexcept = default;
|
||||
PINonTriviallyCopyable(const PINonTriviallyCopyable &) noexcept = default;
|
||||
PINonTriviallyCopyable(PINonTriviallyCopyable &&) noexcept;
|
||||
PINonTriviallyCopyable & operator=(const PINonTriviallyCopyable &) noexcept = default;
|
||||
PINonTriviallyCopyable & operator=(PINonTriviallyCopyable &&) noexcept = default;
|
||||
PINonTriviallyCopyable() = default;
|
||||
PINonTriviallyCopyable(const PINonTriviallyCopyable &) = default;
|
||||
PINonTriviallyCopyable(PINonTriviallyCopyable &&) ;
|
||||
PINonTriviallyCopyable & operator=(const PINonTriviallyCopyable &) = default;
|
||||
PINonTriviallyCopyable & operator=(PINonTriviallyCopyable &&) = default;
|
||||
~PINonTriviallyCopyable() = default;
|
||||
};
|
||||
inline PINonTriviallyCopyable::PINonTriviallyCopyable(PINonTriviallyCopyable &&) noexcept = default;
|
||||
inline PINonTriviallyCopyable::PINonTriviallyCopyable(PINonTriviallyCopyable &&) = default;
|
||||
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Template struct for extracting function type from callable objects
|
||||
//! \~russian Шаблонная структура для извлечения типа функции из вызываемых объектов
|
||||
template<typename T>
|
||||
struct FunctionType {
|
||||
using Type = void;
|
||||
};
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Specialization for member function pointers
|
||||
//! \~russian Специализация для указателей на члены класса
|
||||
template<typename Ret, typename Class, typename... Args>
|
||||
struct FunctionType<Ret (Class::*)(Args...) const> {
|
||||
using Type = std::function<Ret(Args...)>;
|
||||
};
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Convert lambda/functional object to std::function
|
||||
//! \~russian Преобразует лямбду/функциональный объект в std::function
|
||||
//! \~\details
|
||||
//! \~english
|
||||
//! Uses FunctionType template to extract the function signature from the callable object
|
||||
//! \~russian
|
||||
//! Использует шаблон FunctionType для извлечения сигнатуры функции из вызываемого объекта
|
||||
template<typename L>
|
||||
typename FunctionType<decltype(&L::operator())>::Type toStdFunction(L const & func) {
|
||||
return func;
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
/*! \file pibase_macros.h
|
||||
* \ingroup Core
|
||||
* \~\brief
|
||||
* \~english Base macros
|
||||
* \~russian Базовые макросы
|
||||
*
|
||||
* \~\details
|
||||
* \~english
|
||||
* This file declares basic useful maros
|
||||
* \~russian
|
||||
* Этот файл объявляет основные вспомогательные макросы
|
||||
*/
|
||||
//! \addtogroup Core
|
||||
//! \{
|
||||
//! \~\file pibase_macros.h
|
||||
//! \brief
|
||||
//! \~english Base macros
|
||||
//! \~russian Базовые макросы
|
||||
//! \details
|
||||
//! \~english
|
||||
//! This file declares basic useful macros for the PIP library including platform detection,
|
||||
//! compiler-specific configurations, and utility macros for private data handling.
|
||||
//! \~russian
|
||||
//! Этот файл объявляет основные вспомогательные макросы для библиотеки PIP, включая обнаружение платформы,
|
||||
//! конфигурации, специфичные для компилятора, и служебные макросы для работы с приватными данными.
|
||||
//! \~\}
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Base macros
|
||||
@@ -50,147 +52,118 @@
|
||||
|
||||
#ifdef DOXYGEN
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Major value of PIP version
|
||||
//! \~russian Мажорная версия PIP
|
||||
# define PIP_VERSION_MAJOR
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Minor value of PIP version
|
||||
//! \~russian Минорная версия PIP
|
||||
# define PIP_VERSION_MINOR
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Revision value of PIP version
|
||||
//! \~russian Ревизия версии PIP
|
||||
# define PIP_VERSION_REVISION
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Suffix of PIP version
|
||||
//! \~russian Суффикс версии PIP
|
||||
# define PIP_VERSION_SUFFIX
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Version of PIP in hex - 0x##(Major)##(Minor)##(Revision)
|
||||
//! \~russian Версия PIP в hex - 0x##(Major)##(Minor)##(Revision)
|
||||
# define PIP_VERSION
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Macro is defined when compile-time debug is enabled
|
||||
//! \~russian Макрос объявлен когда включена compile-time отладка
|
||||
# define PIP_DEBUG
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Macro is defined when operation system is any Windows
|
||||
//! \~russian Макрос объявлен когда операционная система Windows
|
||||
# define WINDOWS
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Macro is defined when operation system is QNX or Blackberry
|
||||
//! \~russian Макрос объявлен когда операционная система QNX или Blackberry
|
||||
# define QNX
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Macro is defined when operation system is Blackberry
|
||||
//! \~russian Макрос объявлен когда операционная система Blackberry
|
||||
# define BLACKBERRY
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Macro is defined when operation system is FreeBSD
|
||||
//! \~russian Макрос объявлен когда операционная система FreeBSD
|
||||
# define FREE_BSD
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Macro is defined when operation system is Mac OS
|
||||
//! \~russian Макрос объявлен когда операционная система Mac OS
|
||||
# define MAC_OS
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Macro is defined when operation system is Android
|
||||
//! \~russian Макрос объявлен когда операционная система Android
|
||||
# define ANDROID
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Macro is defined when operation system is any Linux
|
||||
//! \~russian Макрос объявлен когда операционная система Linux
|
||||
# define LINUX
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Macro is defined when operation system is FreeRTOS
|
||||
//! \~russian Макрос объявлен когда операционная система FreeRTOS
|
||||
# define FREERTOS
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Macro is defined when compiler is GCC or MinGW
|
||||
//! \~russian Макрос объявлен когда компилятор GCC или MinGW
|
||||
# define CC_GCC
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Macro is defined when PIP is decided that host is support language
|
||||
//! \~russian Макрос объявлен когда PIP решил что система поддерживает локализацию
|
||||
# define HAS_LOCALE
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Macro is defined when PIP is building for embedded systems
|
||||
//! \~russian Макрос объявлен когда PIP собирается для встраиваемых систем
|
||||
# define MICRO_PIP
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Macro is defined when compiler is Visual Studio
|
||||
//! \~russian Макрос объявлен когда компилятор Visual Studio
|
||||
# define CC_VC
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Macro is defined when compiler is AVR GCC
|
||||
//! \~russian Макрос объявлен когда компилятор AVR GCC
|
||||
# define CC_AVR_GCC
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Macro is defined when compiler is unknown
|
||||
//! \~russian Макрос объявлен когда компилятор неизвестен
|
||||
# define CC_OTHER
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Macro to declare private section, "export" is optional
|
||||
//! \~russian Макрос для объявления частной секции, "export" необязателен
|
||||
# define PRIVATE_DECLARATION(export)
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Macro to start definition of private section
|
||||
//! \~russian Макрос для начала реализации частной секции
|
||||
# define PRIVATE_DEFINITION_START(Class)
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Macro to end definition of private section
|
||||
//! \~russian Макрос для окончания реализации частной секции
|
||||
# define PRIVATE_DEFINITION_END(Class)
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Macro to access private section by pointer
|
||||
//! \~russian Макрос для доступа к частной секции
|
||||
# define PRIVATE
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Macro to access private section by pointer without brakes ()
|
||||
//! \~english Macro to access private section by pointer without braces ()
|
||||
//! \~russian Макрос для доступа к частной секции без обрамляющих скобок ()
|
||||
# define PRIVATEWB
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Macro to start static initializer
|
||||
//! \~russian Макрос для начала статической инициализации
|
||||
# define STATIC_INITIALIZER_BEGIN
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Macro to end static initializer
|
||||
//! \~russian Макрос для окончания статической инициализации
|
||||
# define STATIC_INITIALIZER_END
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Macro to remove class copy availability
|
||||
//! \~russian Макрос для запрета копирования класса
|
||||
# define NO_COPY_CLASS(Class)
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Macro to supress compiler warning about unused variable
|
||||
//! \~russian Макрос для подавления предупреждения компилятора о неиспользуемой переменной
|
||||
# define NO_UNUSED(x)
|
||||
@@ -320,6 +293,9 @@ typedef long long ssize_t;
|
||||
// Private data macros
|
||||
#ifndef DOXYGEN
|
||||
|
||||
//! \~english Macro to declare private section, "export" is optional
|
||||
//! \~russian Макрос для объявления частной секции, "export" необязателен
|
||||
//! \~sa PRIVATE PRIVATEWB
|
||||
# define PRIVATE_DECLARATION(e) \
|
||||
struct __Private__; \
|
||||
friend struct __Private__; \
|
||||
@@ -332,10 +308,21 @@ typedef long long ssize_t;
|
||||
}; \
|
||||
__PrivateInitializer__ __privateinitializer__;
|
||||
|
||||
//! \~english Macro to start definition of private section
|
||||
//! \~russian Макрос для начала реализации частной секции
|
||||
//! \~sa PRIVATE_DEFINITION_END PRIVATE_DEFINITION_END_NO_INITIALIZE PRIVATE_DEFINITION_INITIALIZE PRIVATE PRIVATEWB
|
||||
# define PRIVATE_DEFINITION_START(c) struct c::__Private__ {
|
||||
# define PRIVATE_DEFINITION_END(c) \
|
||||
//! \~english Macro to end definition of private section without initialization
|
||||
//! \~russian Макрос для окончания реализации частной секции без инициализации
|
||||
//! \~sa PRIVATE_DEFINITION_END PRIVATE_DEFINITION_START PRIVATE_DEFINITION_INITIALIZE PRIVATE PRIVATEWB
|
||||
# define PRIVATE_DEFINITION_END_NO_INITIALIZE(c) \
|
||||
} \
|
||||
; \
|
||||
;
|
||||
|
||||
//! \~english Macro to initialize private section
|
||||
//! \~russian Макрос для инициализации частной секции
|
||||
//! \~sa PRIVATE_DEFINITION_END PRIVATE_DEFINITION_START PRIVATE_DEFINITION_END_NO_INITIALIZE PRIVATE PRIVATEWB
|
||||
# define PRIVATE_DEFINITION_INITIALIZE(c) \
|
||||
c::__PrivateInitializer__::__PrivateInitializer__() { \
|
||||
p = new c::__Private__(); \
|
||||
} \
|
||||
@@ -351,26 +338,50 @@ typedef long long ssize_t;
|
||||
return *this; \
|
||||
}
|
||||
|
||||
|
||||
//! \~english Macro to end definition of private section with initialization
|
||||
//! \~russian Макрос для окончания реализации частной секции с инициализацией
|
||||
//! \~sa PRIVATE_DEFINITION_END_NO_INITIALIZE PRIVATE_DEFINITION_START PRIVATE_DEFINITION_INITIALIZE PRIVATE PRIVATEWB
|
||||
# define PRIVATE_DEFINITION_END(c) \
|
||||
PRIVATE_DEFINITION_END_NO_INITIALIZE \
|
||||
(c) PRIVATE_DEFINITION_INITIALIZE(c)
|
||||
|
||||
//! \~english Macro to access private section by pointer
|
||||
//! \~russian Макрос для доступа к частной секции
|
||||
//! \~sa PRIVATEWB
|
||||
# define PRIVATE (__privateinitializer__.p)
|
||||
|
||||
//! \~english Macro to access private section by pointer without braces ()
|
||||
//! \~russian Макрос для доступа к частной секции без обрамляющих скобок ()
|
||||
//! \~sa PRIVATE
|
||||
# define PRIVATEWB __privateinitializer__.p
|
||||
|
||||
#endif // DOXYGEN
|
||||
|
||||
//! \~english Macro to remove class copy availability
|
||||
//! \~russian Макрос для запрета копирования класса
|
||||
#define NO_COPY_CLASS(name) \
|
||||
name(const name &) = delete; \
|
||||
name & operator=(const name &) = delete;
|
||||
|
||||
|
||||
//! \~english Counter macro for unique identifier generation
|
||||
//! \~russian Макрос счетчика для генерации уникальных идентификаторов
|
||||
#define _PIP_ADD_COUNTER_WS(a, cnt, line) a##cnt##_##line
|
||||
#define _PIP_ADD_COUNTER_WF(a, cnt, line) _PIP_ADD_COUNTER_WS(a, cnt, line)
|
||||
#define _PIP_ADD_COUNTER(a) _PIP_ADD_COUNTER_WF(a, __COUNTER__, __LINE__)
|
||||
|
||||
|
||||
//! \~english Macro to start static initializer
|
||||
//! \~russian Макрос для начала статической инициализации
|
||||
//! \~sa STATIC_INITIALIZER_END
|
||||
#define STATIC_INITIALIZER_BEGIN \
|
||||
class { \
|
||||
class _Initializer_ { \
|
||||
public: \
|
||||
_Initializer_() {
|
||||
//! \~english Macro to end static initializer
|
||||
//! \~russian Макрос для окончания статической инициализации
|
||||
//! \~sa STATIC_INITIALIZER_BEGIN
|
||||
#define STATIC_INITIALIZER_END \
|
||||
} \
|
||||
} \
|
||||
@@ -379,12 +390,12 @@ typedef long long ssize_t;
|
||||
_PIP_ADD_COUNTER(_pip_initializer_);
|
||||
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Minimal sleep in milliseconds for internal PIP using
|
||||
//! \~russian Минимальное значание задержки в милисекундах для внутреннего использования в библиотеке PIP
|
||||
//! \~\details
|
||||
//! \~english Using in \a piMinSleep(), \a PIThread, \a PITimer::Pool. By default 1ms.
|
||||
//! \~russian Используется в \a piMinSleep(), \a PIThread, \a PITimer::Pool. По умолчанию равна 1мс.
|
||||
//! \~\sa PIP_MIN_MSLEEP
|
||||
#ifndef PIP_MIN_MSLEEP
|
||||
# ifndef MICRO_PIP
|
||||
# define PIP_MIN_MSLEEP 1.
|
||||
@@ -394,19 +405,26 @@ typedef long long ssize_t;
|
||||
#endif
|
||||
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Macro used for infinite loop
|
||||
//! \~russian Макрос для бесконечного цикла
|
||||
//! \~\details
|
||||
//! \~english Expands to \c for(;;) infinite loop construct
|
||||
//! \~russian Раскрывается в конструкцию бесконечного цикла \c for(;;)
|
||||
#define FOREVER for (;;)
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Macro used for infinite wait
|
||||
//! \~russian Макрос для бесконечного ожидания
|
||||
//! \~\details
|
||||
//! \~english Expands to infinite loop with periodic sleep calls for CPU-friendly waiting
|
||||
//! \~russian Раскрывается в бесконечный цикл с периодическими вызовами sleep для экономии ресурсов CPU
|
||||
#define FOREVER_WAIT FOREVER piMinSleep();
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Macro used for infinite wait
|
||||
//! \~russian Макрос для бесконечного ожидания
|
||||
//! \~\details
|
||||
//! \~english Expands to infinite loop with periodic sleep calls for CPU-friendly waiting
|
||||
//! \~russian Раскрывается в бесконечный цикл с периодическими вызовами sleep для экономии ресурсов CPU
|
||||
//! \~\sa FOREVER_WAIT
|
||||
#define WAIT_FOREVER FOREVER piMinSleep();
|
||||
|
||||
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
/*! \file picollection.h
|
||||
* \ingroup Core
|
||||
* \~\brief
|
||||
* \~english Unique classes collection
|
||||
* \~russian Коллекция уникальных классов
|
||||
*/
|
||||
//! \addtogroup Core
|
||||
//! \{
|
||||
//! \~\file picollection.h
|
||||
//! \brief
|
||||
//! \~english Unique classes collection
|
||||
//! \~russian Коллекция уникальных классов
|
||||
//! \details
|
||||
//! \~english Helper module to collect and retrieve classes into groups using macros for automatic registration.
|
||||
//! \~russian Модуль-помощник для сбора и получения классов в группы с помощью макросов для автоматической регистрации.
|
||||
//! \~\}
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Peer - named I/O ethernet node, forming self-organized peering network
|
||||
@@ -30,10 +34,10 @@
|
||||
|
||||
#ifdef DOXYGEN
|
||||
|
||||
//! \~\relatesalso PICollection
|
||||
//! \relatesalso PICollection
|
||||
//! \~\brief
|
||||
//! \~english Add existing element "object" in group with name "group"
|
||||
//! \~russian Добавляет существующий элемент "object" в группу с именем "group"
|
||||
//! \~english Adds existing object to group "group".
|
||||
//! \~russian Добавляет существующий объект в группу "group".
|
||||
//! \~\details
|
||||
//! \~english
|
||||
//! If this is no group with name "group" it will be created.
|
||||
@@ -46,21 +50,21 @@
|
||||
//! то ничего не изменится. \n "object" должен быть наследником \a PIObject.
|
||||
# define ADD_TO_COLLECTION(group, object)
|
||||
|
||||
//! \~\relatesalso PICollection
|
||||
//! \relatesalso PICollection
|
||||
//! \~\brief
|
||||
//! \~english Add existing element "object" in group with name "group" and set its name to "name"
|
||||
//! \~russian Добавляет существующий элемент "object" в группу с именем "group" и присваивает объекту имя "name"
|
||||
//! \~english Adds existing object to group "group" and assigns name "name".
|
||||
//! \~russian Добавляет существующий объект в группу "group" и присваивает ему имя "name".
|
||||
//! \~\details
|
||||
//! \~english
|
||||
//! Similar to \a ADD_TO_COLLECTION(group, object) but set object name to "name"
|
||||
//! Similar to \a ADD_TO_COLLECTION(group, object), but also sets object name.
|
||||
//! \~russian
|
||||
//! Аналогично \a ADD_TO_COLLECTION(group, object), но присваивает имя объекту "name"
|
||||
//! Аналогично \a ADD_TO_COLLECTION(group, object), но дополнительно задает имя объекта.
|
||||
# define ADD_TO_COLLECTION_WITH_NAME(group, object, name)
|
||||
|
||||
//! \~\relatesalso PICollection
|
||||
//! \relatesalso PICollection
|
||||
//! \~\brief
|
||||
//! \~english Add new element of class "class" in group with name "group"
|
||||
//! \~russian Добавляет новый элемент класса "class" в группу с именем "group"
|
||||
//! \~english Creates and adds new object of class "class" to group "group".
|
||||
//! \~russian Создает и добавляет новый объект класса "class" в группу "group".
|
||||
//! \~\details
|
||||
//! \~english
|
||||
//! If this is no group with name "group" it will be created.
|
||||
@@ -73,15 +77,17 @@
|
||||
//! то ничего не изменится. \n "class" должен быть любым классом, наследным от \a PIObject.
|
||||
# define ADD_NEW_TO_COLLECTION(group, class)
|
||||
|
||||
//! \~\relatesalso PICollection
|
||||
//! \relatesalso PICollection
|
||||
//! \~\brief
|
||||
//! \~english Add new element of class "class" in group with name "group" and set its name to "name"
|
||||
//! \~russian Добавляет новый элемент класса "class" в группу с именем "group" и присваивает объекту имя "name"
|
||||
//! \~english Creates and adds new object of class "class" to group "group"
|
||||
//! and assigns name "name".
|
||||
//! \~russian Создает и добавляет новый объект класса "class" в группу "group"
|
||||
//! и присваивает ему имя "name".
|
||||
//! \~\details
|
||||
//! \~english
|
||||
//! Similar to \a ADD_NEW_TO_COLLECTION(group, class) but set object name to "name"
|
||||
//! Similar to \a ADD_NEW_TO_COLLECTION(group, class), but also sets object name.
|
||||
//! \~russian
|
||||
//! Аналогично \a ADD_NEW_TO_COLLECTION(group, class), но присваивает имя объекту "name"
|
||||
//! Аналогично \a ADD_NEW_TO_COLLECTION(group, class), но дополнительно задает имя объекта.
|
||||
# define ADD_NEW_TO_COLLECTION_WITH_NAME(group, class, name)
|
||||
|
||||
#else
|
||||
@@ -100,28 +106,40 @@
|
||||
|
||||
#endif
|
||||
|
||||
//! \ingroup Core
|
||||
//! \~\ingroup Core
|
||||
//! \~\brief
|
||||
//! \~english Helper to collect and retrieve classes to groups.
|
||||
//! \~russian Помощник для создания и получения классов в группы.
|
||||
//! \~english Global collection of %PIObject-based instances grouped by name.
|
||||
//! \~russian Глобальная коллекция экземпляров на базе %PIObject, сгруппированных по имени.
|
||||
class PIP_EXPORT PICollection {
|
||||
friend class __PICollectionInitializer;
|
||||
|
||||
public:
|
||||
//! \~english Constructs collection helper.
|
||||
//! \~russian Создает вспомогательный объект коллекции.
|
||||
PICollection() { ; }
|
||||
|
||||
//! \~english Returns all existing groups by their names
|
||||
//! \~russian Возвращает имена всех групп
|
||||
//! \~english Returns names of all existing groups.
|
||||
//! \~russian Возвращает имена всех существующих групп.
|
||||
static PIStringList groups();
|
||||
|
||||
//! \~english Returns all elements of group "group"
|
||||
//! \~russian Возвращает все элементы группы "group"
|
||||
//! \~english Returns all elements stored in group "group".
|
||||
//! \~russian Возвращает все элементы, хранящиеся в группе "group".
|
||||
static PIVector<const PIObject *> groupElements(const PIString & group);
|
||||
|
||||
//! \~english Adds object to group "group" if that group has no object of the
|
||||
//! same runtime class.
|
||||
//! \~russian Добавляет объект в группу "group", если в группе еще нет объекта
|
||||
//! того же класса времени выполнения.
|
||||
static bool addToGroup(const PIString & group, const PIObject * element);
|
||||
|
||||
//! \~\ingroup Core
|
||||
//! \~\brief
|
||||
//! \~english Helper that registers object in collection during static initialization.
|
||||
//! \~russian Вспомогательный класс, регистрирующий объект в коллекции при статической инициализации.
|
||||
class PIP_EXPORT CollectionAdder {
|
||||
public:
|
||||
//! \~english Registers object in group and optionally assigns object name.
|
||||
//! \~russian Регистрирует объект в группе и при необходимости задает имя объекта.
|
||||
CollectionAdder(const PIString & group, const PIObject * element, const PIString & name = PIString(), bool own = false);
|
||||
};
|
||||
|
||||
|
||||
@@ -1,3 +1,13 @@
|
||||
/*! \file picoremodule.h
|
||||
* \ingroup Core
|
||||
* \~\brief
|
||||
* \~english Umbrella header for the Core module
|
||||
* \~russian Агрегирующий заголовок модуля Core
|
||||
*
|
||||
* \~\details
|
||||
* \~english Includes the public chunk stream, collection, JSON, object, property storage, and time headers.
|
||||
* \~russian Подключает публичные заголовки потоков чанков, коллекций, JSON, объектов, хранилища свойств и времени.
|
||||
*/
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Module includes
|
||||
@@ -34,10 +44,12 @@
|
||||
//! \~russian \par Общее
|
||||
//!
|
||||
//! \~english
|
||||
//! These files provides platform abstraction, useful macros, methods and classes
|
||||
//! These headers provide platform abstraction, common macros, utility functions
|
||||
//! and base classes.
|
||||
//!
|
||||
//! \~russian
|
||||
//! Эти файлы обеспечивают абстракцию операционной системы, полезные макросы, методы и классы
|
||||
//! Эти заголовки предоставляют абстракцию платформы, общие макросы,
|
||||
//! вспомогательные функции и базовые классы.
|
||||
//!
|
||||
//! \~\authors
|
||||
//! \~english
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
/*! \file picout.h
|
||||
* \ingroup Core
|
||||
* \~\brief
|
||||
* \~english Universal output to console class
|
||||
* \~russian Универсальный вывод в консоль
|
||||
*/
|
||||
//! \addtogroup Core
|
||||
//! \{
|
||||
//! \~\file picout.h
|
||||
//! \brief
|
||||
//! \~english Universal output to console class
|
||||
//! \~russian Универсальный вывод в консоль
|
||||
//! \~\}
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Universal output to console class
|
||||
@@ -116,8 +117,8 @@ enum PICoutFormat {
|
||||
Dec /*! \~english Decimal representation of integers \~russian Десятичное представление для целых чисел */ = 0x04,
|
||||
Hex /*! \~english Hexadecimal representation of integers \~russian Шестнадцатеричное представление для целых чисел */ = 0x08,
|
||||
Bold /*! \~english Bold \~russian Жирный */ = 0x10,
|
||||
Faint /*! \~english \~russian */ = 0x20,
|
||||
Italic /*! \~english \~russian */ = 0x40,
|
||||
Faint /*! \~english Faint \~russian Тусклый */ = 0x20,
|
||||
Italic /*! \~english Italic \~russian Курсив */ = 0x40,
|
||||
Underline /*! \~english Underline \~russian Подчеркнутый */ = 0x80,
|
||||
Blink /*! \~english Blink \~russian Мигающий */ = 0x100,
|
||||
Black /*! \~english Black font \~russian Чёрный */ = 0x400,
|
||||
@@ -153,10 +154,15 @@ enum class PICoutStdStream {
|
||||
};
|
||||
|
||||
|
||||
//! \ingroup Core
|
||||
//! \~\ingroup Core
|
||||
//! \~\brief
|
||||
//! \~english Universal output to console class.
|
||||
//! \~russian Универсальный вывод в консоль.
|
||||
//! \details
|
||||
//! \~english This class provides a universal output interface with support for various data types, formatting options, and multiple output
|
||||
//! devices (console, buffer).
|
||||
//! \~russian Данный класс предоставляет универсальный интерфейс вывода с поддержкой различных типов данных, опций форматирования и
|
||||
//! нескольких устройств вывода (консоль, буфер).
|
||||
class PIP_EXPORT PICout {
|
||||
public:
|
||||
//! \~english Default constructor with default features (AddSpaces and AddNewLine)
|
||||
@@ -178,10 +184,16 @@ public:
|
||||
public:
|
||||
//! \~english Singleton access to %PICout::Notifier
|
||||
//! \~russian Синглтон класса %PICout::Notifier
|
||||
//! \details
|
||||
//! \~english Returns the singleton instance of the Notifier class used for emitting PICout events.
|
||||
//! \~russian Возвращает синглтон-экземпляр класса Notifier, используемого для посылки событий PICout.
|
||||
static Notifier * instance();
|
||||
|
||||
//! \~english Object that emit events from %PICout
|
||||
//! \~russian Объект, который посылает события от %PICout
|
||||
//! \details
|
||||
//! \~english Returns the PIObject instance that emits events when PICout with external buffer is destroyed.
|
||||
//! \~russian Возвращает экземпляр PIObject, который посылает события при уничтожении PICout с внешним буфером.
|
||||
static PIObject * object();
|
||||
|
||||
private:
|
||||
@@ -234,26 +246,51 @@ public:
|
||||
|
||||
//! \~english Output operator for <tt>"int"</tt> values
|
||||
//! \~russian Оператор вывода для <tt>"int"</tt> значений
|
||||
//! \details
|
||||
//! \~english Outputs an integer value to the configured stream with optional format (binary, octal, decimal, hexadecimal).
|
||||
//! \~russian Выводит целочисленное значение в настроенный поток с опциональным форматированием (binary, octal, decimal, hexadecimal).
|
||||
PICout & operator<<(int v);
|
||||
|
||||
//! \~english Output operator for <tt>"unsigned int"</tt> values
|
||||
//! \~russian Оператор вывода для <tt>"unsigned int"</tt> значений
|
||||
//! \details
|
||||
//! \~english Outputs an unsigned integer value to the configured stream with optional format (binary, octal, decimal, hexadecimal).
|
||||
//! \~russian Выводит беззнаковое целочисленное значение в настроенный поток с опциональным форматированием (binary, octal, decimal,
|
||||
//! hexadecimal).
|
||||
PICout & operator<<(uint v);
|
||||
|
||||
//! \~english Output operator for <tt>"long"</tt> values
|
||||
//! \~russian Оператор вывода для <tt>"long"</tt> значений
|
||||
//! \details
|
||||
//! \~english Outputs a long integer value to the configured stream with optional format (binary, octal, decimal, hexadecimal).
|
||||
//! \~russian Выводит длинное целочисленное значение в настроенный поток с опциональным форматированием (binary, octal, decimal,
|
||||
//! hexadecimal).
|
||||
PICout & operator<<(long v);
|
||||
|
||||
//! \~english Output operator for <tt>"unsigned long"</tt> values
|
||||
//! \~russian Оператор вывода для <tt>"unsigned long"</tt> значений
|
||||
//! \details
|
||||
//! \~english Outputs an unsigned long integer value to the configured stream with optional format (binary, octal, decimal,
|
||||
//! hexadecimal).
|
||||
//! \~russian Выводит беззнаковое длинное целочисленное значение в настроенный поток с опциональным форматированием (binary, octal,
|
||||
//! decimal, hexadecimal).
|
||||
PICout & operator<<(ulong v);
|
||||
|
||||
//! \~english Output operator for <tt>"long long"</tt> values
|
||||
//! \~russian Оператор вывода для <tt>"long long"</tt> значений
|
||||
//! \details
|
||||
//! \~english Outputs a long long integer value to the configured stream with optional format (binary, octal, decimal, hexadecimal).
|
||||
//! \~russian Выводит длинное long long целочисленное значение в настроенный поток с опциональным форматированием (binary, octal,
|
||||
//! decimal, hexadecimal).
|
||||
PICout & operator<<(llong v);
|
||||
|
||||
//! \~english Output operator for <tt>"unsigned long long"</tt> values
|
||||
//! \~russian Оператор вывода для <tt>"unsigned long long"</tt> значений
|
||||
//! \details
|
||||
//! \~english Outputs an unsigned long long integer value to the configured stream with optional format (binary, octal, decimal,
|
||||
//! hexadecimal).
|
||||
//! \~russian Выводит беззнаковое длинное long long целочисленное значение в настроенный поток с опциональным форматированием (binary,
|
||||
//! octal, decimal, hexadecimal).
|
||||
PICout & operator<<(ullong v);
|
||||
|
||||
//! \~english Output operator for <tt>"float"</tt> values
|
||||
@@ -270,10 +307,16 @@ public:
|
||||
|
||||
//! \~english Output operator for pointers
|
||||
//! \~russian Оператор вывода для указателей
|
||||
//! \details
|
||||
//! \~english Outputs a pointer address to the configured stream in hexadecimal format.
|
||||
//! \~russian Выводит адрес указателя в настроенный поток в шестнадцатеричном формате.
|
||||
PICout & operator<<(const void * v);
|
||||
|
||||
//! \~english Output operator for PIObject and ancestors
|
||||
//! \~russian Оператор вывода для PIObject и наследников
|
||||
//! \details
|
||||
//! \~english Outputs a PIObject or its descendants to the configured stream, including class name and object name.
|
||||
//! \~russian Выводит PIObject или его наследников в настроенный поток, включая имя класса и имя объекта.
|
||||
PICout & operator<<(const PIObject * v);
|
||||
|
||||
//! \~english Output operator for \a PICoutSpecialChar values
|
||||
@@ -282,10 +325,18 @@ public:
|
||||
|
||||
//! \~english Output operator for \a PIFlags<PICoutFormat> values
|
||||
//! \~russian Оператор вывода для \a PIFlags<PICoutFormat>
|
||||
//! \details
|
||||
//! \~english Sets output format flags (binary, octal, decimal, hexadecimal, bold, colors) for subsequent integer output.
|
||||
//! \~russian Устанавливает флаги форматирования вывода (binary, octal, decimal, hexadecimal, bold, colors) для последующего вывода
|
||||
//! целых чисел.
|
||||
PICout & operator<<(PIFlags<PICoutManipulators::PICoutFormat> v);
|
||||
|
||||
//! \~english Output operator for \a PICoutFormat values
|
||||
//! \~russian Оператор вывода для \a PICoutFormat
|
||||
//! \details
|
||||
//! \~english Sets output format flag (binary, octal, decimal, hexadecimal, bold, colors) for subsequent integer output.
|
||||
//! \~russian Устанавливает флаг форматирования вывода (binary, octal, decimal, hexadecimal, bold, colors) для последующего вывода целых
|
||||
//! чисел.
|
||||
PICout & operator<<(PICoutManipulators::PICoutFormat v);
|
||||
|
||||
//! \~english Do some action
|
||||
@@ -301,45 +352,72 @@ public:
|
||||
PICout & setControls(PICoutManipulators::PICoutControls c);
|
||||
|
||||
//! \~english Exec \a saveControls() and set control flags to "c"
|
||||
//! \~russian Иыполнить \a saveControls() и Установить флаги "c"
|
||||
//! \~russian Выполнить \a saveControls() и установить флаги "c"
|
||||
PICout & saveAndSetControls(PICoutManipulators::PICoutControls c);
|
||||
|
||||
//! \~english Save control flags to internal stack
|
||||
//! \~russian Сохраняет состояние флагов во внутренний стек
|
||||
//! \~\sa \a restoreControl()
|
||||
//! \details
|
||||
//! \~english Saves the current control flags to an internal stack for later restoration using restoreControls().
|
||||
//! \~russian Сохраняет текущие флаги управления во внутренний стек для последующего восстановления с помощью restoreControls().
|
||||
//! \~\sa \a restoreControls()
|
||||
PICout & saveControls();
|
||||
|
||||
//! \~english Restore control flags from internal stack
|
||||
//! \~russian Восстанавливает состояние флагов из внутреннего стека
|
||||
//! \~\sa \a saveControl()
|
||||
//! \details
|
||||
//! \~english Restores the control flags from the internal stack that were previously saved using saveControls().
|
||||
//! \~russian Восстанавливает флаги управления из внутреннего стека, которые были ранее сохранены с помощью saveControls().
|
||||
//! \~\sa \a saveControls()
|
||||
PICout & restoreControls();
|
||||
|
||||
//! \~english Conditional put space character to output
|
||||
//! \~russian Условно добавляет пробел
|
||||
//! \details
|
||||
//! \~english Conditionally adds a space character to the output if the AddSpaces control flag is enabled.
|
||||
//! \~russian Условно добавляет пробел в вывод, если включен флаг управления AddSpaces.
|
||||
PICout & space();
|
||||
|
||||
//! \~english Conditional put quote character to output
|
||||
//! \~russian Условно добавляет кавычки
|
||||
//! \details
|
||||
//! \~english Conditionally adds quote characters to the output if the AddQuotes control flag is enabled.
|
||||
//! \~russian Условно добавляет кавычки в вывод, если включен флаг управления AddQuotes.
|
||||
PICout & quote();
|
||||
|
||||
//! \~english Conditional put new line character to output
|
||||
//! \~russian Условно добавляет новую строку
|
||||
//! \details
|
||||
//! \~english Conditionally adds a newline character to the output if the AddNewLine control flag is enabled.
|
||||
//! \~russian Условно добавляет символ новой строки в вывод, если включен флаг управления AddNewLine.
|
||||
PICout & newLine();
|
||||
|
||||
//! \~english Write char
|
||||
//! \~russian Пишет символ
|
||||
//! \details
|
||||
//! \~english Writes a single character directly to the output stream without any formatting.
|
||||
//! \~russian Записывает один символ непосредственно в поток вывода без какого-либо форматирования.
|
||||
PICout & write(char c);
|
||||
|
||||
//! \~english Write raw data
|
||||
//! \~russian Пишет сырые символы
|
||||
//! \details
|
||||
//! \~english Writes raw C-style string data directly to the output stream without any formatting.
|
||||
//! \~russian Записывает сырые данные C-строки непосредственно в поток вывода без какого-либо форматирования.
|
||||
PICout & write(const char * str);
|
||||
|
||||
//! \~english Write raw data
|
||||
//! \~russian Пишет сырые символы
|
||||
//! \details
|
||||
//! \~english Writes raw data of specified length directly to the output stream without any formatting.
|
||||
//! \~russian Записывает сырые данные указанной длины непосредственно в поток вывода без какого-либо форматирования.
|
||||
PICout & write(const char * str, int len);
|
||||
|
||||
//! \~english Write raw \a PIString
|
||||
//! \~russian Пишет сырой \a PIString
|
||||
//! \details
|
||||
//! \~english Writes raw PIString data directly to the output stream without any formatting.
|
||||
//! \~russian Записывает сырые данные PIString непосредственно в поток вывода без какого-либо форматирования.
|
||||
PICout & write(const PIString & s);
|
||||
|
||||
//! \~english Output \a PIString to stdout
|
||||
@@ -386,11 +464,19 @@ public:
|
||||
|
||||
//! \~english Construct with external buffer.
|
||||
//! \~russian Конструктор с внешним буфером.
|
||||
//! \details
|
||||
//! \~english Creates a PICout instance that outputs to an external PIString buffer with specified control flags.
|
||||
//! \~russian Создает экземпляр PICout, который выводит данные во внешний буфер PIString с указанными флагами управления.
|
||||
static PICout withExternalBuffer(PIString * buffer,
|
||||
PIFlags<PICoutManipulators::PICoutControl> controls = PICoutManipulators::AddSpaces);
|
||||
|
||||
//! \~english Construct with external buffer and ID "id". See \a Notifier for details
|
||||
//! \~russian Конструктор с внешним буфером и ID "id". Подробнее \a Notifier
|
||||
//! \details
|
||||
//! \~english Creates a PICout instance with external buffer and notification ID. When the last copy is destroyed, it emits a finished()
|
||||
//! event via Notifier.
|
||||
//! \~russian Создает экземпляр PICout с внешним буфером и идентификатором уведомления. При уничтожении последней копии посылается
|
||||
//! событие finished() через Notifier.
|
||||
static PICout withExternalBufferAndID(PIString * buffer,
|
||||
int id,
|
||||
PIFlags<PICoutManipulators::PICoutControl> controls = PICoutManipulators::DefaultControls);
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
/*! \file piincludes.h
|
||||
* \ingroup Core
|
||||
* \~\brief
|
||||
* \~english Minimal PIP includes
|
||||
* \~russian Минимально-необходимые инклюды PIP
|
||||
* \~english Core includes and low-level helper functions
|
||||
* \~russian Базовые включения и низкоуровневые вспомогательные функции
|
||||
*/
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
@@ -50,27 +50,42 @@ class PIWaitEvent;
|
||||
|
||||
struct lconv;
|
||||
|
||||
//! \~\ingroup Core
|
||||
//! \~\brief
|
||||
//! \~english Pointer to current C locale numeric settings
|
||||
//! \~russian Указатель на текущие числовые настройки C locale
|
||||
extern PIP_EXPORT lconv * currentLocale;
|
||||
|
||||
//! \ingroup Core
|
||||
//! \brief
|
||||
//! \~english Return readable error description in format "code <number> - <description>"
|
||||
//! \~russian Возвращает читаемое описание ошибки в формате "code <номер> - <описание>"
|
||||
//! \~\ingroup Core
|
||||
//! \~\brief
|
||||
//! \~english Returns readable description of the last system error in format
|
||||
//! "code <number> - <description>"
|
||||
//! \~russian Возвращает читаемое описание последней системной ошибки в формате
|
||||
//! "code <номер> - <описание>"
|
||||
PIP_EXPORT PIString errorString();
|
||||
|
||||
//! \ingroup Core
|
||||
//! \brief
|
||||
//! \~english Reset last error
|
||||
//! \~russian Сброс последней ошибки
|
||||
//! \~\ingroup Core
|
||||
//! \~\brief
|
||||
//! \~english Clears the last system error
|
||||
//! \~russian Сбрасывает последнюю системную ошибку
|
||||
PIP_EXPORT void errorClear();
|
||||
|
||||
//! \~\ingroup Core
|
||||
//! \~\brief
|
||||
//! \~english Seeds the global pseudo-random generator
|
||||
//! \~russian Инициализирует глобальный генератор псевдослучайных чисел
|
||||
PIP_EXPORT void randomize();
|
||||
|
||||
//! \~\ingroup Core
|
||||
//! \~\brief
|
||||
//! \~english Returns next value from the global pseudo-random generator
|
||||
//! \~russian Возвращает следующее значение глобального генератора псевдослучайных чисел
|
||||
PIP_EXPORT int randomi();
|
||||
|
||||
//! \ingroup Core
|
||||
//! \brief
|
||||
//! \~english Return readable version of PIP
|
||||
//! \~russian Возвращает читаемую версию PIP
|
||||
//! \~\ingroup Core
|
||||
//! \~\brief
|
||||
//! \~english Returns readable PIP version string
|
||||
//! \~russian Возвращает строку версии PIP
|
||||
PIP_EXPORT PIString PIPVersion();
|
||||
|
||||
#endif // PIINCLUDES_H
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
/*! \file piinit.h
|
||||
* \ingroup Core
|
||||
* \~\brief
|
||||
* \~english Library initialization
|
||||
* \~russian Инициализация библиотеки
|
||||
*/
|
||||
//! \~\ingroup Core
|
||||
//! \~\file piinit.h
|
||||
//! \~\brief
|
||||
//! \~english Library initialization
|
||||
//! \~russian Инициализация библиотеки
|
||||
//! \details
|
||||
//! \~english This file provides initialization and build information for the PIP library.
|
||||
//! \~russian Этот файл предоставляет инициализацию и информацию о сборке для библиотеки PIP.//! \}
|
||||
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Initialization
|
||||
@@ -36,7 +39,6 @@
|
||||
class PIFile;
|
||||
class PIStringList;
|
||||
|
||||
|
||||
class PIP_EXPORT __PIInit_Initializer__ {
|
||||
public:
|
||||
__PIInit_Initializer__();
|
||||
@@ -47,7 +49,10 @@ public:
|
||||
|
||||
static __PIInit_Initializer__ __piinit_initializer__;
|
||||
|
||||
|
||||
//! \~\ingroup Core
|
||||
//! \~\brief
|
||||
//! \~english Library initialization singleton and build information access point.
|
||||
//! \~russian Синглтон инициализации библиотеки и точка доступа к сведениям о сборке.
|
||||
class PIP_EXPORT PIInit {
|
||||
friend class __PIInit_Initializer__;
|
||||
friend class PIFile;
|
||||
@@ -55,9 +60,9 @@ class PIP_EXPORT PIInit {
|
||||
public:
|
||||
~PIInit();
|
||||
|
||||
//! \ingroup Core
|
||||
//! \~english Build options which PIP library was built
|
||||
//! \~russian Опции, с которыми был собран PIP
|
||||
//! \~\ingroup Core
|
||||
//! \~english Build options enabled in the current PIP library
|
||||
//! \~russian Опции, включенные в текущей сборке библиотеки PIP
|
||||
enum BuildOption {
|
||||
boICU /*! \~english Unicode support by ICU \~russian Поддержка юникода через ICU */ = 0x01,
|
||||
boUSB /*! \~english USB support \~russian Поддержка USB */ = 0x02,
|
||||
@@ -69,16 +74,19 @@ public:
|
||||
boCloud /*! \~english PICloud transport support \~russian Поддержка облачного транспорта PICloud */ = 0x200,
|
||||
boConsole /*! \~english Console graphics support \~russian Поддержка графики в консоли */ = 0x400,
|
||||
};
|
||||
|
||||
//! \~english Returns current global %PIInit instance.
|
||||
//! \~russian Возвращает текущий глобальный экземпляр %PIInit.
|
||||
static PIInit * instance() { return __PIInit_Initializer__::__instance__; }
|
||||
|
||||
//! \ingroup Core
|
||||
//! \~english Returns if build option was enabled
|
||||
//! \~russian Возвращает была ли включена опция при сборке
|
||||
//! \~\ingroup Core
|
||||
//! \~english Returns whether build option was enabled
|
||||
//! \~russian Возвращает, была ли опция включена при сборке
|
||||
static bool isBuildOptionEnabled(BuildOption o);
|
||||
|
||||
//! \ingroup Core
|
||||
//! \~english Returns build options as stringlist
|
||||
//! \~russian Возвращает опции сборки как список строк
|
||||
//! \~\ingroup Core
|
||||
//! \~english Returns enabled build options as string list
|
||||
//! \~russian Возвращает включенные опции сборки в виде списка строк
|
||||
static PIStringList buildOptions();
|
||||
|
||||
private:
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
/*! \file pimemoryblock.h
|
||||
* \ingroup Core
|
||||
* \~\brief
|
||||
* \~english Base types and functions
|
||||
* \~russian Базовые типы и методы
|
||||
*/
|
||||
//! \~\ingroup Core
|
||||
|
||||
//! \~\file pimemoryblock.h
|
||||
//! \brief
|
||||
//! \~english Memory block helper struct for data storage and binary stream operations
|
||||
//! \~russian Вспомогательная структура памяти для хранения данных и операций с двоичным потоком
|
||||
//! \details
|
||||
//! \~english The PIMemoryBlock struct provides a lightweight wrapper to store and restore custom blocks of data to/from PIBinaryStream. It
|
||||
//! holds a pointer to data and its size in bytes.
|
||||
//! \~russian Структура PIMemoryBlock предоставляет легковесный wrapper для сохранения и извлечения произвольных блоков данных в/из
|
||||
//! PIBinaryStream. Она содержит указатель на данные и их размер в байтах.
|
||||
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Base types and functions
|
||||
@@ -27,49 +33,52 @@
|
||||
#define PIMEMORYBLOCK_H
|
||||
|
||||
|
||||
//! \ingroup Core
|
||||
//! \include pimemoryblock.h
|
||||
//! \brief
|
||||
//! \~english Help struct to store/restore custom blocks of data to/from PIBinaryStream
|
||||
//! \~russian Вспомогательная структура для сохранения/извлечения произвольного блока данных в/из PIBinaryStream
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Helper struct to store and restore custom blocks of data to/from PIBinaryStream
|
||||
//! \~russian Вспомогательная структура для сохранения и извлечения произвольных блоков данных в/из PIBinaryStream
|
||||
struct PIMemoryBlock {
|
||||
public:
|
||||
//! \~english Constructs data block
|
||||
//! \~russian Создает блок данных
|
||||
//! \~english Constructs empty memory block.
|
||||
//! \~russian Создает пустой блок памяти.
|
||||
PIMemoryBlock() {}
|
||||
|
||||
//! \~english Constructs data block
|
||||
//! \~russian Создает блок данных
|
||||
//! \~english Constructs memory block from pointer and size.
|
||||
//! \~russian Создает блок памяти из указателя и размера.
|
||||
PIMemoryBlock(const void * data_, const int size_) {
|
||||
d = const_cast<void *>(data_);
|
||||
s = size_;
|
||||
}
|
||||
|
||||
//! \~english Copy constructor.
|
||||
//! \~russian Конструктор копирования.
|
||||
PIMemoryBlock(const PIMemoryBlock & o) {
|
||||
d = o.d;
|
||||
s = o.s;
|
||||
}
|
||||
|
||||
//! \~english Copy assignment operator.
|
||||
//! \~russian Оператор присваивания копированием.
|
||||
PIMemoryBlock & operator=(const PIMemoryBlock & o) {
|
||||
d = o.d;
|
||||
s = o.s;
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Pointer to data
|
||||
//! \~russian Указатель на данные
|
||||
//! \~english Returns pointer to block data.
|
||||
//! \~russian Возвращает указатель на данные блока.
|
||||
void * data() { return d; }
|
||||
|
||||
//! \~english Pointer to data
|
||||
//! \~russian Указатель на данные
|
||||
//! \~english Returns pointer to block data.
|
||||
//! \~russian Возвращает указатель на данные блока.
|
||||
const void * data() const { return d; }
|
||||
|
||||
//! \~english Size of data in bytes
|
||||
//! \~russian Размер данных в байтах
|
||||
//! \~english Returns block size in bytes.
|
||||
//! \~russian Возвращает размер блока в байтах.
|
||||
int size() const { return s; }
|
||||
|
||||
//! \~english Returns if this block points to nothing
|
||||
//! \~russian Возвращает пустой ли указатель на данные
|
||||
//! \~english Returns `true` when the block stores a non-null pointer.
|
||||
//! \~russian Возвращает `true`, когда блок хранит ненулевой указатель.
|
||||
bool isNull() const { return d; }
|
||||
|
||||
private:
|
||||
@@ -77,8 +86,10 @@ private:
|
||||
int s = 0;
|
||||
};
|
||||
|
||||
//! \~english Returns PIMemoryBlock from pointer to variable "ptr" with type "T"
|
||||
//! \~russian Возвращает PIMemoryBlock из указателя "ptr" типа "T"
|
||||
//! \~\ingroup Core
|
||||
//! \~\brief
|
||||
//! \~english Creates %PIMemoryBlock for object pointed by "ptr".
|
||||
//! \~russian Создает %PIMemoryBlock для объекта, на который указывает "ptr".
|
||||
template<typename T>
|
||||
PIMemoryBlock createMemoryBlock(const T * ptr) {
|
||||
return PIMemoryBlock(ptr, sizeof(T));
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/*! \file piobject.h
|
||||
* \ingroup Core
|
||||
* \~\brief
|
||||
* \~english Base object
|
||||
* \~russian Базовый класс
|
||||
*/
|
||||
//! \~\ingroup Core
|
||||
//! \~\file piobject.h
|
||||
//! \~\brief
|
||||
//! \~english Base object class providing event -> handler mechanism
|
||||
//! \~russian Базовый класс объектов, обеспечивающий механизм событий -> обработчиков
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Object, base class of some PIP classes, provide EVENT -> EVENT_HANDLER mechanism
|
||||
@@ -34,10 +33,26 @@
|
||||
#include "pivariant.h"
|
||||
#include "pivariantsimple.h"
|
||||
|
||||
//! \ingroup Core
|
||||
//! \~\ingroup Core
|
||||
//! \~\brief
|
||||
//! \~english This is base class for any classes which use events -> handlers mechanism.
|
||||
//! \~russian Этот класс является базовым для использования механизма события -> обработчики.
|
||||
//! \~english Base class for objects that declare events, event handlers and registered methods.
|
||||
//! \~russian Базовый класс для объектов, которые объявляют события, обработчики событий и зарегистрированные методы.
|
||||
//! \~\details
|
||||
//! \~english
|
||||
//! PIObject is the base class for all PIP classes that need event-driven communication.
|
||||
//! It provides signal-slot mechanism, property system, and object lifetime management.
|
||||
//! %PIObject stores named properties, keeps connection state and exposes a
|
||||
//! small metaobject table used by \a CONNECTU(), \a execute() and related APIs.
|
||||
//! Queued delivery runs on the performer object and requires explicit draining
|
||||
//! through \a callQueuedEvents() or \a maybeCallQueuedEvents().
|
||||
//! \~russian
|
||||
//! PIObject является базовым классом для всех классов PIP, которым необходима событийная коммуникация.
|
||||
//! Он обеспечивает механизм сигналов-слотов, систему свойств и управление жизненным циклом объектов.
|
||||
//! %PIObject хранит именованные свойства, состояние соединений и небольшую
|
||||
//! метаобъектную таблицу, которую используют \a CONNECTU(), \a execute() и
|
||||
//! связанные методы. Отложенная доставка выполняется на объекте-исполнителе и
|
||||
//! требует явного опустошения очереди через \a callQueuedEvents() или
|
||||
//! \a maybeCallQueuedEvents().
|
||||
class PIP_EXPORT PIObject {
|
||||
#ifndef MICRO_PIP
|
||||
friend class PIObjectManager;
|
||||
@@ -50,16 +65,18 @@ class PIP_EXPORT PIObject {
|
||||
public:
|
||||
NO_COPY_CLASS(PIObject);
|
||||
|
||||
//! \~english Contructs %PIObject with name "name"
|
||||
//! \~russian Создает %PIObject с именем "name"
|
||||
//! \~english Constructs an object and initializes its \c name property.
|
||||
//! \~russian Создает объект и инициализирует его свойство \c name.
|
||||
explicit PIObject(const PIString & name = PIString());
|
||||
|
||||
//! \~english Destroys the object, raises \a deleted() and disconnects it from the event graph.
|
||||
//! \~russian Уничтожает объект, вызывает \a deleted() и отключает его от событийного графа.
|
||||
virtual ~PIObject();
|
||||
|
||||
//! \ingroup Core
|
||||
//! \~\ingroup Core
|
||||
//! \~\brief
|
||||
//! \~english Helper class for obtain info about if connection successful and disconnect single connection.
|
||||
//! \~russian Вспомогательный класс для получения информации об успешности соединения и возможности его разрыва.
|
||||
//! \~english Handle of one connection between a source object and a destination object or functor.
|
||||
//! \~russian Дескриптор одного соединения между объектом-источником и объектом-приемником либо функтором.
|
||||
class PIP_EXPORT Connection {
|
||||
friend class PIObject;
|
||||
Connection(void * sl,
|
||||
@@ -93,28 +110,31 @@ public:
|
||||
int args_count;
|
||||
|
||||
public:
|
||||
//! \~english Contructs invalid %Connection
|
||||
//! \~russian Создает недействительный %Connection
|
||||
//! \~english Constructs an invalid connection handle.
|
||||
//! \~russian Создает недействительный дескриптор соединения.
|
||||
Connection();
|
||||
|
||||
//! \~english Returns if %Connection is valid
|
||||
//! \~russian Возвращает успешен ли %Connection
|
||||
//! \~english Returns \c true when the connection was created successfully.
|
||||
//! \~russian Возвращает \c true, если соединение было успешно создано.
|
||||
bool isValid() const { return signal; }
|
||||
|
||||
//! \~english Returns source object
|
||||
//! \~russian Возвращает объект-источник
|
||||
//! \~english Returns the source object that emits the event.
|
||||
//! \~russian Возвращает объект-источник, который испускает событие.
|
||||
PIObject * sourceObject() const { return src_o; }
|
||||
|
||||
//! \~english Returns destination object or "nullptr" if this is lambda connection
|
||||
//! \~russian Возвращает объект-приемник или "nullptr" если это соединение на лямбда-функцию
|
||||
//! \~english Returns the destination object, or \c nullptr for a lambda connection.
|
||||
//! \~russian Возвращает объект-приемник, либо \c nullptr для соединения с лямбда-функцией.
|
||||
PIObject * destinationObject() const { return dest_o; }
|
||||
|
||||
//! \~english Returns performer object or "nullptr" if this is non-queued connection
|
||||
//! \~russian Возвращает объект-исполнитель или "nullptr" если это соединение не отложенное
|
||||
//! \~english Returns the performer object, or \c nullptr for direct delivery.
|
||||
//! \~russian Возвращает объект-исполнитель, либо \c nullptr для прямой доставки.
|
||||
//! \~\details
|
||||
//! \~english Queued delivery runs only when the performer drains its queue.
|
||||
//! \~russian Отложенная доставка выполняется только когда исполнитель обрабатывает свою очередь.
|
||||
PIObject * performerObject() const { return performer; }
|
||||
|
||||
//! \~english Disconnect this %Connection, returns if operation successful
|
||||
//! \~russian Разрывает этот %Connection, возвращает успешен ли разрыв
|
||||
//! \~english Disconnects this single connection.
|
||||
//! \~russian Разрывает только это соединение.
|
||||
bool disconnect() const;
|
||||
};
|
||||
|
||||
@@ -122,14 +142,16 @@ private:
|
||||
uint _signature_;
|
||||
|
||||
public:
|
||||
//! \~english Returns object name
|
||||
//! \~russian Возвращает имя объекта
|
||||
//! \~english Returns the \c name property of this object.
|
||||
//! \~russian Возвращает свойство \c name этого объекта.
|
||||
PIString name() const { return property("name").toString(); }
|
||||
|
||||
//! \~english Returns object class name
|
||||
//! \~russian Возвращает имя класса объекта
|
||||
//! \~english Returns the registered class name of this object.
|
||||
//! \~russian Возвращает зарегистрированное имя класса этого объекта.
|
||||
virtual const char * className() const { return "PIObject"; }
|
||||
|
||||
//! \~english Returns the hash of \a className().
|
||||
//! \~russian Возвращает хэш от \a className().
|
||||
virtual uint classNameID() const {
|
||||
static uint ret = PIStringAscii("PIObject").hash();
|
||||
return ret;
|
||||
@@ -141,51 +163,87 @@ public:
|
||||
return ret;
|
||||
}
|
||||
|
||||
//! \~english Returns parent class name
|
||||
//! \~russian Возвращает имя родительского класса
|
||||
//! \~english Returns the registered parent class name, or an empty string for the root.
|
||||
//! \~russian Возвращает зарегистрированное имя родительского класса, либо пустую строку для корня.
|
||||
virtual const char * parentClassName() const { return ""; }
|
||||
|
||||
|
||||
//! \~english Return if \a piCoutObj of this object is active
|
||||
//! \~russian Возвращает включен ли вывод \a piCoutObj для этого объекта
|
||||
//! \~english Returns whether \a piCoutObj output is enabled for this object.
|
||||
//! \~russian Возвращает, включен ли вывод \a piCoutObj для этого объекта.
|
||||
bool debug() const { return property("debug").toBool(); }
|
||||
|
||||
|
||||
//! \~english Set object name
|
||||
//! \~russian Устанавливает имя объекта
|
||||
//! \~english Sets the \c name property of this object.
|
||||
//! \~russian Устанавливает свойство \c name этого объекта.
|
||||
void setName(const PIString & name) { setProperty("name", name); }
|
||||
|
||||
//! \~english Set object \a piCoutObj active
|
||||
//! \~russian Включает или отключает вывод \a piCoutObj для этого объекта
|
||||
//! \~english Enables or disables \a piCoutObj output for this object.
|
||||
//! \~russian Включает или отключает вывод \a piCoutObj для этого объекта.
|
||||
void setDebug(bool debug) { setProperty("debug", debug); }
|
||||
|
||||
//! \~english Returns property with name "name"
|
||||
//! \~russian Возвращает свойство объекта по имени "name"
|
||||
//! \~english Returns the property with name "name".
|
||||
//! \~russian Возвращает свойство объекта по имени "name".
|
||||
PIVariant property(const char * name) const { return properties_.value(piHashData((const uchar *)name, strlen(name))); }
|
||||
|
||||
//! \~english Set property with name "name" to "value". If there is no such property in object it will be added
|
||||
//! \~russian Устанавливает у объекта свойство по имени "name" в "value". Если такого свойства нет, оно добавляется
|
||||
//! \~english Sets the property "name" to "value" and creates it if needed.
|
||||
//! \~russian Устанавливает свойство "name" в значение "value" и создаёт его при необходимости.
|
||||
//! \~\details
|
||||
//! \~english Calls \a propertyChanged() after updating the stored value.
|
||||
//! \~russian После обновления сохранённого значения вызывает \a propertyChanged().
|
||||
void setProperty(const char * name, const PIVariant & value) {
|
||||
properties_[piHashData((const uchar *)name, strlen(name))] = value;
|
||||
propertyChanged(name);
|
||||
}
|
||||
|
||||
//! \~english Returns if property with name "name" exists
|
||||
//! \~russian Возвращает присутствует ли свойство по имени "name"
|
||||
//! \~english Returns whether the property "name" exists.
|
||||
//! \~russian Возвращает, существует ли свойство "name".
|
||||
bool isPropertyExists(const char * name) const { return properties_.contains(piHashData((const uchar *)name, strlen(name))); }
|
||||
|
||||
//! \~english Enables or disables the internal object mutex during handler execution.
|
||||
//! \~russian Включает или отключает внутренний мьютекс объекта во время выполнения обработчиков.
|
||||
//! \~\details
|
||||
//! \~english This flag affects direct and queued handler invocation for this object, but does not describe full thread-safety of the
|
||||
//! class.
|
||||
//! \~russian Этот флаг влияет на прямой и отложенный вызов обработчиков для данного объекта, но не описывает полную потокобезопасность
|
||||
//! класса.
|
||||
void setThreadSafe(bool yes) { thread_safe_ = yes; }
|
||||
//! \~english Returns whether the internal object mutex is enabled for handler execution.
|
||||
//! \~russian Возвращает, включен ли внутренний мьютекс объекта для выполнения обработчиков.
|
||||
bool isThreadSafe() const { return thread_safe_; }
|
||||
|
||||
//! \~english Executes a registered method or handler method by name with the supplied arguments.
|
||||
//! \~russian Выполняет зарегистрированный метод или метод-обработчик по имени с переданными аргументами.
|
||||
//! \~\details
|
||||
//! \~english
|
||||
//! This helper works only with the registered-method table built from
|
||||
//! \a EVENT_HANDLER*() and \a EVENT*() declarations. It does not provide
|
||||
//! arbitrary reflection or complex overload resolution: the implementation
|
||||
//! selects a suitable registered method by name and argument count.
|
||||
//! \~russian
|
||||
//! Этот вспомогательный метод работает только с таблицей зарегистрированных
|
||||
//! методов, построенной из объявлений \a EVENT_HANDLER*() и \a EVENT*().
|
||||
//! Он не предоставляет произвольную рефлексию и сложное разрешение
|
||||
//! перегрузок: реализация выбирает подходящий зарегистрированный метод по
|
||||
//! имени и числу аргументов.
|
||||
bool execute(const PIString & method, const PIVector<PIVariantSimple> & vl);
|
||||
//! \~english Overload of \a execute() for a method without arguments.
|
||||
//! \~russian Перегрузка \a execute() для метода без аргументов.
|
||||
bool execute(const PIString & method) { return execute(method, PIVector<PIVariantSimple>()); }
|
||||
//! \~english Overload of \a execute() for one argument.
|
||||
//! \~russian Перегрузка \a execute() для одного аргумента.
|
||||
bool execute(const PIString & method, const PIVariantSimple & v0) { return execute(method, PIVector<PIVariantSimple>() << v0); }
|
||||
//! \~english Overload of \a execute() for two arguments.
|
||||
//! \~russian Перегрузка \a execute() для двух аргументов.
|
||||
bool execute(const PIString & method, const PIVariantSimple & v0, const PIVariantSimple & v1) {
|
||||
return execute(method, PIVector<PIVariantSimple>() << v0 << v1);
|
||||
}
|
||||
//! \~english Overload of \a execute() for three arguments.
|
||||
//! \~russian Перегрузка \a execute() для трёх аргументов.
|
||||
bool execute(const PIString & method, const PIVariantSimple & v0, const PIVariantSimple & v1, const PIVariantSimple & v2) {
|
||||
return execute(method, PIVector<PIVariantSimple>() << v0 << v1 << v2);
|
||||
}
|
||||
//! \~english Overload of \a execute() for four arguments.
|
||||
//! \~russian Перегрузка \a execute() для четырёх аргументов.
|
||||
bool execute(const PIString & method,
|
||||
const PIVariantSimple & v0,
|
||||
const PIVariantSimple & v1,
|
||||
@@ -194,16 +252,36 @@ public:
|
||||
return execute(method, PIVector<PIVariantSimple>() << v0 << v1 << v2 << v3);
|
||||
}
|
||||
|
||||
//! \~english Queues execution of a registered method on the performer object.
|
||||
//! \~russian Ставит выполнение зарегистрированного метода в очередь объекта-исполнителя.
|
||||
//! \~\details
|
||||
//! \~english
|
||||
//! Delivery happens only when "performer" later calls \a callQueuedEvents()
|
||||
//! or \a maybeCallQueuedEvents(). Argument values are transported through
|
||||
//! \a PIVariantSimple, so queued arguments should be representable there.
|
||||
//! \~russian
|
||||
//! Доставка происходит только когда "performer" позже вызывает
|
||||
//! \a callQueuedEvents() или \a maybeCallQueuedEvents(). Значения аргументов
|
||||
//! передаются через \a PIVariantSimple, поэтому аргументы очереди должны в
|
||||
//! нём представляться.
|
||||
bool executeQueued(PIObject * performer, const PIString & method, const PIVector<PIVariantSimple> & vl);
|
||||
//! \~english Overload of \a executeQueued() for a method without arguments.
|
||||
//! \~russian Перегрузка \a executeQueued() для метода без аргументов.
|
||||
bool executeQueued(PIObject * performer, const PIString & method) {
|
||||
return executeQueued(performer, method, PIVector<PIVariantSimple>());
|
||||
}
|
||||
//! \~english Overload of \a executeQueued() for one argument.
|
||||
//! \~russian Перегрузка \a executeQueued() для одного аргумента.
|
||||
bool executeQueued(PIObject * performer, const PIString & method, const PIVariantSimple & v0) {
|
||||
return executeQueued(performer, method, PIVector<PIVariantSimple>() << v0);
|
||||
}
|
||||
//! \~english Overload of \a executeQueued() for two arguments.
|
||||
//! \~russian Перегрузка \a executeQueued() для двух аргументов.
|
||||
bool executeQueued(PIObject * performer, const PIString & method, const PIVariantSimple & v0, const PIVariantSimple & v1) {
|
||||
return executeQueued(performer, method, PIVector<PIVariantSimple>() << v0 << v1);
|
||||
}
|
||||
//! \~english Overload of \a executeQueued() for three arguments.
|
||||
//! \~russian Перегрузка \a executeQueued() для трёх аргументов.
|
||||
bool executeQueued(PIObject * performer,
|
||||
const PIString & method,
|
||||
const PIVariantSimple & v0,
|
||||
@@ -211,6 +289,8 @@ public:
|
||||
const PIVariantSimple & v2) {
|
||||
return executeQueued(performer, method, PIVector<PIVariantSimple>() << v0 << v1 << v2);
|
||||
}
|
||||
//! \~english Overload of \a executeQueued() for four arguments.
|
||||
//! \~russian Перегрузка \a executeQueued() для четырёх аргументов.
|
||||
bool executeQueued(PIObject * performer,
|
||||
const PIString & method,
|
||||
const PIVariantSimple & v0,
|
||||
@@ -220,18 +300,30 @@ public:
|
||||
return executeQueued(performer, method, PIVector<PIVariantSimple>() << v0 << v1 << v2 << v3);
|
||||
}
|
||||
|
||||
//! \~english Static convenience wrapper for \a execute().
|
||||
//! \~russian Статическая удобная обёртка над \a execute().
|
||||
static bool execute(PIObject * o, const PIString & method, const PIVector<PIVariantSimple> & vl) { return o->execute(method, vl); }
|
||||
//! \~english Static overload of \a execute() without arguments.
|
||||
//! \~russian Статическая перегрузка \a execute() без аргументов.
|
||||
static bool execute(PIObject * o, const PIString & method) { return execute(o, method, PIVector<PIVariantSimple>()); }
|
||||
//! \~english Static overload of \a execute() for one argument.
|
||||
//! \~russian Статическая перегрузка \a execute() для одного аргумента.
|
||||
static bool execute(PIObject * o, const PIString & method, const PIVariantSimple & v0) {
|
||||
return execute(o, method, PIVector<PIVariantSimple>() << v0);
|
||||
}
|
||||
//! \~english Static overload of \a execute() for two arguments.
|
||||
//! \~russian Статическая перегрузка \a execute() для двух аргументов.
|
||||
static bool execute(PIObject * o, const PIString & method, const PIVariantSimple & v0, const PIVariantSimple & v1) {
|
||||
return execute(o, method, PIVector<PIVariantSimple>() << v0 << v1);
|
||||
}
|
||||
//! \~english Static overload of \a execute() for three arguments.
|
||||
//! \~russian Статическая перегрузка \a execute() для трёх аргументов.
|
||||
static bool
|
||||
execute(PIObject * o, const PIString & method, const PIVariantSimple & v0, const PIVariantSimple & v1, const PIVariantSimple & v2) {
|
||||
return execute(o, method, PIVector<PIVariantSimple>() << v0 << v1 << v2);
|
||||
}
|
||||
//! \~english Static overload of \a execute() for four arguments.
|
||||
//! \~russian Статическая перегрузка \a execute() для четырёх аргументов.
|
||||
static bool execute(PIObject * o,
|
||||
const PIString & method,
|
||||
const PIVariantSimple & v0,
|
||||
@@ -241,19 +333,29 @@ public:
|
||||
return execute(o, method, PIVector<PIVariantSimple>() << v0 << v1 << v2 << v3);
|
||||
}
|
||||
|
||||
//! \~english Static convenience wrapper for \a executeQueued().
|
||||
//! \~russian Статическая удобная обёртка над \a executeQueued().
|
||||
static bool executeQueued(PIObject * o, PIObject * performer, const PIString & method, const PIVector<PIVariantSimple> & vl) {
|
||||
return o->executeQueued(performer, method, vl);
|
||||
}
|
||||
//! \~english Static overload of \a executeQueued() without arguments.
|
||||
//! \~russian Статическая перегрузка \a executeQueued() без аргументов.
|
||||
static bool executeQueued(PIObject * o, PIObject * performer, const PIString & method) {
|
||||
return executeQueued(o, performer, method, PIVector<PIVariantSimple>());
|
||||
}
|
||||
//! \~english Static overload of \a executeQueued() for one argument.
|
||||
//! \~russian Статическая перегрузка \a executeQueued() для одного аргумента.
|
||||
static bool executeQueued(PIObject * o, PIObject * performer, const PIString & method, const PIVariantSimple & v0) {
|
||||
return executeQueued(o, performer, method, PIVector<PIVariantSimple>() << v0);
|
||||
}
|
||||
//! \~english Static overload of \a executeQueued() for two arguments.
|
||||
//! \~russian Статическая перегрузка \a executeQueued() для двух аргументов.
|
||||
static bool
|
||||
executeQueued(PIObject * o, PIObject * performer, const PIString & method, const PIVariantSimple & v0, const PIVariantSimple & v1) {
|
||||
return executeQueued(o, performer, method, PIVector<PIVariantSimple>() << v0 << v1);
|
||||
}
|
||||
//! \~english Static overload of \a executeQueued() for three arguments.
|
||||
//! \~russian Статическая перегрузка \a executeQueued() для трёх аргументов.
|
||||
static bool executeQueued(PIObject * o,
|
||||
PIObject * performer,
|
||||
const PIString & method,
|
||||
@@ -262,6 +364,8 @@ public:
|
||||
const PIVariantSimple & v2) {
|
||||
return executeQueued(o, performer, method, PIVector<PIVariantSimple>() << v0 << v1 << v2);
|
||||
}
|
||||
//! \~english Static overload of \a executeQueued() for four arguments.
|
||||
//! \~russian Статическая перегрузка \a executeQueued() для четырёх аргументов.
|
||||
static bool executeQueued(PIObject * o,
|
||||
PIObject * performer,
|
||||
const PIString & method,
|
||||
@@ -272,22 +376,37 @@ public:
|
||||
return executeQueued(o, performer, method, PIVector<PIVariantSimple>() << v0 << v1 << v2 << v3);
|
||||
}
|
||||
|
||||
//! \~english Dumps object diagnostics to the project output stream.
|
||||
//! \~russian Выводит диагностическую информацию об объекте в проектный поток вывода.
|
||||
void dump(const PIString & line_prefix = PIString()) const;
|
||||
|
||||
|
||||
//! \~english Returns subclass scope of this object (including this class name)
|
||||
//! \~russian Возвращает цепочку наследования объекта (вместе с классом самого объекта)
|
||||
//! \~english Returns the registered inheritance scope of this object, including its own class.
|
||||
//! \~russian Возвращает зарегистрированную цепочку наследования объекта, включая его собственный класс.
|
||||
PIStringList scopeList() const;
|
||||
|
||||
//! \~english Returns full signatures of all registered event and handler methods for this class scope.
|
||||
//! \~russian Возвращает полные сигнатуры всех зарегистрированных событий и обработчиков для области этого класса.
|
||||
PIStringList methodsEH() const;
|
||||
//! \~english Returns whether a registered event or handler method with this name exists.
|
||||
//! \~russian Возвращает, существует ли зарегистрированное событие или обработчик с таким именем.
|
||||
bool isMethodEHContains(const PIString & name) const;
|
||||
//! \~english Returns the comma-separated argument type list of a registered method.
|
||||
//! \~russian Возвращает список типов аргументов зарегистрированного метода через запятую.
|
||||
PIString methodEHArguments(const PIString & name) const;
|
||||
//! \~english Returns the full registered signature of a method.
|
||||
//! \~russian Возвращает полную зарегистрированную сигнатуру метода.
|
||||
PIString methodEHFullFormat(const PIString & name) const;
|
||||
//! \~english Returns the registered method name for the specified entry-point address.
|
||||
//! \~russian Возвращает имя зарегистрированного метода для указанного адреса точки входа.
|
||||
PIString methodEHFromAddr(const void * addr) const;
|
||||
|
||||
// / Direct connect
|
||||
//! \~english Low-level direct connection helper behind the legacy \c CONNECT* macros.
|
||||
//! \~russian Низкоуровневый помощник прямого соединения, лежащий под устаревшими макросами \c CONNECT*.
|
||||
static PIObject::Connection
|
||||
piConnect(PIObject * src, const PIString & sig, PIObject * dest_o, void * dest, void * ev_h, void * e_h, int args, const char * loc);
|
||||
//! \~english Low-level name-based connection helper behind \a CONNECTU() and \a CONNECTU_QUEUED().
|
||||
//! \~russian Низкоуровневый помощник соединения по имени, лежащий под \a CONNECTU() и \a CONNECTU_QUEUED().
|
||||
static PIObject::Connection piConnectU(PIObject * src,
|
||||
const PIString & sig,
|
||||
PIObject * dest_o,
|
||||
@@ -295,6 +414,8 @@ public:
|
||||
const PIString & hname,
|
||||
const char * loc,
|
||||
PIObject * performer = 0);
|
||||
//! \~english Low-level helper that connects an event to a lambda or functor wrapper.
|
||||
//! \~russian Низкоуровневый помощник, который соединяет событие с лямбдой или обёрткой функтора.
|
||||
static PIObject::Connection piConnectLS(PIObject * src, const PIString & sig, std::function<void()> * f, const char * loc);
|
||||
template<typename PIINPUT, typename... PITYPES>
|
||||
static std::function<void()> * __newFunctor(void (*stat_handler)(void *, PITYPES...), PIINPUT functor) {
|
||||
@@ -302,33 +423,33 @@ public:
|
||||
}
|
||||
|
||||
|
||||
//! \~english Disconnect object from all connections with event name "sig", connected to destination object "dest" and handler "ev_h"
|
||||
//! \~russian Разрывает все соединения от события "sig" к объекту "dest" и обработчику "ev_h"
|
||||
//! \~english Disconnects this source object from a specific destination handler for event "sig".
|
||||
//! \~russian Разрывает соединения этого объекта-источника с конкретным обработчиком объекта-приемника для события "sig".
|
||||
void piDisconnect(const PIString & sig, PIObject * dest, void * ev_h) { piDisconnect(this, sig, dest, ev_h); }
|
||||
|
||||
//! \~english Disconnect object from all connections with event name "sig", connected to destination object "dest"
|
||||
//! \~russian Разрывает все соединения от события "sig" к объекту "dest"
|
||||
//! \~english Disconnects this source object from all connections of event "sig" to destination object "dest".
|
||||
//! \~russian Разрывает все соединения этого объекта-источника от события "sig" к объекту-приемнику "dest".
|
||||
void piDisconnect(const PIString & sig, PIObject * dest) { piDisconnect(this, sig, dest); }
|
||||
|
||||
//! \~english Disconnect object from all connections with event name "sig"
|
||||
//! \~russian Разрывает все соединения от события "sig"
|
||||
//! \~english Disconnects this source object from all connections of event "sig".
|
||||
//! \~russian Разрывает все соединения этого объекта-источника от события "sig".
|
||||
void piDisconnect(const PIString & sig) { piDisconnect(this, sig); }
|
||||
|
||||
|
||||
//! \~english Disconnect object "src" from all connections with event name "sig", connected to destination object "dest" and handler
|
||||
//! "ev_h"
|
||||
//! \~russian Разрывает все соединения от события "sig" объекта "src" к объекту "dest" и обработчику "ev_h"
|
||||
//! \~english Disconnects source object "src" from a specific destination handler for event "sig".
|
||||
//! \~russian Разрывает соединения объекта-источника "src" с конкретным обработчиком объекта-приемника для события "sig".
|
||||
static void piDisconnect(PIObject * src, const PIString & sig, PIObject * dest, void * ev_h);
|
||||
|
||||
//! \~english Disconnect object "src" from all connections with event name "sig", connected to destination object "dest"
|
||||
//! \~russian Разрывает все соединения от события "sig" объекта "src" к объекту "dest"
|
||||
//! \~english Disconnects source object "src" from all connections of event "sig" to destination object "dest".
|
||||
//! \~russian Разрывает все соединения объекта-источника "src" от события "sig" к объекту-приемнику "dest".
|
||||
static void piDisconnect(PIObject * src, const PIString & sig, PIObject * dest);
|
||||
|
||||
//! \~english Disconnect object "src" from all connections with event name "sig"
|
||||
//! \~russian Разрывает все соединения от события "sig" объекта "src"
|
||||
//! \~english Disconnects source object "src" from all connections of event "sig".
|
||||
//! \~russian Разрывает все соединения объекта-источника "src" от события "sig".
|
||||
static void piDisconnect(PIObject * src, const PIString & sig);
|
||||
|
||||
// / Raise events
|
||||
//! \~english Internal event delivery helper for registered events without arguments.
|
||||
//! \~russian Внутренний помощник доставки для зарегистрированных событий без аргументов.
|
||||
static void raiseEvent(PIObject * sender, const uint eventID) {
|
||||
for (int j = 0; j < sender->connections.size_s(); ++j) {
|
||||
Connection i(sender->connections[j]);
|
||||
@@ -357,6 +478,8 @@ public:
|
||||
}
|
||||
}
|
||||
|
||||
//! \~english Internal event delivery helper for registered events with one argument.
|
||||
//! \~russian Внутренний помощник доставки для зарегистрированных событий с одним аргументом.
|
||||
template<typename T0>
|
||||
static void raiseEvent(PIObject * sender, const uint eventID, const T0 & v0 = T0()) {
|
||||
for (int j = 0; j < sender->connections.size_s(); ++j) {
|
||||
@@ -390,6 +513,8 @@ public:
|
||||
if (!sender->isPIObject()) break;
|
||||
}
|
||||
}
|
||||
//! \~english Internal event delivery helper for registered events with two arguments.
|
||||
//! \~russian Внутренний помощник доставки для зарегистрированных событий с двумя аргументами.
|
||||
template<typename T0, typename T1>
|
||||
static void raiseEvent(PIObject * sender, const uint eventID, const T0 & v0 = T0(), const T1 & v1 = T1()) {
|
||||
for (int j = 0; j < sender->connections.size_s(); ++j) {
|
||||
@@ -425,6 +550,8 @@ public:
|
||||
if (!sender->isPIObject()) break;
|
||||
}
|
||||
}
|
||||
//! \~english Internal event delivery helper for registered events with three arguments.
|
||||
//! \~russian Внутренний помощник доставки для зарегистрированных событий с тремя аргументами.
|
||||
template<typename T0, typename T1, typename T2>
|
||||
static void raiseEvent(PIObject * sender, const uint eventID, const T0 & v0 = T0(), const T1 & v1 = T1(), const T2 & v2 = T2()) {
|
||||
for (int j = 0; j < sender->connections.size_s(); ++j) {
|
||||
@@ -462,6 +589,8 @@ public:
|
||||
if (!sender->isPIObject()) break;
|
||||
}
|
||||
}
|
||||
//! \~english Internal event delivery helper for registered events with four arguments.
|
||||
//! \~russian Внутренний помощник доставки для зарегистрированных событий с четырьмя аргументами.
|
||||
template<typename T0, typename T1, typename T2, typename T3>
|
||||
static void raiseEvent(PIObject * sender,
|
||||
const uint eventID,
|
||||
@@ -507,7 +636,8 @@ public:
|
||||
}
|
||||
}
|
||||
|
||||
//! Returns PIObject* with name "name" or 0, if there is no object found
|
||||
//! \~english Returns the first live object with name "name", or \c nullptr.
|
||||
//! \~russian Возвращает первый живой объект с именем "name", либо \c nullptr.
|
||||
static PIObject * findByName(const PIString & name) {
|
||||
PIMutexLocker _ml(mutexObjects());
|
||||
for (auto * i: PIObject::objects()) {
|
||||
@@ -517,12 +647,12 @@ public:
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
//! \~english Returns if this is valid %PIObject (check signature)
|
||||
//! \~russian Возвращает действительный ли это %PIObject (проверяет подпись)
|
||||
//! \~english Returns whether this pointer still refers to a live %PIObject instance.
|
||||
//! \~russian Возвращает, указывает ли этот указатель на ещё существующий экземпляр %PIObject.
|
||||
bool isPIObject() const { return isPIObject(this); }
|
||||
|
||||
//! \~english Returns if this is valid %PIObject subclass "T" (check signature and classname)
|
||||
//! \~russian Возвращает действительный ли это наследник %PIObject типа "T" (проверяет подпись и имя класса)
|
||||
//! \~english Returns whether this object belongs to class "T" or one of its registered descendants.
|
||||
//! \~russian Возвращает, принадлежит ли этот объект классу "T" или одному из его зарегистрированных потомков.
|
||||
template<typename T>
|
||||
bool isTypeOf() const {
|
||||
if (!isPIObject()) return false;
|
||||
@@ -530,30 +660,35 @@ public:
|
||||
return __meta_data()[classNameID()].scope_id.contains(T::__classNameIDS());
|
||||
}
|
||||
|
||||
//! \~english Returns cast to T if this is valid subclass "T" (check by \a isTypeOf()) or "nullptr"
|
||||
//! \~russian Возвращает преобразование к типу T если это действительный наследник типа "T" (проверяет через \a isTypeOf()), или
|
||||
//! "nullptr"
|
||||
//! \~english Returns this object cast to "T" when \a isTypeOf<T>() succeeds, otherwise \c nullptr.
|
||||
//! \~russian Возвращает этот объект, приведённый к типу "T", если \a isTypeOf<T>() успешно, иначе \c nullptr.
|
||||
template<typename T>
|
||||
T * cast() const {
|
||||
if (!isTypeOf<T>()) return (T *)nullptr;
|
||||
return (T *)this;
|
||||
}
|
||||
|
||||
//! \~english Returns if "o" is valid %PIObject (check signature)
|
||||
//! \~russian Возвращает действительный ли "o" %PIObject (проверяет подпись)
|
||||
//! \~english Returns whether "o" points to a live %PIObject instance.
|
||||
//! \~russian Возвращает, указывает ли "o" на ещё существующий экземпляр %PIObject.
|
||||
static bool isPIObject(const PIObject * o);
|
||||
//! \~english Overload of \a isPIObject() for an untyped pointer.
|
||||
//! \~russian Перегрузка \a isPIObject() для нетипизированного указателя.
|
||||
static bool isPIObject(const void * o) { return isPIObject((PIObject *)o); }
|
||||
|
||||
//! \~english Returns if "o" is valid %PIObject subclass "T" (check signature and classname)
|
||||
//! \~russian Возвращает действительный ли "o" наследник %PIObject типа "T" (проверяет подпись и имя класса)
|
||||
//! \~english Returns whether "o" belongs to class "T" or one of its registered descendants.
|
||||
//! \~russian Возвращает, принадлежит ли "o" классу "T" или одному из его зарегистрированных потомков.
|
||||
template<typename T>
|
||||
static bool isTypeOf(const PIObject * o) {
|
||||
return o->isTypeOf<T>();
|
||||
}
|
||||
//! \~english Overload of \a isTypeOf() for an untyped pointer.
|
||||
//! \~russian Перегрузка \a isTypeOf() для нетипизированного указателя.
|
||||
template<typename T>
|
||||
static bool isTypeOf(const void * o) {
|
||||
return isTypeOf<T>((PIObject *)o);
|
||||
}
|
||||
//! \~english Simplifies a C++ type spelling for registered-method metadata.
|
||||
//! \~russian Упрощает запись типа C++ для метаданных зарегистрированных методов.
|
||||
static PIString simplifyType(const char * a, bool readable = true);
|
||||
|
||||
struct PIP_EXPORT __MetaFunc {
|
||||
@@ -589,36 +724,32 @@ public:
|
||||
};
|
||||
typedef PIPair<const void *, __MetaFunc> __EHPair;
|
||||
|
||||
//! \~english Execute all posted events from CONNECTU_QUEUED connections
|
||||
//! \~russian Выполнить все отложенные события от CONNECTU_QUEUED соединений
|
||||
//! \~english Executes all queued deliveries posted to this performer object.
|
||||
//! \~russian Выполняет все отложенные доставки, поставленные в очередь этому объекту-исполнителю.
|
||||
void callQueuedEvents();
|
||||
|
||||
//! \~english
|
||||
//! \brief Check if any CONNECTU_QUEUED connections to this object and execute them
|
||||
//! \details This function is more optimized than \a callQueuedEvents() for objects that doesn`t
|
||||
//! appears as \"performer\" target at CONNECTU_QUEUED
|
||||
//! \~russian
|
||||
//! \brief Если было хотя бы одно CONNECTU_QUEUED соединение с исполнителем this, то выполнить события
|
||||
//! \details Этот метод более оптимален, чем \a callQueuedEvents(), для объектов, которые не были в роли
|
||||
//! \"performer\" в макросе CONNECTU_QUEUED
|
||||
//! \~\brief
|
||||
//! \~english Executes queued deliveries only when this object was used as a performer.
|
||||
//! \~russian Выполняет отложенные доставки только если этот объект использовался как исполнитель.
|
||||
//! \~\details
|
||||
//! \~english This helper is cheaper than unconditional \a callQueuedEvents() for objects that are rarely used as performer targets.
|
||||
//! \~russian Этот помощник дешевле, чем безусловный \a callQueuedEvents(), для объектов, которые редко используются как исполнители.
|
||||
bool maybeCallQueuedEvents() {
|
||||
if (proc_event_queue) callQueuedEvents();
|
||||
return proc_event_queue;
|
||||
}
|
||||
|
||||
//! \~english Mark object to delete
|
||||
//! \~russian Пометить объект на удаление
|
||||
//! \~english Schedules the object for deferred deletion.
|
||||
//! \~russian Планирует отложенное удаление объекта.
|
||||
void deleteLater();
|
||||
|
||||
EVENT1(deleted, PIObject *, o);
|
||||
|
||||
//! \events
|
||||
//! \{
|
||||
|
||||
//! \fn void deleted(PIObject * o)
|
||||
//! \brief
|
||||
//! \~english Raise before object delete
|
||||
//! \~russian Вызывается перед удалением объекта
|
||||
//! \~english Raised immediately before object destruction.
|
||||
//! \~russian Вызывается непосредственно перед уничтожением объекта.
|
||||
//! \~\warning
|
||||
//! \~english
|
||||
//! This event raised from destructor, so use only "o" numeric value,
|
||||
@@ -626,19 +757,23 @@ public:
|
||||
//! \~russian
|
||||
//! Это событие вызывается из деструктора, поэтому используйте
|
||||
//! только численное значение "o", не надо кастовать его в другие типы!
|
||||
EVENT1(deleted, PIObject *, o);
|
||||
|
||||
//! \}
|
||||
|
||||
static PIMutex & __meta_mutex();
|
||||
static PIMap<uint, __MetaData> & __meta_data(); // [hash(classname)]=__MetaData
|
||||
static PIMap<uint, __MetaData> & __meta_data();
|
||||
|
||||
protected:
|
||||
//! \~english Returns %PIObject* which has raised an event. This value is correct only in definition of some event handler
|
||||
//! \~russian Возвращает %PIObject* который вызвал это событие. Значение допустимо только из методов обработчиков событий
|
||||
//! \~english Returns the source object that raised the current event.
|
||||
//! \~russian Возвращает объект-источник, который вызвал текущее событие.
|
||||
//! \~\details
|
||||
//! \~english This value is valid only while an event handler is running.
|
||||
//! \~russian Это значение корректно только пока выполняется обработчик события.
|
||||
PIObject * emitter() const { return emitter_; }
|
||||
|
||||
//! \~english Virtual function executes after property with name "name" has been changed
|
||||
//! \~russian Виртуальная функция, вызывается после изменения любого свойства.
|
||||
//! \~english Virtual method called after property "name" has been changed by \a setProperty().
|
||||
//! \~russian Виртуальный метод, вызываемый после изменения свойства "name" через \a setProperty().
|
||||
virtual void propertyChanged(const char * name) {}
|
||||
|
||||
private:
|
||||
@@ -702,8 +837,15 @@ private:
|
||||
};
|
||||
|
||||
#ifndef MICRO_PIP
|
||||
|
||||
//! \~english Dumps application-level %PIObject diagnostics.
|
||||
//! \~russian Выводит диагностическую информацию уровня приложения для %PIObject.
|
||||
PIP_EXPORT void dumpApplication(bool with_objects = true);
|
||||
|
||||
//! \~english Dumps application-level %PIObject diagnostics to file "path".
|
||||
//! \~russian Выводит диагностическую информацию уровня приложения для %PIObject в файл "path".
|
||||
PIP_EXPORT bool dumpApplicationToFile(const PIString & path, bool with_objects = true);
|
||||
|
||||
#endif
|
||||
|
||||
#endif // PIOBJECT_H
|
||||
|
||||
@@ -1,9 +1,17 @@
|
||||
/*! \file piobject_macros.h
|
||||
* \ingroup Core
|
||||
* \~\brief
|
||||
* \~english PIObject macros
|
||||
* \~russian Макросы PIObject
|
||||
*/
|
||||
//! \~\ingroup Core
|
||||
//! \~\file piobject_macros.h
|
||||
//! \~\brief
|
||||
//! \~english PIObject macros for event system and object introspection
|
||||
//! \~russian Макросы PIObject для событийной системы и интроспекции объектов
|
||||
//! \~\details
|
||||
//! \~english
|
||||
//! This file declares the macro layer used by %PIObject-based classes:
|
||||
//! class registration, event declaration, event handler declaration,
|
||||
//! connection helpers and event raising helpers.
|
||||
//! \~russian
|
||||
//! Этот файл объявляет макросный слой для классов на базе %PIObject:
|
||||
//! регистрацию класса, объявление событий, объявление обработчиков,
|
||||
//! макросы соединения и макросы вызова событий.
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Macros for PIObject
|
||||
@@ -32,47 +40,47 @@
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english You should use this macro after class declaration to use EVENT and EVENT_HANDLER and correct piCoutObj output
|
||||
//! \~russian Необходимо использовать этот макрос после объявления класса для использования событийной системы и корректного вывода
|
||||
//! piCoutObj
|
||||
//! \~english Put this macro inside a direct %PIObject subclass definition to enable registered events, event handlers and class metadata.
|
||||
//! \~russian Поместите этот макрос внутрь объявления прямого наследника %PIObject, чтобы включить регистрацию событий, обработчиков и
|
||||
//! метаданных класса.
|
||||
# define PIOBJECT(name)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english You should use this macro after class declaration to use EVENT and EVENT_HANDLER of parent class, and \a scopeList()
|
||||
//! \~russian
|
||||
//! \~english Put this macro inside a %PIObject subclass definition to inherit registered methods and class scope from "parent".
|
||||
//! \~russian Поместите этот макрос внутрь объявления наследника %PIObject, чтобы унаследовать зарегистрированные методы и цепочку
|
||||
//! классов от "parent".
|
||||
# define PIOBJECT_SUBCLASS(name, parent)
|
||||
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english Declare event handler with name \"name\" and return type \"ret\", ret name()
|
||||
//! \~russian Объявляет обработчик событий с именем \"name\" и возвращаемым типом \"ret\", ret name()
|
||||
//! \~english Declare a registered event handler method with signature `ret name()`.
|
||||
//! \~russian Объявляет зарегистрированный метод-обработчик событий с сигнатурой `ret name()`.
|
||||
# define EVENT_HANDLER0(ret, name) ret name()
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english Declare event handler with name \"name\" and return type \"ret\", ret name(type0 var0)
|
||||
//! \~russian Объявляет обработчик событий с именем \"name\" и возвращаемым типом \"ret\", ret name(type0 var0)
|
||||
//! \~english Declare a registered event handler method with one argument.
|
||||
//! \~russian Объявляет зарегистрированный метод-обработчик событий с одним аргументом.
|
||||
# define EVENT_HANDLER1(ret, name, type0, var0) ret name(type0 var0)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english Declare event handler with name \"name\" and return type \"ret\", ret name(type0 var0, type1 var1)
|
||||
//! \~russian Объявляет обработчик событий с именем \"name\" и возвращаемым типом \"ret\", ret name(type0 var0, type1 var1)
|
||||
//! \~english Declare a registered event handler method with two arguments.
|
||||
//! \~russian Объявляет зарегистрированный метод-обработчик событий с двумя аргументами.
|
||||
# define EVENT_HANDLER2(ret, name, type0, var0, type1, var1) ret name(type0 var0, type1 var1)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english Declare event handler with name \"name\" and return type \"ret\", ret name(type0 var0, type1 var1, type2 var2)
|
||||
//! \~russian Объявляет обработчик событий с именем \"name\" и возвращаемым типом \"ret\", ret name(type0 var0, type1 var1, type2 var2)
|
||||
//! \~english Declare a registered event handler method with three arguments.
|
||||
//! \~russian Объявляет зарегистрированный метод-обработчик событий с тремя аргументами.
|
||||
# define EVENT_HANDLER3(ret, name, type0, var0, type1, var1, type2, var2) ret name(type0 var0, type1 var1, type2 var2)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english Declare event handler with name \"name\" and return type \"ret\", ret name(type0 var0, type1 var1, type2 var2, type3 var3)
|
||||
//! \~russian Объявляет обработчик событий с именем \"name\" и возвращаемым типом \"ret\", ret name(type0 var0, type1 var1, type2 var2,
|
||||
//! type3 var3)
|
||||
//! \~english Declare a registered event handler method with four arguments.
|
||||
//! \~russian Объявляет зарегистрированный метод-обработчик событий с четырьмя аргументами.
|
||||
# define EVENT_HANDLER4(ret, name, type0, var0, type1, var1, type2, var2, type3, var3) \
|
||||
ret name(type0 var0, type1 var1, type2 var2, type3 var3)
|
||||
|
||||
@@ -85,36 +93,32 @@
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english Declare virtual event handler with name \"name\" and return type \"ret\", virtual ret name()
|
||||
//! \~russian Объявляет виртуальный обработчик событий с именем \"name\" и возвращаемым типом \"ret\", virtual ret name()
|
||||
//! \~english Declare a virtual registered event handler method with signature `virtual ret name()`.
|
||||
//! \~russian Объявляет виртуальный зарегистрированный метод-обработчик с сигнатурой `virtual ret name()`.
|
||||
# define EVENT_VHANDLER0(ret, name) virtual ret name()
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english Declare virtual event handler with name \"name\" and return type \"ret\", virtual ret name(type0 var0)
|
||||
//! \~russian Объявляет виртуальный обработчик событий с именем \"name\" и возвращаемым типом \"ret\", virtual ret name(type0 var0)
|
||||
//! \~english Declare a virtual registered event handler method with one argument.
|
||||
//! \~russian Объявляет виртуальный зарегистрированный метод-обработчик с одним аргументом.
|
||||
# define EVENT_VHANDLER1(ret, name, type0, var0) virtual ret name(type0 var0)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english Declare virtual event handler with name \"name\" and return type \"ret\", virtual ret name(type0 var0, type1 var1)
|
||||
//! \~russian Объявляет виртуальный обработчик событий с именем \"name\" и возвращаемым типом \"ret\", virtual ret name(type0 var0, type1
|
||||
//! var1)
|
||||
//! \~english Declare a virtual registered event handler method with two arguments.
|
||||
//! \~russian Объявляет виртуальный зарегистрированный метод-обработчик с двумя аргументами.
|
||||
# define EVENT_VHANDLER2(ret, name, type0, var0, type1, var1) virtual ret name(type0 var0, type1 var1)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english Declare virtual event handler with name \"name\" and return type \"ret\", virtual ret name(type0 var0, type1 var1, type2 var2)
|
||||
//! \~russian Объявляет виртуальный обработчик событий с именем \"name\" и возвращаемым типом \"ret\", virtual ret name(type0 var0, type1
|
||||
//! var1, type2 var2)
|
||||
//! \~english Declare a virtual registered event handler method with three arguments.
|
||||
//! \~russian Объявляет виртуальный зарегистрированный метод-обработчик с тремя аргументами.
|
||||
# define EVENT_VHANDLER3(ret, name, type0, var0, type1, var1, type2, var2) virtual ret name(type0 var0, type1 var1, type2 var2)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english Declare virtual event handler with name \"name\" and return type \"ret\", virtual ret name(type0 var0, type1 var1, type2 var2,
|
||||
//! type3 var3)
|
||||
//! \~russian Объявляет виртуальный обработчик событий с именем \"name\" и возвращаемым типом \"ret\", virtual ret name(type0 var0, type1
|
||||
//! var1, type2 var2, type3 var3)
|
||||
//! \~english Declare a virtual registered event handler method with four arguments.
|
||||
//! \~russian Объявляет виртуальный зарегистрированный метод-обработчик с четырьмя аргументами.
|
||||
# define EVENT_VHANDLER4(ret, name, type0, var0, type1, var1, type2, var2, type3, var3) \
|
||||
virtual ret name(type0 var0, type1 var1, type2 var2, type3 var3)
|
||||
|
||||
@@ -127,32 +131,32 @@
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english Declare event with name \"name\", void name();
|
||||
//! \~russian Объявляет событие с именем \"name\", void name();
|
||||
//! \~english Declare an event method with no arguments.
|
||||
//! \~russian Объявляет метод-событие без аргументов.
|
||||
# define EVENT0(name) void name();
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english Declare event with name \"name\", void name(type0 var0);
|
||||
//! \~russian Объявляет событие с именем \"name\", void name(type0 var0);
|
||||
//! \~english Declare an event method with one argument.
|
||||
//! \~russian Объявляет метод-событие с одним аргументом.
|
||||
# define EVENT1(name, type0, var0) void name(type0 var0);
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english Declare event with name \"name\", void name(type0 var0, type1 var1);
|
||||
//! \~russian Объявляет событие с именем \"name\", void name(type0 var0, type1 var1);
|
||||
//! \~english Declare an event method with two arguments.
|
||||
//! \~russian Объявляет метод-событие с двумя аргументами.
|
||||
# define EVENT2(name, type0, var0, type1, var1) void name(type0 var0, type1 var1);
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english Declare event with name \"name\", void name(type0 var0, type1 var1, type2 var2);
|
||||
//! \~russian Объявляет событие с именем \"name\", void name(type0 var0, type1 var1, type2 var2);
|
||||
//! \~english Declare an event method with three arguments.
|
||||
//! \~russian Объявляет метод-событие с тремя аргументами.
|
||||
# define EVENT3(name, type0, var0, type1, var1, type2, var2) void name(type0 var0, type1 var1, type2 var2);
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english Declare event with name \"name\", void name(type0 var0, type1 var1, type2 var2, type3 var3);
|
||||
//! \~russian Объявляет событие с именем \"name\", void name(type0 var0, type1 var1, type2 var2, type3 var3);
|
||||
//! \~english Declare an event method with four arguments.
|
||||
//! \~russian Объявляет метод-событие с четырьмя аргументами.
|
||||
# define EVENT4(name, type0, var0, type1, var1, type2, var2, type3, var3) void name(type0 var0, type1 var1, type2 var2, type3 var3);
|
||||
|
||||
//! \relatesalso PIObject
|
||||
@@ -162,10 +166,26 @@
|
||||
# define EVENT EVENT0
|
||||
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english Compatibility helper that raises event "event" on source object "src".
|
||||
//! \~russian Совместимый вспомогательный макрос, вызывающий событие "event" у объекта-источника "src".
|
||||
# define RAISE_EVENT0(src, event)
|
||||
//! \relatesalso PIObject
|
||||
//! \~english Compatibility helper that raises event "event" with one argument.
|
||||
//! \~russian Совместимый вспомогательный макрос, вызывающий событие "event" с одним аргументом.
|
||||
# define RAISE_EVENT1(src, event, v0)
|
||||
//! \relatesalso PIObject
|
||||
//! \~english Compatibility helper that raises event "event" with two arguments.
|
||||
//! \~russian Совместимый вспомогательный макрос, вызывающий событие "event" с двумя аргументами.
|
||||
# define RAISE_EVENT2(src, event, v0, v1)
|
||||
//! \relatesalso PIObject
|
||||
//! \~english Compatibility helper that raises event "event" with three arguments.
|
||||
//! \~russian Совместимый вспомогательный макрос, вызывающий событие "event" с тремя аргументами.
|
||||
# define RAISE_EVENT3(src, event, v0, v1, v2)
|
||||
//! \relatesalso PIObject
|
||||
//! \~english Compatibility helper that raises event "event" with four arguments.
|
||||
//! \~russian Совместимый вспомогательный макрос, вызывающий событие "event" с четырьмя аргументами.
|
||||
# define RAISE_EVENT4(src, event, v0, v1, v2, v3)
|
||||
# define RAISE_EVENT RAISE_EVENT0
|
||||
|
||||
@@ -176,11 +196,11 @@
|
||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" объекта \"dest\".
|
||||
//! \~\details
|
||||
//! \~english
|
||||
//! \"handler\" can handle subset arguments of \"event\".
|
||||
//! Returns \a PIObject::Connection
|
||||
//! \"handler\" can accept a prefix of \"event\" arguments.
|
||||
//! This macro resolves registered methods by name at run time and returns \a PIObject::Connection.
|
||||
//! \~russian
|
||||
//! \"handler\" может принимать не все аргументы от \"event\".
|
||||
//! Возвращает \a PIObject::Connection
|
||||
//! \"handler\" может принимать только начальную часть аргументов \"event\".
|
||||
//! Макрос ищет зарегистрированные методы по имени во время выполнения и возвращает \a PIObject::Connection.
|
||||
# define CONNECTU(src, event, dest, handler)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
@@ -189,17 +209,19 @@
|
||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" объекта \"dest\".
|
||||
//! \~\details
|
||||
//! \~english
|
||||
//! \"handler\" can handle subset arguments of \"event\".
|
||||
//! Event handler will be executed by \"performer\" when \a PIObject::callQueuedEvents() called.
|
||||
//! \"handler\" can accept a prefix of \"event\" arguments.
|
||||
//! Delivery is queued on the performer object and runs only when that object calls
|
||||
//! \a PIObject::callQueuedEvents() or \a PIObject::maybeCallQueuedEvents().
|
||||
//! All argument types should be registered by \a REGISTER_VARIANT() macro, but many
|
||||
//! common and PIP types already done.
|
||||
//! Returns \a PIObject::Connection
|
||||
//! Returns \a PIObject::Connection.
|
||||
//! \~russian
|
||||
//! \"handler\" может принимать не все аргументы от \"event\".
|
||||
//! Обработчик будет вызван объектом \"performer\" при вызове \a PIObject::callQueuedEvents().
|
||||
//! \"handler\" может принимать только начальную часть аргументов \"event\".
|
||||
//! Доставка ставится в очередь объекта \"performer\" и выполняется только когда этот объект
|
||||
//! вызывает \a PIObject::callQueuedEvents() или \a PIObject::maybeCallQueuedEvents().
|
||||
//! Все типы аргументов должны быть зарегистрированы с помощью макроса \a REGISTER_VARIANT(),
|
||||
//! однако многие стандартные и PIP типы уже там.
|
||||
//! Возвращает \a PIObject::Connection
|
||||
//! Возвращает \a PIObject::Connection.
|
||||
# define CONNECTU_QUEUED(src, event, dest, handler, performer)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
@@ -208,13 +230,13 @@
|
||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к лямбда-функции \"functor\".
|
||||
//! \~\details
|
||||
//! \~english
|
||||
//! \"event\" and \"functor\" must has equal argument lists.
|
||||
//! You should parentness \"functor\" with () if this is complex lambda.
|
||||
//! Returns \a PIObject::Connection
|
||||
//! \"event\" and \"functor\" must have the same argument list.
|
||||
//! Wrap \"functor\" in () when the lambda expression is complex.
|
||||
//! Returns \a PIObject::Connection.
|
||||
//! \~russian
|
||||
//! \"event\" и \"functor\" должны иметь одинаковые аргументы.
|
||||
//! В случае сложной лямбда-функции оберните её ().
|
||||
//! Возвращает \a PIObject::Connection
|
||||
//! \"event\" и \"functor\" должны иметь одинаковый список аргументов.
|
||||
//! В случае сложной лямбда-функции оберните её в ().
|
||||
//! Возвращает \a PIObject::Connection.
|
||||
# define CONNECTL(src, event, functor)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
@@ -222,12 +244,11 @@
|
||||
//! \~english Use \a CONNECTU() instead
|
||||
//! \~russian Используйте \a CONNECTU()
|
||||
//! \~\brief
|
||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" with
|
||||
//! check of event and handler exists
|
||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта
|
||||
//! \"dest\" с проверкой наличия события и обработчика.
|
||||
//! \~english Legacy compatibility helper that connects an event to a registered handler with compile-time signature spelling.
|
||||
//! \~russian Устаревший совместимый макрос, который соединяет событие с зарегистрированным обработчиком через явное указание сигнатуры.
|
||||
//! \~\details
|
||||
//! Returns PIObject::Connection
|
||||
//! \~english Prefer \a CONNECTU() for new code.
|
||||
//! \~russian Для нового кода предпочитайте \a CONNECTU().
|
||||
# define CONNECT0(ret, src, event, dest, handler)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
@@ -235,12 +256,8 @@
|
||||
//! \~english Use \a CONNECTU() instead
|
||||
//! \~russian Используйте \a CONNECTU()
|
||||
//! \~\brief
|
||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" with
|
||||
//! check of event and handler exists
|
||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта
|
||||
//! \"dest\" с проверкой наличия события и обработчика.
|
||||
//! \~\details
|
||||
//! Returns PIObject::Connection
|
||||
//! \~english Legacy compatibility helper for a one-argument registered event or handler.
|
||||
//! \~russian Устаревший совместимый макрос для зарегистрированного события или обработчика с одним аргументом.
|
||||
# define CONNECT1(ret, type0, src, event, dest, handler)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
@@ -248,12 +265,8 @@
|
||||
//! \~english Use \a CONNECTU() instead
|
||||
//! \~russian Используйте \a CONNECTU()
|
||||
//! \~\brief
|
||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" with
|
||||
//! check of event and handler exists
|
||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта
|
||||
//! \"dest\" с проверкой наличия события и обработчика.
|
||||
//! \~\details
|
||||
//! Returns PIObject::Connection
|
||||
//! \~english Legacy compatibility helper for a two-argument registered event or handler.
|
||||
//! \~russian Устаревший совместимый макрос для зарегистрированного события или обработчика с двумя аргументами.
|
||||
# define CONNECT2(ret, type0, type1, src, event, dest, handler)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
@@ -261,12 +274,8 @@
|
||||
//! \~english Use \a CONNECTU() instead
|
||||
//! \~russian Используйте \a CONNECTU()
|
||||
//! \~\brief
|
||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" with
|
||||
//! check of event and handler exists
|
||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта
|
||||
//! \"dest\" с проверкой наличия события и обработчика.
|
||||
//! \~\details
|
||||
//! Returns PIObject::Connection
|
||||
//! \~english Legacy compatibility helper for a three-argument registered event or handler.
|
||||
//! \~russian Устаревший совместимый макрос для зарегистрированного события или обработчика с тремя аргументами.
|
||||
# define CONNECT3(ret, type0, type1, type2, src, event, dest, handler)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
@@ -274,12 +283,8 @@
|
||||
//! \~english Use \a CONNECTU() instead
|
||||
//! \~russian Используйте \a CONNECTU()
|
||||
//! \~\brief
|
||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" with
|
||||
//! check of event and handler exists.
|
||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта
|
||||
//! \"dest\" с проверкой наличия события и обработчика.
|
||||
//! \~\details
|
||||
//! Returns PIObject::Connection
|
||||
//! \~english Legacy compatibility helper for a four-argument registered event or handler.
|
||||
//! \~russian Устаревший совместимый макрос для зарегистрированного события или обработчика с четырьмя аргументами.
|
||||
# define CONNECT4(ret, type0, type1, type2, type3, src, event, dest, handler)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
@@ -297,10 +302,8 @@
|
||||
//! \~english Use \a CONNECTU() instead
|
||||
//! \~russian Используйте \a CONNECTU()
|
||||
//! \~\brief
|
||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" without
|
||||
//! check of event exists
|
||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта
|
||||
//! \"dest\" без проверки наличия события и обработчика.
|
||||
//! \~english Legacy compatibility helper that skips source method verification.
|
||||
//! \~russian Устаревший совместимый макрос, который пропускает проверку исходного метода.
|
||||
# define WEAK_CONNECT0(ret, src, event, dest, handler)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
@@ -308,10 +311,8 @@
|
||||
//! \~english Use \a CONNECTU() instead
|
||||
//! \~russian Используйте \a CONNECTU()
|
||||
//! \~\brief
|
||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" without
|
||||
//! check of event exists
|
||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта
|
||||
//! \"dest\" без проверки наличия события и обработчика.
|
||||
//! \~english Legacy compatibility helper that skips source method verification for one argument.
|
||||
//! \~russian Устаревший совместимый макрос, который пропускает проверку исходного метода для случая с одним аргументом.
|
||||
# define WEAK_CONNECT1(ret, type0, src, event, dest, handler)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
@@ -319,10 +320,8 @@
|
||||
//! \~english Use \a CONNECTU() instead
|
||||
//! \~russian Используйте \a CONNECTU()
|
||||
//! \~\brief
|
||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" without
|
||||
//! check of event exists
|
||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта
|
||||
//! \"dest\" без проверки наличия события и обработчика.
|
||||
//! \~english Legacy compatibility helper that skips source method verification for two arguments.
|
||||
//! \~russian Устаревший совместимый макрос, который пропускает проверку исходного метода для случая с двумя аргументами.
|
||||
# define WEAK_CONNECT2(ret, type0, type1, src, event, dest, handler)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
@@ -330,10 +329,8 @@
|
||||
//! \~english Use \a CONNECTU() instead
|
||||
//! \~russian Используйте \a CONNECTU()
|
||||
//! \~\brief
|
||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" without
|
||||
//! check of event exists
|
||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта
|
||||
//! \"dest\" без проверки наличия события и обработчика.
|
||||
//! \~english Legacy compatibility helper that skips source method verification for three arguments.
|
||||
//! \~russian Устаревший совместимый макрос, который пропускает проверку исходного метода для случая с тремя аргументами.
|
||||
# define WEAK_CONNECT3(ret, type0, type1, type2, src, event, dest, handler)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
@@ -341,10 +338,8 @@
|
||||
//! \~english Use \a CONNECTU() instead
|
||||
//! \~russian Используйте \a CONNECTU()
|
||||
//! \~\brief
|
||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" without
|
||||
//! check of event exists
|
||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта
|
||||
//! \"dest\" без проверки наличия события и обработчика.
|
||||
//! \~english Legacy compatibility helper that skips source method verification for four arguments.
|
||||
//! \~russian Устаревший совместимый макрос, который пропускает проверку исходного метода для случая с четырьмя аргументами.
|
||||
# define WEAK_CONNECT4(ret, type0, type1, type2, type3, src, event, dest, handler)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
@@ -359,37 +354,32 @@
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english piDisconnect event \"event\" from object \"src\" from event handler \"handler\" with return type \"ret\" from object \"dest\"
|
||||
//! \~russian piDisconnect событие \"event\" объекта \"src\" от обработчика или события \"handler\" с возвращаемым типом \"ret\" объекта
|
||||
//! \"dest\"
|
||||
//! \~english Disconnect a registered event from a registered event handler.
|
||||
//! \~russian Разрывает соединение зарегистрированного события с зарегистрированным обработчиком.
|
||||
# define DISCONNECT0(ret, src, event, dest, handler)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english piDisconnect event \"event\" from object \"src\" from event handler \"handler\" with return type \"ret\" from object \"dest\"
|
||||
//! \~russian piDisconnect событие \"event\" объекта \"src\" от обработчика или события \"handler\" с возвращаемым типом \"ret\" объекта
|
||||
//! \"dest\"
|
||||
//! \~english Disconnect a one-argument registered event from a registered event handler.
|
||||
//! \~russian Разрывает соединение зарегистрированного события с одним аргументом и зарегистрированного обработчика.
|
||||
# define DISCONNECT1(ret, type0, src, event, dest, handler)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english piDisconnect event \"event\" from object \"src\" from event handler \"handler\" with return type \"ret\" from object \"dest\"
|
||||
//! \~russian piDisconnect событие \"event\" объекта \"src\" от обработчика или события \"handler\" с возвращаемым типом \"ret\" объекта
|
||||
//! \"dest\"
|
||||
//! \~english Disconnect a two-argument registered event from a registered event handler.
|
||||
//! \~russian Разрывает соединение зарегистрированного события с двумя аргументами и зарегистрированного обработчика.
|
||||
# define DISCONNECT2(ret, type0, type1, src, event, dest, handler)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english piDisconnect event \"event\" from object \"src\" from event handler \"handler\" with return type \"ret\" from object \"dest\"
|
||||
//! \~russian piDisconnect событие \"event\" объекта \"src\" от обработчика или события \"handler\" с возвращаемым типом \"ret\" объекта
|
||||
//! \"dest\"
|
||||
//! \~english Disconnect a three-argument registered event from a registered event handler.
|
||||
//! \~russian Разрывает соединение зарегистрированного события с тремя аргументами и зарегистрированного обработчика.
|
||||
# define DISCONNECT3(ret, type0, type1, type2, src, event, dest, handler)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english piDisconnect event \"event\" from object \"src\" from event handler \"handler\" with return type \"ret\" from object \"dest\"
|
||||
//! \~russian piDisconnect событие \"event\" объекта \"src\" от обработчика или события \"handler\" с возвращаемым типом \"ret\" объекта
|
||||
//! \"dest\"
|
||||
//! \~english Disconnect a four-argument registered event from a registered event handler.
|
||||
//! \~russian Разрывает соединение зарегистрированного события с четырьмя аргументами и зарегистрированного обработчика.
|
||||
# define DISCONNECT4(ret, type0, type1, type2, type3, src, event, dest, handler)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
@@ -401,8 +391,8 @@
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english Returns pointer to events handler \"handler\"
|
||||
//! \~russian Возвращает указатель на обработчик события \"handler\"
|
||||
//! \~english Low-level helper that expands to the registered handler entry point.
|
||||
//! \~russian Низкоуровневый вспомогательный макрос, который разворачивается в точку входа зарегистрированного обработчика.
|
||||
# define HANDLER(handler)
|
||||
|
||||
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/*! \file piauth.h
|
||||
* \ingroup Crypt
|
||||
* \~\brief
|
||||
* \~english Authentication API
|
||||
* \~russian API аутентификации
|
||||
*/
|
||||
//! \~\file piauth.h
|
||||
//! \~\ingroup Crypt
|
||||
//! \~\brief
|
||||
//! \~english Authentication API
|
||||
//! \~russian API аутентификации
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
PIP Authentication API
|
||||
@@ -31,72 +30,110 @@
|
||||
#include "pip_crypt_export.h"
|
||||
|
||||
|
||||
//! \~\ingroup Crypt
|
||||
//! \~\brief
|
||||
//! \~english Peer authentication state machine with signed key exchange.
|
||||
//! \~russian Машина состояний аутентификации узлов с подписанным обменом ключами.
|
||||
class PIP_CRYPT_EXPORT PIAuth: public PIObject {
|
||||
PIOBJECT(PIAuth)
|
||||
|
||||
public:
|
||||
//! \~english Handshake state.
|
||||
//! \~russian Состояние рукопожатия.
|
||||
enum State {
|
||||
NotConnected,
|
||||
AuthProbe,
|
||||
PassRequest,
|
||||
AuthReply,
|
||||
KeyExchange,
|
||||
Connected
|
||||
NotConnected /** \~english No active authentication session. \~russian Активной сессии аутентификации нет. */,
|
||||
AuthProbe /** \~english Initial probe stage with signed peer introduction. \~russian Начальный этап с подписанным представлением
|
||||
узла. */
|
||||
,
|
||||
PassRequest /** \~english Password verification stage for unknown peers. \~russian Этап проверки пароля для неизвестных узлов. */,
|
||||
AuthReply /** \~english Reply with client authentication data. \~russian Ответ с данными аутентификации клиента. */,
|
||||
KeyExchange /** \~english Session key exchange stage. \~russian Этап обмена сеансовым ключом. */,
|
||||
Connected /** \~english Authentication finished and session key is established. \~russian Аутентификация завершена и сеансовый ключ
|
||||
установлен. */
|
||||
};
|
||||
|
||||
//! Create PIAuth with your digital sign
|
||||
|
||||
//! \~english Creates an authentication endpoint from a signing secret key.
|
||||
//! \~russian Создает конечную точку аутентификации из секретного ключа подписи.
|
||||
PIAuth(const PIByteArray & sign);
|
||||
|
||||
//! Set server info data for client authorize event
|
||||
|
||||
//! \~english Sets application-defined info exchanged during authorization.
|
||||
//! \~russian Задает прикладные данные, передаваемые во время авторизации.
|
||||
void setInfoData(const PIByteArray & info) { custom_info = info; }
|
||||
|
||||
//! Set server password for check
|
||||
//! \~english Sets the server password used for password-based peer validation.
|
||||
//! \~russian Устанавливает пароль сервера, используемый для проверки узла по паролю.
|
||||
void setServerPassword(const PIString & ps);
|
||||
|
||||
//! Set list of trusted clients/servers public digital sign keys
|
||||
//! \~english Replaces the list of trusted peer signing public keys.
|
||||
//! \~russian Заменяет список доверенных открытых ключей подписи удаленных узлов.
|
||||
void setAuthorizedPublicKeys(const PIVector<PIByteArray> & pkeys) { auth_pkeys = pkeys; }
|
||||
|
||||
//! Get list of trusted clients/servers public digital sign keys
|
||||
//! \~english Returns the list of trusted peer signing public keys.
|
||||
//! \~russian Возвращает список доверенных открытых ключей подписи удаленных узлов.
|
||||
PIVector<PIByteArray> getAuthorizedPublicKeys() { return auth_pkeys; }
|
||||
|
||||
//! Get your digital sign public key
|
||||
//! \~english Returns the public signing key derived from the local secret key.
|
||||
//! \~russian Возвращает открытый ключ подписи, полученный из локального секретного ключа.
|
||||
PIByteArray getSignPublicKey() { return sign_pk; }
|
||||
|
||||
|
||||
//! Stop authorization
|
||||
//! \~english Stops the current authorization session and clears transient keys.
|
||||
//! \~russian Останавливает текущую сессию авторизации и очищает временные ключи.
|
||||
void stop();
|
||||
|
||||
//! Start authorization as client
|
||||
//! \~english Starts the handshake in client mode.
|
||||
//! \~russian Запускает рукопожатие в режиме клиента.
|
||||
void startClient();
|
||||
|
||||
//! Start authorization as server, return first server message for client
|
||||
//! \~english Starts the handshake in server mode and returns the first packet for the client.
|
||||
//! \~russian Запускает рукопожатие в режиме сервера и возвращает первый пакет для клиента.
|
||||
PIByteArray startServer();
|
||||
|
||||
//! Process reseived message both for client and server, return current state and new message writed in "ba"
|
||||
//! \~english Processes an incoming handshake packet, updates the state and writes the reply back to \a ba.
|
||||
//! \~russian Обрабатывает входящий пакет рукопожатия, обновляет состояние и записывает ответ обратно в \a ba.
|
||||
State receive(PIByteArray & ba);
|
||||
|
||||
//! Get session secret key, return key only when Connected state
|
||||
//! \~english Returns the session secret key after the state becomes \a Connected.
|
||||
//! \~russian Возвращает сеансовый секретный ключ после перехода в состояние \a Connected.
|
||||
PIByteArray getSecretKey();
|
||||
|
||||
//! Generate digital sign from seed
|
||||
//! \~english Generates a signing secret key from \a seed.
|
||||
//! \~russian Генерирует секретный ключ подписи из \a seed.
|
||||
static PIByteArray generateSign(const PIByteArray & seed);
|
||||
|
||||
|
||||
//! Disconneted event
|
||||
//! \events
|
||||
//! \{
|
||||
|
||||
//! \fn void disconnected(PIString reason)
|
||||
//! \~english Raised when the handshake is aborted or an established session is dropped.
|
||||
//! \~russian Вызывается при прерывании рукопожатия или разрыве установленной сессии.
|
||||
EVENT1(disconnected, PIString, reason);
|
||||
|
||||
//! Conneted event
|
||||
//! \fn void connected(PIString info)
|
||||
//! \~english Raised after the peer reaches state \a Connected.
|
||||
//! \~russian Вызывается после перехода узла в состояние \a Connected.
|
||||
EVENT1(connected, PIString, info);
|
||||
|
||||
//! Client event for authorize new server
|
||||
//! \fn void authorize(PIByteArray info, bool * ok)
|
||||
//! \~english Client-side callback used to approve an unknown server and optionally trust its signing key.
|
||||
//! \~russian Клиентский вызов для подтверждения неизвестного сервера и, при необходимости, доверия его ключу подписи.
|
||||
EVENT2(authorize, PIByteArray, info, bool *, ok);
|
||||
|
||||
//! Client event for input server password
|
||||
//! \fn void passwordRequest(PIString * pass)
|
||||
//! \~english Client-side callback requesting the server password.
|
||||
//! \~russian Клиентский вызов для запроса пароля сервера.
|
||||
EVENT1(passwordRequest, PIString *, pass);
|
||||
|
||||
//! Server event on check client password
|
||||
//! \fn void passwordCheck(bool result)
|
||||
//! \~english Server-side callback reporting the result of client password validation.
|
||||
//! \~russian Серверный вызов, сообщающий результат проверки пароля клиента.
|
||||
EVENT1(passwordCheck, bool, result);
|
||||
|
||||
//! \}
|
||||
|
||||
private:
|
||||
enum Role {
|
||||
Client,
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/*! \file picrypt.h
|
||||
* \ingroup Crypt
|
||||
* \~\brief
|
||||
* \~english Cryptographic using libsodium
|
||||
* \~russian Шифрование с помощью libsodium
|
||||
*/
|
||||
//! \~\ingroup Crypt
|
||||
//! \~\file picrypt.h
|
||||
//! \brief
|
||||
//! \~english Cryptographic using libsodium
|
||||
//! \~russian Шифрование с помощью libsodium
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Cryptographic class using lib Sodium
|
||||
@@ -29,154 +28,136 @@
|
||||
#include "pip_crypt_export.h"
|
||||
#include "pistring.h"
|
||||
|
||||
//! \ingroup Crypt
|
||||
//! \~\ingroup Crypt
|
||||
//! \~\brief
|
||||
//! \~english Class for encrypting and decrypting data.
|
||||
//! \~russian Класс для шифрования и дешифрования данных.
|
||||
//! \details
|
||||
//! \~english Class providing cryptographic operations using the libsodium library, including encryption, decryption, hashing, and digital
|
||||
//! signatures. It supports both instance-based and static method-based operations.
|
||||
//! \~russian Класс, предоставляющий криптографические операции с использованием библиотеки libsodium, включая шифрование, дешифрование,
|
||||
//! хэширование и цифровые подписи. Поддерживаются операции как на основе экземпляра класса, так и на основе статических методов.
|
||||
//! \note
|
||||
//! \~english Requires libsodium library initialization. All methods are thread-safe when using different keys.
|
||||
//! \~russian Требуется инициализация библиотеки libsodium. Все методы потокобезопасны при использовании различных ключей.
|
||||
class PIP_CRYPT_EXPORT PICrypt {
|
||||
public:
|
||||
//! \~\brief
|
||||
//! \~english Constructor that generates a random key
|
||||
//! \~russian Конструктор, генерирующий случайный ключ
|
||||
//! \~english Constructor that generates a random key.
|
||||
//! \~russian Конструктор, генерирующий случайный ключ.
|
||||
PICrypt();
|
||||
|
||||
//! \~english Destructor.
|
||||
//! \~russian Деструктор.
|
||||
~PICrypt();
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Set key to "key", key size must be a \a sizeKey()
|
||||
//! \~russian Установить ключ "key", размер ключа должен быть равен \a sizeKey()
|
||||
//! \~english Set key to "key", key size must be a \a sizeKey().
|
||||
//! \~russian Установить ключ "key", размер ключа должен быть равен \a sizeKey().
|
||||
bool setKey(const PIByteArray & key);
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Generate and set key from keyphrase "secret"
|
||||
//! \~russian Генерировать и установить ключ из ключевой фразы "secret"
|
||||
//! \~english Generate and set key from keyphrase "secret".
|
||||
//! \~russian Генерировать и установить ключ из ключевой фразы "secret".
|
||||
bool setKey(const PIString & secret);
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Returns current key
|
||||
//! \~russian Возвращает текущий ключ
|
||||
//! \~english Returns current key.
|
||||
//! \~russian Возвращает текущий ключ.
|
||||
PIByteArray key() { return key_; }
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Encrypt given data "data", result size will be increased by \a sizeCrypt()
|
||||
//! \~russian Зашифровать данные "data", размер результата увеличится на \a sizeCrypt()
|
||||
//! \~english Encrypt given data "data", result size will be increased by \a sizeCrypt().
|
||||
//! \~russian Зашифровать данные "data", размер результата увеличится на \a sizeCrypt().
|
||||
PIByteArray crypt(const PIByteArray & data);
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Decrypt given data "crypt_data"
|
||||
//! \~russian Расшифровать данные "crypt_data"
|
||||
//! \~english Decrypt given data "crypt_data".
|
||||
//! \~russian Расшифровать данные "crypt_data".
|
||||
PIByteArray decrypt(const PIByteArray & crypt_data, bool * ok = 0);
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Encrypt given data "data" with key "key", result size will be increased by \a sizeCrypt()
|
||||
//! \~russian Зашифровать данные "data" ключом "key", размер результата увеличится на \a sizeCrypt()
|
||||
//! \~english Encrypt given data "data" with key "key", result size will be increased by \a sizeCrypt().
|
||||
//! \~russian Зашифровать данные "data" ключом "key", размер результата увеличится на \a sizeCrypt().
|
||||
static PIByteArray crypt(const PIByteArray & data, PIByteArray key);
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Decrypt given data "crypt_data" with key "key"
|
||||
//! \~russian Расшифровать данные "crypt_data" ключом "key"
|
||||
//! \~english Decrypt given data "crypt_data" with key "key".
|
||||
//! \~russian Расшифровать данные "crypt_data" ключом "key".
|
||||
static PIByteArray decrypt(const PIByteArray & crypt_data, PIByteArray key, bool * ok = 0);
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Generate hash from keyphrase "secret", may be used as a key for encryption
|
||||
//! \~russian Генерировать хэш из ключевой фразы "secret", может использоваться в качестве ключа для шифрования
|
||||
//! \~english Generate hash from keyphrase "secret", may be used as a key for encryption.
|
||||
//! \~russian Генерировать хэш из ключевой фразы "secret", может использоваться в качестве ключа для шифрования.
|
||||
static PIByteArray hash(PIString secret);
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Generate hash from bytearray
|
||||
//! \~russian Генерировать хэш из массива байт
|
||||
//! \~english Generate hash from bytearray.
|
||||
//! \~russian Генерировать хэш из массива байт.
|
||||
static PIByteArray hash(const PIByteArray & data);
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Generate hash from bytearray
|
||||
//! \~russian Генерировать хэш из массива байт
|
||||
//! \~english Generate hash from bytearray using provided key.
|
||||
//! \~russian Генерировать хэш из массива байт с использованием предоставленного ключа.
|
||||
static PIByteArray hash(const PIByteArray & data, const unsigned char * key, size_t keylen);
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Returns hash size
|
||||
//! \~russian Возвращает размер хэша
|
||||
//! \~english Returns hash size.
|
||||
//! \~russian Возвращает размер хэша.
|
||||
static size_t sizeHash();
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Generate short hash from string "s", may be used for hash table
|
||||
//! \~russian Генерировать короткий хэш из строки "s", может использоваться для хэш-таблиц
|
||||
//! \~english Generate short hash from string "s", may be used for hash table.
|
||||
//! \~russian Генерировать короткий хэш из строки "s", может использоваться для хэш-таблиц.
|
||||
static ullong shorthash(const PIString & s, PIByteArray key = PIByteArray());
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Generate random key
|
||||
//! \~russian Генерировать случайный ключ
|
||||
//! \~english Generate random key.
|
||||
//! \~russian Генерировать случайный ключ.
|
||||
static PIByteArray generateKey();
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Generate random buffer
|
||||
//! \~russian Генерировать случайный буфер
|
||||
//! \~english Generate random buffer.
|
||||
//! \~russian Генерировать случайный буфер.
|
||||
static PIByteArray generateRandomBuff(int size);
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Returns key size
|
||||
//! \~russian Возвращает размер ключа
|
||||
//! \~english Returns key size.
|
||||
//! \~russian Возвращает размер ключа.
|
||||
static size_t sizeKey();
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Returns size which be added to data size in encryption process
|
||||
//! \~russian Возвращает размер, который будет добавлен к размеру данных в процессе шифрования
|
||||
//! \~english Returns size which be added to data size in encryption process.
|
||||
//! \~russian Возвращает размер, который будет добавлен к размеру данных в процессе шифрования.
|
||||
static size_t sizeCrypt();
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Function randomly generates a secret key and a corresponding public key for digital signature
|
||||
//! \~russian Функция случайным образом генерирует секретный ключ и соответствующий ему открытый ключ для цифровой подписи
|
||||
//! \~english Function randomly generates a secret key and a corresponding public key for digital signature.
|
||||
//! \~russian Функция случайным образом генерирует секретный ключ и соответствующий ему открытый ключ для цифровой подписи.
|
||||
static bool generateSignKeys(PIByteArray & public_key, PIByteArray & secret_key);
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Function generates a secret key from input data and a corresponding public key for digital signature
|
||||
//! \~russian Функция генерирует секретный ключ из входных данных и соответствующий ему открытый ключ для цифровой подписи
|
||||
//! \~english Function generates a secret key from input data and a corresponding public key for digital signature.
|
||||
//! \~russian Функция генерирует секретный ключ из входных данных и соответствующий ему открытый ключ для цифровой подписи.
|
||||
static bool generateSignKeys(PIByteArray & public_key, PIByteArray & secret_key, const PIByteArray & seed);
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Function extract sign public key from sing secret key
|
||||
//! \~russian Функция извлекает открытый ключ для подписи из секретного ключа для подписи
|
||||
//! \~english Function extract sign public key from sing secret key.
|
||||
//! \~russian Функция извлекает открытый ключ для подписи из секретного ключа для подписи.
|
||||
static PIByteArray extractSignPublicKey(const PIByteArray & secret_key);
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Calculate digital signature for data
|
||||
//! \~russian Вычислить цифровую подпись для данных
|
||||
//! \~english Calculate digital signature for data.
|
||||
//! \~russian Вычислить цифровую подпись для данных.
|
||||
PIByteArray signMessage(const PIByteArray & data, const PIByteArray & secret_key);
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Verify digital signature of signed message
|
||||
//! \~russian Проверить цифровую подпись подписанного сообщения
|
||||
//! \~english Verify digital signature of signed message.
|
||||
//! \~russian Проверить цифровую подпись подписанного сообщения.
|
||||
bool verifySign(const PIByteArray & data, const PIByteArray & signature, const PIByteArray & public_key);
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Function randomly generates a secret key and a corresponding public key for authenticated encryption
|
||||
//! \~english Function randomly generates a secret key and a corresponding public key for authenticated encryption.
|
||||
//! \~russian Функция случайным образом генерирует секретный ключ и соответствующий ему открытый ключ для аутентифицированного
|
||||
//! шифрования
|
||||
//! шифрования.
|
||||
static bool generateKeypair(PIByteArray & public_key, PIByteArray & secret_key);
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Function generates a secret key from input data and a corresponding public key for authenticated encryption
|
||||
//! \~english Function generates a secret key from input data and a corresponding public key for authenticated encryption.
|
||||
//! \~russian Функция генерирует секретный ключ из входных данных и соответствующий ему открытый ключ для аутентифицированного
|
||||
//! шифрования
|
||||
//! шифрования.
|
||||
static bool generateKeypair(PIByteArray & public_key, PIByteArray & secret_key, const PIByteArray & seed);
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Encrypt given data "data"
|
||||
//! \~russian Зашифровать данные "data"
|
||||
//! \~english Encrypt given data "data".
|
||||
//! \~russian Зашифровать данные "data".
|
||||
PIByteArray crypt(const PIByteArray & data, const PIByteArray & public_key, const PIByteArray & secret_key);
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Decrypt given data "crypt_data"
|
||||
//! \~russian Расшифровать данные "crypt_data"
|
||||
//! \~english Decrypt given data "crypt_data".
|
||||
//! \~russian Расшифровать данные "crypt_data".
|
||||
PIByteArray decrypt(const PIByteArray & crypt_data, const PIByteArray & public_key, const PIByteArray & secret_key, bool * ok = 0);
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Generate password hash from "password"
|
||||
//! \~russian Генерировать хэш пароля из "password"
|
||||
//! \~english Generate password hash from "password".
|
||||
//! \~russian Генерировать хэш пароля из "password".
|
||||
static PIByteArray passwordHash(PIString password, const PIByteArray & seed);
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Returns libsodium version
|
||||
//! \~russian Возвращает версию libsodium
|
||||
//! \~english Returns libsodium version.
|
||||
//! \~russian Возвращает версию libsodium.
|
||||
static PIString version();
|
||||
|
||||
|
||||
|
||||
@@ -1,3 +1,13 @@
|
||||
/*! \file picryptmodule.h
|
||||
* \ingroup Crypt
|
||||
* \~\brief
|
||||
* \~english Umbrella header for the Crypt module
|
||||
* \~russian Зонтичный заголовок модуля Crypt
|
||||
*
|
||||
* \~\details
|
||||
* \~english Includes the public cryptographic and authentication headers.
|
||||
* \~russian Подключает публичные заголовки шифрования и аутентификации.
|
||||
*/
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Module includes
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
#include "pidigest_md5_p.h"
|
||||
#include "pidigest_sha1_p.h"
|
||||
#include "pidigest_sha2_p.h"
|
||||
#include "pidigest_siphash_p.h"
|
||||
|
||||
|
||||
int PIDigest::hashLength(Type type) {
|
||||
@@ -49,6 +50,10 @@ int PIDigest::hashLength(Type type) {
|
||||
case Type::BLAKE2b_256: return 32;
|
||||
case Type::BLAKE2b_384: return 48;
|
||||
case Type::BLAKE2b_512: return 64;
|
||||
case Type::SipHash_2_4_64: return 8;
|
||||
case Type::SipHash_2_4_128: return 16;
|
||||
case Type::HalfSipHash_2_4_32: return 4;
|
||||
case Type::HalfSipHash_2_4_64: return 8;
|
||||
default: break;
|
||||
}
|
||||
return 0;
|
||||
@@ -77,6 +82,10 @@ int PIDigest::blockLength(Type type) {
|
||||
case Type::BLAKE2b_256:
|
||||
case Type::BLAKE2b_384:
|
||||
case Type::BLAKE2b_512: return 128;
|
||||
case Type::SipHash_2_4_64: return 8;
|
||||
case Type::SipHash_2_4_128: return 16;
|
||||
case Type::HalfSipHash_2_4_32: return 4;
|
||||
case Type::HalfSipHash_2_4_64: return 8;
|
||||
default: break;
|
||||
}
|
||||
return 0;
|
||||
@@ -105,6 +114,10 @@ PIConstChars PIDigest::typeName(Type type) {
|
||||
case Type::BLAKE2b_256: return "BLAKE2b_256";
|
||||
case Type::BLAKE2b_384: return "BLAKE2b_384";
|
||||
case Type::BLAKE2b_512: return "BLAKE2b_512";
|
||||
case Type::SipHash_2_4_64: return "SipHash_2_4_64";
|
||||
case Type::SipHash_2_4_128: return "SipHash_2_4_128";
|
||||
case Type::HalfSipHash_2_4_32: return "HalfSipHash_2_4_32";
|
||||
case Type::HalfSipHash_2_4_64: return "HalfSipHash_2_4_64";
|
||||
default: break;
|
||||
}
|
||||
return "Unknown";
|
||||
@@ -123,16 +136,42 @@ PIByteArray PIDigest::calculate(const PIByteArray & msg, Type type) {
|
||||
case Type::SHA2_512: return SHA2::sha5xx(msg, SHA2::initial_512, 64);
|
||||
case Type::SHA2_512_224: return SHA2::sha5xx(msg, SHA2::initial_512_224, 28);
|
||||
case Type::SHA2_512_256: return SHA2::sha5xx(msg, SHA2::initial_512_256, 32);
|
||||
case Type::BLAKE2s_128: return BLAKE2::blake2s(msg, 16);
|
||||
case Type::BLAKE2s_160: return BLAKE2::blake2s(msg, 20);
|
||||
case Type::BLAKE2s_224: return BLAKE2::blake2s(msg, 28);
|
||||
case Type::BLAKE2s_256: return BLAKE2::blake2s(msg, 32);
|
||||
case Type::BLAKE2b_128: return BLAKE2::blake2b(msg, 16);
|
||||
case Type::BLAKE2b_160: return BLAKE2::blake2b(msg, 20);
|
||||
case Type::BLAKE2b_224: return BLAKE2::blake2b(msg, 28);
|
||||
case Type::BLAKE2b_256: return BLAKE2::blake2b(msg, 32);
|
||||
case Type::BLAKE2b_384: return BLAKE2::blake2b(msg, 48);
|
||||
case Type::BLAKE2b_512: return BLAKE2::blake2b(msg, 64);
|
||||
case Type::BLAKE2s_128: return BLAKE2::blake2s(msg, {}, 16);
|
||||
case Type::BLAKE2s_160: return BLAKE2::blake2s(msg, {}, 20);
|
||||
case Type::BLAKE2s_224: return BLAKE2::blake2s(msg, {}, 28);
|
||||
case Type::BLAKE2s_256: return BLAKE2::blake2s(msg, {}, 32);
|
||||
case Type::BLAKE2b_128: return BLAKE2::blake2b(msg, {}, 16);
|
||||
case Type::BLAKE2b_160: return BLAKE2::blake2b(msg, {}, 20);
|
||||
case Type::BLAKE2b_224: return BLAKE2::blake2b(msg, {}, 28);
|
||||
case Type::BLAKE2b_256: return BLAKE2::blake2b(msg, {}, 32);
|
||||
case Type::BLAKE2b_384: return BLAKE2::blake2b(msg, {}, 48);
|
||||
case Type::BLAKE2b_512: return BLAKE2::blake2b(msg, {}, 64);
|
||||
case Type::SipHash_2_4_64: return SipHash::siphash(msg, {}, 8);
|
||||
case Type::SipHash_2_4_128: return SipHash::siphash(msg, {}, 16);
|
||||
case Type::HalfSipHash_2_4_32: return SipHash::halfsiphash(msg, {}, 4);
|
||||
case Type::HalfSipHash_2_4_64: return SipHash::halfsiphash(msg, {}, 8);
|
||||
default: break;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
|
||||
PIByteArray PIDigest::calculateWithKey(const PIByteArray & msg, const PIByteArray & key, Type type) {
|
||||
switch (type) {
|
||||
case Type::BLAKE2s_128: return BLAKE2::blake2s(msg, key, 16);
|
||||
case Type::BLAKE2s_160: return BLAKE2::blake2s(msg, key, 20);
|
||||
case Type::BLAKE2s_224: return BLAKE2::blake2s(msg, key, 28);
|
||||
case Type::BLAKE2s_256: return BLAKE2::blake2s(msg, key, 32);
|
||||
case Type::BLAKE2b_128: return BLAKE2::blake2b(msg, key, 16);
|
||||
case Type::BLAKE2b_160: return BLAKE2::blake2b(msg, key, 20);
|
||||
case Type::BLAKE2b_224: return BLAKE2::blake2b(msg, key, 28);
|
||||
case Type::BLAKE2b_256: return BLAKE2::blake2b(msg, key, 32);
|
||||
case Type::BLAKE2b_384: return BLAKE2::blake2b(msg, key, 48);
|
||||
case Type::BLAKE2b_512: return BLAKE2::blake2b(msg, key, 64);
|
||||
case Type::SipHash_2_4_64: return SipHash::siphash(msg, key, 8);
|
||||
case Type::SipHash_2_4_128: return SipHash::siphash(msg, key, 16);
|
||||
case Type::HalfSipHash_2_4_32: return SipHash::halfsiphash(msg, key, 4);
|
||||
case Type::HalfSipHash_2_4_64: return SipHash::halfsiphash(msg, key, 8);
|
||||
default: break;
|
||||
}
|
||||
return {};
|
||||
|
||||
@@ -1,15 +1,8 @@
|
||||
/*! \file pidigest.h
|
||||
* \ingroup Core
|
||||
* \~\brief
|
||||
* \~english Digest algorithms
|
||||
* \~russian Алгоритмы хэш-сумм
|
||||
*
|
||||
* \~\details
|
||||
* \~english
|
||||
* This file implements several common-usage hash algorithms
|
||||
* \~russian
|
||||
* Этот файл реализует несколько распространенных алгоритмов хэширования
|
||||
*/
|
||||
//! \~\file pidigest.h
|
||||
//! \~\ingroup Digest
|
||||
//! \~\brief
|
||||
//! \~english Digest calculation helpers
|
||||
//! \~russian Вспомогательные методы вычисления хэш-сумм
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Digest algorithms
|
||||
@@ -35,37 +28,72 @@
|
||||
#include "pibytearray.h"
|
||||
#include "piconstchars.h"
|
||||
|
||||
//! \class PIDigest
|
||||
//! \~\ingroup Digest
|
||||
//! \~\brief
|
||||
//! \~english One-shot digest API for supported algorithms.
|
||||
//! \~russian Одношаговый API хэширования для поддерживаемых алгоритмов.
|
||||
class PIP_EXPORT PIDigest {
|
||||
public:
|
||||
//! \~english Supported digest algorithms.
|
||||
//! \~russian Поддерживаемые алгоритмы хэширования.
|
||||
enum class Type {
|
||||
SHA1,
|
||||
SHA2_224,
|
||||
SHA2_256,
|
||||
SHA2_384,
|
||||
SHA2_512,
|
||||
SHA2_512_224,
|
||||
SHA2_512_256,
|
||||
MD2,
|
||||
MD4,
|
||||
MD5,
|
||||
BLAKE2s_128,
|
||||
BLAKE2s_160,
|
||||
BLAKE2s_224,
|
||||
BLAKE2s_256,
|
||||
BLAKE2b_128,
|
||||
BLAKE2b_160,
|
||||
BLAKE2b_224,
|
||||
BLAKE2b_256,
|
||||
BLAKE2b_384,
|
||||
BLAKE2b_512,
|
||||
Count,
|
||||
SHA1 /** \~english SHA-1 \~russian SHA-1 */,
|
||||
|
||||
SHA2_224 /** \~english SHA-2 with 224-bit digest \~russian SHA-2 с дайджестом 224 бита */,
|
||||
SHA2_256 /** \~english SHA-2 with 256-bit digest \~russian SHA-2 с дайджестом 256 бит */,
|
||||
SHA2_384 /** \~english SHA-2 with 384-bit digest \~russian SHA-2 с дайджестом 384 бита */,
|
||||
SHA2_512 /** \~english SHA-2 with 512-bit digest \~russian SHA-2 с дайджестом 512 бит */,
|
||||
SHA2_512_224 /** \~english SHA-512/224 \~russian SHA-512/224 */,
|
||||
SHA2_512_256 /** \~english SHA-512/256 \~russian SHA-512/256 */,
|
||||
|
||||
MD2 /** \~english MD2 \~russian MD2 */,
|
||||
MD4 /** \~english MD4 \~russian MD4 */,
|
||||
MD5 /** \~english MD5 \~russian MD5 */,
|
||||
|
||||
BLAKE2s_128 /** \~english BLAKE2s with 128-bit digest \~russian BLAKE2s с дайджестом 128 бит */,
|
||||
BLAKE2s_160 /** \~english BLAKE2s with 160-bit digest \~russian BLAKE2s с дайджестом 160 бит */,
|
||||
BLAKE2s_224 /** \~english BLAKE2s with 224-bit digest \~russian BLAKE2s с дайджестом 224 бита */,
|
||||
BLAKE2s_256 /** \~english BLAKE2s with 256-bit digest \~russian BLAKE2s с дайджестом 256 бит */,
|
||||
BLAKE2b_128 /** \~english BLAKE2b with 128-bit digest \~russian BLAKE2b с дайджестом 128 бит */,
|
||||
BLAKE2b_160 /** \~english BLAKE2b with 160-bit digest \~russian BLAKE2b с дайджестом 160 бит */,
|
||||
BLAKE2b_224 /** \~english BLAKE2b with 224-bit digest \~russian BLAKE2b с дайджестом 224 бита */,
|
||||
BLAKE2b_256 /** \~english BLAKE2b with 256-bit digest \~russian BLAKE2b с дайджестом 256 бит */,
|
||||
BLAKE2b_384 /** \~english BLAKE2b with 384-bit digest \~russian BLAKE2b с дайджестом 384 бита */,
|
||||
BLAKE2b_512 /** \~english BLAKE2b with 512-bit digest \~russian BLAKE2b с дайджестом 512 бит */,
|
||||
|
||||
SipHash_2_4_64 /** \~english SipHash-2-4 with 64-bit output \~russian SipHash-2-4 с выходом 64 бита */,
|
||||
SipHash_2_4_128 /** \~english SipHash-2-4 with 128-bit output \~russian SipHash-2-4 с выходом 128 бит */,
|
||||
HalfSipHash_2_4_32 /** \~english HalfSipHash-2-4 with 32-bit output \~russian HalfSipHash-2-4 с выходом 32 бита */,
|
||||
HalfSipHash_2_4_64 /** \~english HalfSipHash-2-4 with 64-bit output \~russian HalfSipHash-2-4 с выходом 64 бита */,
|
||||
|
||||
Count /** \~english Number of supported algorithms \~russian Количество поддерживаемых алгоритмов */
|
||||
};
|
||||
|
||||
|
||||
//! \~english Returns digest length in bytes for algorithm "type".
|
||||
//! \~russian Возвращает длину дайджеста в байтах для алгоритма "type".
|
||||
static int hashLength(Type type);
|
||||
|
||||
//! \~english Returns internal block length in bytes for algorithm "type".
|
||||
//! \~russian Возвращает внутреннюю длину блока в байтах для алгоритма "type".
|
||||
static int blockLength(Type type);
|
||||
|
||||
//! \~english Returns stable algorithm name for "type".
|
||||
//! \~russian Возвращает стабильное имя алгоритма для "type".
|
||||
static PIConstChars typeName(Type type);
|
||||
|
||||
|
||||
//! \~english Calculates digest of message "msg" with algorithm "type".
|
||||
//! \~russian Вычисляет хэш сообщения "msg" алгоритмом "type".
|
||||
static PIByteArray calculate(const PIByteArray & msg, Type type);
|
||||
|
||||
//! \~english Calculates keyed digest for algorithms with native key support, otherwise returns empty array.
|
||||
//! \~russian Вычисляет keyed digest для алгоритмов с нативной поддержкой ключа, иначе возвращает пустой массив.
|
||||
static PIByteArray calculateWithKey(const PIByteArray & msg, const PIByteArray & key, Type type);
|
||||
|
||||
//! \~english Calculates HMAC for message "msg" and key "key" with algorithm "type".
|
||||
//! \~russian Вычисляет HMAC для сообщения "msg" и ключа "key" алгоритмом "type".
|
||||
static PIByteArray HMAC(const PIByteArray & msg, const PIByteArray & key, PIDigest::Type type);
|
||||
};
|
||||
|
||||
|
||||
@@ -21,44 +21,18 @@
|
||||
|
||||
#include "3rd/BLAKE2/blake2.h"
|
||||
|
||||
|
||||
PIByteArray BLAKE2::blake2s(const PIByteArray & in, int out_bytes) {
|
||||
PIByteArray ret(out_bytes);
|
||||
::blake2s(ret.data(), ret.size(), in.data(), in.size(), nullptr, 0);
|
||||
return ret;
|
||||
#define IMPLEMENT(func, key_len) \
|
||||
PIByteArray BLAKE2::func(const PIByteArray & in, const PIByteArray & key, int out_bytes) { \
|
||||
PIByteArray ret(out_bytes); \
|
||||
::func(ret.data(), ret.size(), in.data(), in.size(), key.isEmpty() ? nullptr : key.data(), piMini(key.size(), key_len)); \
|
||||
return ret; \
|
||||
}
|
||||
|
||||
IMPLEMENT(blake2s, BLAKE2S_KEYBYTES)
|
||||
IMPLEMENT(blake2b, BLAKE2B_KEYBYTES)
|
||||
IMPLEMENT(blake2sp, BLAKE2S_KEYBYTES)
|
||||
IMPLEMENT(blake2bp, BLAKE2B_KEYBYTES)
|
||||
IMPLEMENT(blake2xs, BLAKE2S_KEYBYTES)
|
||||
IMPLEMENT(blake2xb, BLAKE2B_KEYBYTES)
|
||||
|
||||
PIByteArray BLAKE2::blake2b(const PIByteArray & in, int out_bytes) {
|
||||
PIByteArray ret(out_bytes);
|
||||
::blake2b(ret.data(), ret.size(), in.data(), in.size(), nullptr, 0);
|
||||
return ret;
|
||||
}
|
||||
|
||||
|
||||
PIByteArray BLAKE2::blake2sp(const PIByteArray & in, int out_bytes) {
|
||||
PIByteArray ret(out_bytes);
|
||||
::blake2sp(ret.data(), ret.size(), in.data(), in.size(), nullptr, 0);
|
||||
return ret;
|
||||
}
|
||||
|
||||
|
||||
PIByteArray BLAKE2::blake2bp(const PIByteArray & in, int out_bytes) {
|
||||
PIByteArray ret(out_bytes);
|
||||
::blake2bp(ret.data(), ret.size(), in.data(), in.size(), nullptr, 0);
|
||||
return ret;
|
||||
}
|
||||
|
||||
|
||||
PIByteArray BLAKE2::blake2xs(const PIByteArray & in, int out_bytes) {
|
||||
PIByteArray ret(out_bytes);
|
||||
::blake2xs(ret.data(), ret.size(), in.data(), in.size(), nullptr, 0);
|
||||
return ret;
|
||||
}
|
||||
|
||||
|
||||
PIByteArray BLAKE2::blake2xb(const PIByteArray & in, int out_bytes) {
|
||||
PIByteArray ret(out_bytes);
|
||||
::blake2xb(ret.data(), ret.size(), in.data(), in.size(), nullptr, 0);
|
||||
return ret;
|
||||
}
|
||||
#undef IMPLEMENT
|
||||
|
||||
@@ -24,12 +24,12 @@
|
||||
|
||||
class BLAKE2 {
|
||||
public:
|
||||
static PIByteArray blake2s(const PIByteArray & in, int out_bytes);
|
||||
static PIByteArray blake2b(const PIByteArray & in, int out_bytes);
|
||||
static PIByteArray blake2sp(const PIByteArray & in, int out_bytes);
|
||||
static PIByteArray blake2bp(const PIByteArray & in, int out_bytes);
|
||||
static PIByteArray blake2xs(const PIByteArray & in, int out_bytes);
|
||||
static PIByteArray blake2xb(const PIByteArray & in, int out_bytes);
|
||||
static PIByteArray blake2s(const PIByteArray & in, const PIByteArray & key, int out_bytes);
|
||||
static PIByteArray blake2b(const PIByteArray & in, const PIByteArray & key, int out_bytes);
|
||||
static PIByteArray blake2sp(const PIByteArray & in, const PIByteArray & key, int out_bytes);
|
||||
static PIByteArray blake2bp(const PIByteArray & in, const PIByteArray & key, int out_bytes);
|
||||
static PIByteArray blake2xs(const PIByteArray & in, const PIByteArray & key, int out_bytes);
|
||||
static PIByteArray blake2xb(const PIByteArray & in, const PIByteArray & key, int out_bytes);
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
@@ -70,7 +70,7 @@ PIByteArray SHA2::sha2xx(const PIByteArray & in, const uint32_t * initial, int o
|
||||
constexpr int part_size = 64;
|
||||
constexpr int rounds = 64;
|
||||
|
||||
static constexpr uint32_t k[part_size] = {
|
||||
static constexpr uint32_t k[rounds] = {
|
||||
0x428A2F98u, 0x71374491u, 0xB5C0FBCFu, 0xE9B5DBA5u, 0x3956C25Bu, 0x59F111F1u, 0x923F82A4u, 0xAB1C5ED5u, 0xD807AA98u, 0x12835B01u,
|
||||
0x243185BEu, 0x550C7DC3u, 0x72BE5D74u, 0x80DEB1FEu, 0x9BDC06A7u, 0xC19BF174u, 0xE49B69C1u, 0xEFBE4786u, 0x0FC19DC6u, 0x240CA1CCu,
|
||||
0x2DE92C6Fu, 0x4A7484AAu, 0x5CB0A9DCu, 0x76F988DAu, 0x983E5152u, 0xA831C66Du, 0xB00327C8u, 0xBF597FC7u, 0xC6E00BF3u, 0xD5A79147u,
|
||||
@@ -153,7 +153,7 @@ PIByteArray SHA2::sha5xx(const PIByteArray & in, const uint64_t * initial, int o
|
||||
constexpr int part_size = 128;
|
||||
constexpr int rounds = 80;
|
||||
|
||||
static constexpr uint64_t k[80] = {
|
||||
static constexpr uint64_t k[rounds] = {
|
||||
0X428A2F98D728AE22U, 0X7137449123EF65CDU, 0XB5C0FBCFEC4D3B2FU, 0XE9B5DBA58189DBBCU, 0X3956C25BF348B538U, 0X59F111F1B605D019U,
|
||||
0X923F82A4AF194F9BU, 0XAB1C5ED5DA6D8118U, 0XD807AA98A3030242U, 0X12835B0145706FBEU, 0X243185BE4EE4B28CU, 0X550C7DC3D5FFB4E2U,
|
||||
0X72BE5D74F27B896FU, 0X80DEB1FE3B1696B1U, 0X9BDC06A725C71235U, 0XC19BF174CF692694U, 0XE49B69C19EF14AD2U, 0XEFBE4786384F25E3U,
|
||||
|
||||
58
libs/main/digest/pidigest_siphash_p.cpp
Normal file
58
libs/main/digest/pidigest_siphash_p.cpp
Normal file
@@ -0,0 +1,58 @@
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Digest algorithms
|
||||
Ivan Pelipenko peri4ko@yandex.ru
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Lesser General Public License as published by
|
||||
the Free Software Foundation, either version 3 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 Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "pidigest_siphash_p.h"
|
||||
|
||||
#include "3rd/SipHash/halfsiphash.h"
|
||||
#include "3rd/SipHash/siphash.h"
|
||||
#include "3rd/SipHash/vectors.h"
|
||||
|
||||
|
||||
PIByteArray SipHash::siphash(const PIByteArray & in, const PIByteArray & key, int out_bytes) {
|
||||
PIByteArray ret(out_bytes);
|
||||
static PIByteArray empty_key(16, 0);
|
||||
if (key.isEmpty())
|
||||
::siphash(in.data(), in.size(), empty_key.data(), ret.data(), ret.size());
|
||||
else {
|
||||
if (key.size() >= 16)
|
||||
::siphash(in.data(), in.size(), key.data(), ret.data(), ret.size());
|
||||
else {
|
||||
auto skey = key.resized(16);
|
||||
::siphash(in.data(), in.size(), skey.data(), ret.data(), ret.size());
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
|
||||
PIByteArray SipHash::halfsiphash(const PIByteArray & in, const PIByteArray & key, int out_bytes) {
|
||||
PIByteArray ret(out_bytes);
|
||||
static PIByteArray empty_key(8, 0);
|
||||
if (key.isEmpty())
|
||||
::halfsiphash(in.data(), in.size(), empty_key.data(), ret.data(), ret.size());
|
||||
else {
|
||||
if (key.size() >= 8)
|
||||
::halfsiphash(in.data(), in.size(), key.data(), ret.data(), ret.size());
|
||||
else {
|
||||
auto skey = key.resized(8);
|
||||
::halfsiphash(in.data(), in.size(), skey.data(), ret.data(), ret.size());
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
31
libs/main/digest/pidigest_siphash_p.h
Normal file
31
libs/main/digest/pidigest_siphash_p.h
Normal file
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Digest algorithms
|
||||
Ivan Pelipenko peri4ko@yandex.ru
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Lesser General Public License as published by
|
||||
the Free Software Foundation, either version 3 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 Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef pidigest_siphash_h
|
||||
#define pidigest_siphash_h
|
||||
|
||||
#include "pibytearray.h"
|
||||
|
||||
class SipHash {
|
||||
public:
|
||||
static PIByteArray siphash(const PIByteArray & in, const PIByteArray & key, int out_bytes);
|
||||
static PIByteArray halfsiphash(const PIByteArray & in, const PIByteArray & key, int out_bytes);
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -1,9 +1,8 @@
|
||||
/*! \file piellipsoidmodel.h
|
||||
* \ingroup Geo
|
||||
* \~\brief
|
||||
* \~english Geographical ellipsoid Earth models
|
||||
* \~russian Географическая эллипсоидная модель Земли
|
||||
*/
|
||||
//! \~\ingroup Geo
|
||||
//! \~\file piellipsoidmodel.h
|
||||
//! \brief
|
||||
//! \~english Geographical ellipsoid Earth models
|
||||
//! \~russian Географическая эллипсоидная модель Земли
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Contains geo ellipsoid models
|
||||
@@ -29,21 +28,60 @@
|
||||
|
||||
#include "pimathbase.h"
|
||||
|
||||
//! \~\ingroup Geo
|
||||
//! \~\brief
|
||||
//! \~english Reference ellipsoid parameters used by geographic calculations.
|
||||
//! \~russian Параметры опорного эллипсоида для географических вычислений.
|
||||
//! \details
|
||||
//! \~english This module provides Earth ellipsoid models used in geodesy and navigation systems. It includes standard models like WGS84,
|
||||
//! PZ90, GPS, and Krasovskiy.
|
||||
//! \~russian Этот модуль предоставляет модели эллипсоидов Земли, используемые в геодезии и навигационных системах. Он включает стандартные
|
||||
//! модели WGS84, ПЗ-90, GPS и Красовского.
|
||||
class PIP_EXPORT PIEllipsoidModel {
|
||||
public:
|
||||
//! \~english Constructs an empty ellipsoid description.
|
||||
//! \~russian Создает пустое описание эллипсоида.
|
||||
PIEllipsoidModel();
|
||||
double eccSquared() const { return eccentricity * eccentricity; } // eccentricity squared
|
||||
|
||||
//! \~english Returns squared eccentricity.
|
||||
//! \~russian Возвращает квадрат эксцентриситета.
|
||||
double eccSquared() const { return eccentricity * eccentricity; }
|
||||
|
||||
//! \~english Returns semi-minor axis in meters.
|
||||
//! \~russian Возвращает малую полуось в метрах.
|
||||
double b() const { return a * sqrt(1 - eccSquared()); }
|
||||
|
||||
//! \~english Returns the WGS84 reference ellipsoid.
|
||||
//! \~russian Возвращает опорный эллипсоид WGS84.
|
||||
static PIEllipsoidModel WGS84Ellipsoid();
|
||||
|
||||
//! \~english Returns the PZ-90 reference ellipsoid.
|
||||
//! \~russian Возвращает опорный эллипсоид ПЗ-90.
|
||||
static PIEllipsoidModel PZ90Ellipsoid();
|
||||
|
||||
//! \~english Returns the GPS ellipsoid variant used by this module.
|
||||
//! \~russian Возвращает вариант GPS-эллипсоида, используемый в этом модуле.
|
||||
static PIEllipsoidModel GPSEllipsoid();
|
||||
|
||||
//! \~english Returns the Krasovskiy reference ellipsoid.
|
||||
//! \~russian Возвращает опорный эллипсоид Красовского.
|
||||
static PIEllipsoidModel KrasovskiyEllipsoid();
|
||||
|
||||
double a; /// Major axis of Earth in meters
|
||||
double flattening; /// Flattening (ellipsoid parameter)
|
||||
double eccentricity; /// Eccentricity (ellipsoid parameter)
|
||||
double angVelocity; /// Angular velocity of Earth in radians/sec
|
||||
//! \~english Semi-major axis in meters.
|
||||
//! \~russian Большая полуось в метрах.
|
||||
double a;
|
||||
|
||||
//! \~english Flattening coefficient.
|
||||
//! \~russian Коэффициент сжатия.
|
||||
double flattening;
|
||||
|
||||
//! \~english First eccentricity.
|
||||
//! \~russian Первый эксцентриситет.
|
||||
double eccentricity;
|
||||
|
||||
//! \~english Angular velocity in radians per second.
|
||||
//! \~russian Угловая скорость в радианах в секунду.
|
||||
double angVelocity;
|
||||
};
|
||||
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user