mirror of
https://github.com/openharmony/third_party_lz4.git
synced 2026-07-01 06:48:22 -04:00
@@ -4,6 +4,7 @@ unlz4
|
||||
lz4cat
|
||||
lz4c
|
||||
lz4c32
|
||||
lz4-nomt
|
||||
lz4-wlib
|
||||
datagen
|
||||
frametest
|
||||
|
||||
+51
-307
@@ -1,339 +1,83 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 2, June 1991
|
||||
Full name:
|
||||
GNU General Public License v2.0 or later
|
||||
|
||||
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
Short identifier:
|
||||
GPL-2.0-or-later
|
||||
|
||||
Preamble
|
||||
Text:
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 2, June 1991
|
||||
|
||||
The licenses for most software are designed to take away your
|
||||
freedom to share and change it. By contrast, the GNU General Public
|
||||
License is intended to guarantee your freedom to share and change free
|
||||
software--to make sure the software is free for all its users. This
|
||||
General Public License applies to most of the Free Software
|
||||
Foundation's software and to any other program whose authors commit to
|
||||
using it. (Some other Free Software Foundation software is covered by
|
||||
the GNU Lesser General Public License instead.) You can apply it to
|
||||
your programs, too.
|
||||
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
this service if you wish), that you receive source code or can get it
|
||||
if you want it, that you can change the software or use pieces of it
|
||||
in new free programs; and that you know you can do these things.
|
||||
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid
|
||||
anyone to deny you these rights or to ask you to surrender the rights.
|
||||
These restrictions translate to certain responsibilities for you if you
|
||||
distribute copies of the software, or if you modify it.
|
||||
Preamble
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must give the recipients all the rights that
|
||||
you have. You must make sure that they, too, receive or can get the
|
||||
source code. And you must show them these terms so they know their
|
||||
rights.
|
||||
The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too.
|
||||
|
||||
We protect your rights with two steps: (1) copyright the software, and
|
||||
(2) offer you this license which gives you legal permission to copy,
|
||||
distribute and/or modify the software.
|
||||
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.
|
||||
|
||||
Also, for each author's protection and ours, we want to make certain
|
||||
that everyone understands that there is no warranty for this free
|
||||
software. If the software is modified by someone else and passed on, we
|
||||
want its recipients to know that what they have is not the original, so
|
||||
that any problems introduced by others will not reflect on the original
|
||||
authors' reputations.
|
||||
To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.
|
||||
|
||||
Finally, any free program is threatened constantly by software
|
||||
patents. We wish to avoid the danger that redistributors of a free
|
||||
program will individually obtain patent licenses, in effect making the
|
||||
program proprietary. To prevent this, we have made it clear that any
|
||||
patent must be licensed for everyone's free use or not licensed at all.
|
||||
For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.
|
||||
|
||||
0. This License applies to any program or other work which contains
|
||||
a notice placed by the copyright holder saying it may be distributed
|
||||
under the terms of this General Public License. The "Program", below,
|
||||
refers to any such program or work, and a "work based on the Program"
|
||||
means either the Program or any derivative work under copyright law:
|
||||
that is to say, a work containing the Program or a portion of it,
|
||||
either verbatim or with modifications and/or translated into another
|
||||
language. (Hereinafter, translation is included without limitation in
|
||||
the term "modification".) Each licensee is addressed as "you".
|
||||
Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.
|
||||
|
||||
Activities other than copying, distribution and modification are not
|
||||
covered by this License; they are outside its scope. The act of
|
||||
running the Program is not restricted, and the output from the Program
|
||||
is covered only if its contents constitute a work based on the
|
||||
Program (independent of having been made by running the Program).
|
||||
Whether that is true depends on what the Program does.
|
||||
The precise terms and conditions for copying, distribution and modification follow.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Program's
|
||||
source code as you receive it, in any medium, provided that you
|
||||
conspicuously and appropriately publish on each copy an appropriate
|
||||
copyright notice and disclaimer of warranty; keep intact all the
|
||||
notices that refer to this License and to the absence of any warranty;
|
||||
and give any other recipients of the Program a copy of this License
|
||||
along with the Program.
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy, and
|
||||
you may at your option offer warranty protection in exchange for a fee.
|
||||
0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".
|
||||
Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
|
||||
|
||||
2. You may modify your copy or copies of the Program or any portion
|
||||
of it, thus forming a work based on the Program, and copy and
|
||||
distribute such modifications or work under the terms of Section 1
|
||||
above, provided that you also meet all of these conditions:
|
||||
1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.
|
||||
You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
|
||||
|
||||
a) You must cause the modified files to carry prominent notices
|
||||
stating that you changed the files and the date of any change.
|
||||
2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
|
||||
a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
|
||||
b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
|
||||
c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
|
||||
These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
|
||||
|
||||
b) You must cause any work that you distribute or publish, that in
|
||||
whole or in part contains or is derived from the Program or any
|
||||
part thereof, to be licensed as a whole at no charge to all third
|
||||
parties under the terms of this License.
|
||||
Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.
|
||||
|
||||
c) If the modified program normally reads commands interactively
|
||||
when run, you must cause it, when started running for such
|
||||
interactive use in the most ordinary way, to print or display an
|
||||
announcement including an appropriate copyright notice and a
|
||||
notice that there is no warranty (or else, saying that you provide
|
||||
a warranty) and that users may redistribute the program under
|
||||
these conditions, and telling the user how to view a copy of this
|
||||
License. (Exception: if the Program itself is interactive but
|
||||
does not normally print such an announcement, your work based on
|
||||
the Program is not required to print an announcement.)
|
||||
In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
|
||||
|
||||
These requirements apply to the modified work as a whole. If
|
||||
identifiable sections of that work are not derived from the Program,
|
||||
and can be reasonably considered independent and separate works in
|
||||
themselves, then this License, and its terms, do not apply to those
|
||||
sections when you distribute them as separate works. But when you
|
||||
distribute the same sections as part of a whole which is a work based
|
||||
on the Program, the distribution of the whole must be on the terms of
|
||||
this License, whose permissions for other licensees extend to the
|
||||
entire whole, and thus to each and every part regardless of who wrote it.
|
||||
3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
|
||||
a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
|
||||
b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
|
||||
c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
|
||||
The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest
|
||||
your rights to work written entirely by you; rather, the intent is to
|
||||
exercise the right to control the distribution of derivative or
|
||||
collective works based on the Program.
|
||||
If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Program
|
||||
with the Program (or with a work based on the Program) on a volume of
|
||||
a storage or distribution medium does not bring the other work under
|
||||
the scope of this License.
|
||||
4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
|
||||
|
||||
3. You may copy and distribute the Program (or a work based on it,
|
||||
under Section 2) in object code or executable form under the terms of
|
||||
Sections 1 and 2 above provided that you also do one of the following:
|
||||
5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
|
||||
|
||||
a) Accompany it with the complete corresponding machine-readable
|
||||
source code, which must be distributed under the terms of Sections
|
||||
1 and 2 above on a medium customarily used for software interchange; or,
|
||||
6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
|
||||
|
||||
b) Accompany it with a written offer, valid for at least three
|
||||
years, to give any third party, for a charge no more than your
|
||||
cost of physically performing source distribution, a complete
|
||||
machine-readable copy of the corresponding source code, to be
|
||||
distributed under the terms of Sections 1 and 2 above on a medium
|
||||
customarily used for software interchange; or,
|
||||
7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.
|
||||
If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.
|
||||
|
||||
c) Accompany it with the information you received as to the offer
|
||||
to distribute corresponding source code. (This alternative is
|
||||
allowed only for noncommercial distribution and only if you
|
||||
received the program in object code or executable form with such
|
||||
an offer, in accord with Subsection b above.)
|
||||
It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
|
||||
|
||||
The source code for a work means the preferred form of the work for
|
||||
making modifications to it. For an executable work, complete source
|
||||
code means all the source code for all modules it contains, plus any
|
||||
associated interface definition files, plus the scripts used to
|
||||
control compilation and installation of the executable. However, as a
|
||||
special exception, the source code distributed need not include
|
||||
anything that is normally distributed (in either source or binary
|
||||
form) with the major components (compiler, kernel, and so on) of the
|
||||
operating system on which the executable runs, unless that component
|
||||
itself accompanies the executable.
|
||||
This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
|
||||
|
||||
If distribution of executable or object code is made by offering
|
||||
access to copy from a designated place, then offering equivalent
|
||||
access to copy the source code from the same place counts as
|
||||
distribution of the source code, even though third parties are not
|
||||
compelled to copy the source along with the object code.
|
||||
8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
|
||||
|
||||
4. You may not copy, modify, sublicense, or distribute the Program
|
||||
except as expressly provided under this License. Any attempt
|
||||
otherwise to copy, modify, sublicense or distribute the Program is
|
||||
void, and will automatically terminate your rights under this License.
|
||||
However, parties who have received copies, or rights, from you under
|
||||
this License will not have their licenses terminated so long as such
|
||||
parties remain in full compliance.
|
||||
9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
|
||||
Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
|
||||
|
||||
5. You are not required to accept this License, since you have not
|
||||
signed it. However, nothing else grants you permission to modify or
|
||||
distribute the Program or its derivative works. These actions are
|
||||
prohibited by law if you do not accept this License. Therefore, by
|
||||
modifying or distributing the Program (or any work based on the
|
||||
Program), you indicate your acceptance of this License to do so, and
|
||||
all its terms and conditions for copying, distributing or modifying
|
||||
the Program or works based on it.
|
||||
10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
|
||||
NO WARRANTY
|
||||
|
||||
6. Each time you redistribute the Program (or any work based on the
|
||||
Program), the recipient automatically receives a license from the
|
||||
original licensor to copy, distribute or modify the Program subject to
|
||||
these terms and conditions. You may not impose any further
|
||||
restrictions on the recipients' exercise of the rights granted herein.
|
||||
You are not responsible for enforcing compliance by third parties to
|
||||
this License.
|
||||
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
7. If, as a consequence of a court judgment or allegation of patent
|
||||
infringement or for any other reason (not limited to patent issues),
|
||||
conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot
|
||||
distribute so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you
|
||||
may not distribute the Program at all. For example, if a patent
|
||||
license would not permit royalty-free redistribution of the Program by
|
||||
all those who receive copies directly or indirectly through you, then
|
||||
the only way you could satisfy both it and this License would be to
|
||||
refrain entirely from distribution of the Program.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under
|
||||
any particular circumstance, the balance of the section is intended to
|
||||
apply and the section as a whole is intended to apply in other
|
||||
circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any
|
||||
patents or other property right claims or to contest validity of any
|
||||
such claims; this section has the sole purpose of protecting the
|
||||
integrity of the free software distribution system, which is
|
||||
implemented by public license practices. Many people have made
|
||||
generous contributions to the wide range of software distributed
|
||||
through that system in reliance on consistent application of that
|
||||
system; it is up to the author/donor to decide if he or she is willing
|
||||
to distribute software through any other system and a licensee cannot
|
||||
impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to
|
||||
be a consequence of the rest of this License.
|
||||
|
||||
8. If the distribution and/or use of the Program is restricted in
|
||||
certain countries either by patents or by copyrighted interfaces, the
|
||||
original copyright holder who places the Program under this License
|
||||
may add an explicit geographical distribution limitation excluding
|
||||
those countries, so that distribution is permitted only in or among
|
||||
countries not thus excluded. In such case, this License incorporates
|
||||
the limitation as if written in the body of this License.
|
||||
|
||||
9. The Free Software Foundation may publish revised and/or new versions
|
||||
of the General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program
|
||||
specifies a version number of this License which applies to it and "any
|
||||
later version", you have the option of following the terms and conditions
|
||||
either of that version or of any later version published by the Free
|
||||
Software Foundation. If the Program does not specify a version number of
|
||||
this License, you may choose any version ever published by the Free Software
|
||||
Foundation.
|
||||
|
||||
10. If you wish to incorporate parts of the Program into other free
|
||||
programs whose distribution conditions are different, write to the author
|
||||
to ask for permission. For software which is copyrighted by the Free
|
||||
Software Foundation, write to the Free Software Foundation; we sometimes
|
||||
make exceptions for this. Our decision will be guided by the two goals
|
||||
of preserving the free status of all derivatives of our free software and
|
||||
of promoting the sharing and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
|
||||
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
|
||||
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
|
||||
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
|
||||
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
|
||||
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
|
||||
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
|
||||
REPAIR OR CORRECTION.
|
||||
|
||||
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
|
||||
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
|
||||
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
|
||||
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
|
||||
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
|
||||
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
convey the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program is interactive, make it output a short notice like this
|
||||
when it starts in an interactive mode:
|
||||
|
||||
Gnomovision version 69, Copyright (C) year name of author
|
||||
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, the commands you use may
|
||||
be called something other than `show w' and `show c'; they could even be
|
||||
mouse-clicks or menu items--whatever suits your program.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or your
|
||||
school, if any, to sign a "copyright disclaimer" for the program, if
|
||||
necessary. Here is a sample; alter the names:
|
||||
|
||||
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
|
||||
`Gnomovision' (which makes passes at compilers) written by James Hacker.
|
||||
|
||||
<signature of Ty Coon>, 1 April 1989
|
||||
Ty Coon, President of Vice
|
||||
|
||||
This General Public License does not permit incorporating your program into
|
||||
proprietary programs. If your program is a subroutine library, you may
|
||||
consider it more useful to permit linking proprietary applications with the
|
||||
library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License.
|
||||
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
+76
-38
@@ -1,6 +1,6 @@
|
||||
# ##########################################################################
|
||||
# LZ4 programs - Makefile
|
||||
# Copyright (C) Yann Collet 2011-2020
|
||||
# Copyright (C) Yann Collet 2011-2023
|
||||
#
|
||||
# This Makefile is validated for Linux, macOS, *BSD, Hurd, Solaris, MSYS2 targets
|
||||
#
|
||||
@@ -28,30 +28,30 @@
|
||||
# lz4c : CLU, supporting also legacy lz4demo arguments
|
||||
# lz4c32: Same as lz4c, but forced to compile in 32-bits mode
|
||||
# ##########################################################################
|
||||
SED = sed
|
||||
SED ?= sed
|
||||
|
||||
# Version numbers
|
||||
LZ4DIR := ../lib
|
||||
LIBVER_SRC := $(LZ4DIR)/lz4.h
|
||||
LIBVER_MAJOR_SCRIPT:=`$(SED) -n '/define LZ4_VERSION_MAJOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LIBVER_SRC)`
|
||||
LIBVER_MINOR_SCRIPT:=`$(SED) -n '/define LZ4_VERSION_MINOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LIBVER_SRC)`
|
||||
LIBVER_PATCH_SCRIPT:=`$(SED) -n '/define LZ4_VERSION_RELEASE/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LIBVER_SRC)`
|
||||
LIBDIR := ../lib
|
||||
LIBVER_SRC := $(LIBDIR)/lz4.h
|
||||
LIBVER_MAJOR_SCRIPT:=`$(SED) -n '/define[[:blank:]][[:blank:]]*LZ4_VERSION_MAJOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LIBVER_SRC)`
|
||||
LIBVER_MINOR_SCRIPT:=`$(SED) -n '/define[[:blank:]][[:blank:]]*LZ4_VERSION_MINOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LIBVER_SRC)`
|
||||
LIBVER_PATCH_SCRIPT:=`$(SED) -n '/define[[:blank:]][[:blank:]]*LZ4_VERSION_RELEASE/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LIBVER_SRC)`
|
||||
LIBVER_SCRIPT:= $(LIBVER_MAJOR_SCRIPT).$(LIBVER_MINOR_SCRIPT).$(LIBVER_PATCH_SCRIPT)
|
||||
LIBVER_MAJOR := $(shell echo $(LIBVER_MAJOR_SCRIPT))
|
||||
LIBVER_MINOR := $(shell echo $(LIBVER_MINOR_SCRIPT))
|
||||
LIBVER_PATCH := $(shell echo $(LIBVER_PATCH_SCRIPT))
|
||||
LIBVER := $(shell echo $(LIBVER_SCRIPT))
|
||||
|
||||
LIBFILES = $(wildcard $(LZ4DIR)/*.c)
|
||||
LIBFILES = $(wildcard $(LIBDIR)/*.c)
|
||||
SRCFILES = $(sort $(LIBFILES) $(wildcard *.c))
|
||||
OBJFILES = $(SRCFILES:.c=.o)
|
||||
|
||||
CPPFLAGS += -I$(LZ4DIR) -DXXH_NAMESPACE=LZ4_
|
||||
CFLAGS ?= -O3
|
||||
DEBUGFLAGS= -Wall -Wextra -Wundef -Wcast-qual -Wcast-align -Wshadow \
|
||||
-Wswitch-enum -Wdeclaration-after-statement -Wstrict-prototypes \
|
||||
-Wpointer-arith -Wstrict-aliasing=1
|
||||
CFLAGS += $(DEBUGFLAGS) $(MOREFLAGS)
|
||||
USERCFLAGS:= -O3 $(CFLAGS) # -O3 can be overruled by user-provided -Ox level
|
||||
CFLAGS = $(DEBUGFLAGS) $(USERCFLAGS)
|
||||
CPPFLAGS += -I$(LIBDIR) -DXXH_NAMESPACE=LZ4_
|
||||
|
||||
include ../Makefile.inc
|
||||
|
||||
@@ -60,20 +60,37 @@ ifeq ($(TARGET_OS)$(shell $(OS_VERSION)),SunOS5.10)
|
||||
LDFLAGS += -lrt
|
||||
endif
|
||||
|
||||
FLAGS = $(CFLAGS) $(CPPFLAGS) $(LDFLAGS)
|
||||
ALLFLAGS = $(CFLAGS) $(CPPFLAGS) $(LDFLAGS)
|
||||
|
||||
# thread detection
|
||||
NUM_SYMBOL := \#
|
||||
NO_THREAD_MSG:= ==> no multithread support: building for single-thread mode only
|
||||
HAVE_PTHREAD := $(shell printf '$(NUM_SYMBOL)include <pthread.h>\nint main(void) { return 0; }' > have_pthread.c && $(CC) $(ALLFLAGS) -o have_pthread$(EXT) have_pthread.c -pthread 2> $(VOID) && rm -f have_pthread$(EXT) && echo 1 || echo 0; rm have_pthread.c)
|
||||
HAVE_MULTITHREAD := $(shell [ "$(HAVE_PTHREAD)" -eq "1" -o -n "$(filter Windows%,$(OS))" ] && echo 1 || echo 0)
|
||||
ifeq ($(HAVE_MULTITHREAD), 1)
|
||||
THREAD_MSG := ==> building with multithreading support
|
||||
THREAD_CPP := -DLZ4IO_MULTITHREAD
|
||||
ifeq ($(HAVE_PTHREAD), 1)
|
||||
THREAD_LD := -pthread
|
||||
endif
|
||||
else
|
||||
THREAD_MSG := $(NO_THREAD_MSG)
|
||||
endif
|
||||
|
||||
LZ4_VERSION=$(LIBVER)
|
||||
MD2ROFF = ronn
|
||||
MD2ROFF = ronn
|
||||
MD2ROFF_FLAGS = --roff --warnings --manual="User Commands" --organization="lz4 $(LZ4_VERSION)"
|
||||
|
||||
|
||||
.PHONY:default
|
||||
default: lz4-release
|
||||
|
||||
# silent mode by default; verbose can be triggered by V=1 or VERBOSE=1
|
||||
$(V)$(VERBOSE).SILENT:
|
||||
|
||||
all: lz4 lz4c
|
||||
.PHONY:all
|
||||
all: lz4 lz4-nomt lz4c unlz4 lz4cat
|
||||
|
||||
.PHONY:all32
|
||||
all32: CFLAGS+=-m32
|
||||
all32: all
|
||||
|
||||
@@ -81,64 +98,89 @@ ifeq ($(WINBASED),yes)
|
||||
lz4-exe.rc: lz4-exe.rc.in
|
||||
@echo creating executable resource
|
||||
$(SED) -e 's|@PROGNAME@|lz4|' \
|
||||
-e 's|@LIBVER_MAJOR@|$(LIBVER_MAJOR)|g' \
|
||||
-e 's|@LIBVER_MINOR@|$(LIBVER_MINOR)|g' \
|
||||
-e 's|@LIBVER_PATCH@|$(LIBVER_PATCH)|g' \
|
||||
-e 's|@EXT@|$(EXT)|g' \
|
||||
$< >$@
|
||||
-e 's|@LIBVER_MAJOR@|$(LIBVER_MAJOR)|g' \
|
||||
-e 's|@LIBVER_MINOR@|$(LIBVER_MINOR)|g' \
|
||||
-e 's|@LIBVER_PATCH@|$(LIBVER_PATCH)|g' \
|
||||
-e 's|@EXT@|.exe|g' \
|
||||
$< >$@
|
||||
|
||||
lz4-exe.o: lz4-exe.rc
|
||||
$(WINDRES) -i lz4-exe.rc -o lz4-exe.o
|
||||
|
||||
lz4: CPPFLAGS += $(THREAD_CPP)
|
||||
lz4: LDFLAGS += $(THREAD_LD)
|
||||
lz4: $(OBJFILES) lz4-exe.o
|
||||
$(CC) $(FLAGS) $^ -o $@$(EXT)
|
||||
echo "$(THREAD_MSG)"
|
||||
$(CC) $(ALLFLAGS) $^ -o $@$(EXT)
|
||||
else
|
||||
lz4: CPPFLAGS += $(THREAD_CPP)
|
||||
lz4: LDFLAGS += $(THREAD_LD)
|
||||
lz4: $(OBJFILES)
|
||||
$(CC) $(FLAGS) $(OBJFILES) -o $@$(EXT) $(LDLIBS)
|
||||
echo "$(THREAD_MSG)"
|
||||
$(CC) $(ALLFLAGS) $(OBJFILES) -o $@$(EXT) $(LDLIBS)
|
||||
endif
|
||||
CLEAN += lz4
|
||||
|
||||
.PHONY: lz4-release
|
||||
lz4-release: DEBUGFLAGS=
|
||||
lz4-release: CPPFLAGS+=-DNDEBUG
|
||||
lz4-release: lz4
|
||||
|
||||
CLEAN += lz4-nomt
|
||||
lz4-nomt: $(SRCFILES)
|
||||
$(CC) $(ALLFLAGS) $^ -o $@$(EXT)
|
||||
|
||||
CLEAN += lz4-wlib
|
||||
lz4-wlib: LIBFILES =
|
||||
lz4-wlib: SRCFILES+= $(LZ4DIR)/xxhash.c # benchmark unit needs XXH64()
|
||||
lz4-wlib: LDFLAGS += -L $(LZ4DIR)
|
||||
lz4-wlib: SRCFILES+= $(LIBDIR)/xxhash.c # benchmark unit needs XXH64()
|
||||
lz4-wlib: LDFLAGS += -L $(LIBDIR)
|
||||
lz4-wlib: LDLIBS = -llz4
|
||||
lz4-wlib: liblz4 $(OBJFILES)
|
||||
@echo WARNING: $@ must link to an extended variant of the dynamic library which also exposes unstable symbols
|
||||
$(CC) $(FLAGS) $(OBJFILES) -o $@$(EXT) $(LDLIBS)
|
||||
$(CC) $(ALLFLAGS) $(OBJFILES) -o $@$(EXT) $(LDLIBS)
|
||||
|
||||
.PHONY:liblz4
|
||||
liblz4:
|
||||
CPPFLAGS="-DLZ4F_PUBLISH_STATIC_FUNCTIONS -DLZ4_PUBLISH_STATIC_FUNCTIONS" $(MAKE) -C $(LZ4DIR) liblz4
|
||||
CPPFLAGS="-DLZ4F_PUBLISH_STATIC_FUNCTIONS -DLZ4_PUBLISH_STATIC_FUNCTIONS" $(MAKE) -C $(LIBDIR) liblz4
|
||||
|
||||
CLEAN += lz4c
|
||||
lz4c: lz4
|
||||
$(LN_SF) lz4$(EXT) lz4c$(EXT)
|
||||
|
||||
CLEAN += lz4c32
|
||||
lz4c32: CFLAGS += -m32
|
||||
lz4c32 : $(SRCFILES)
|
||||
$(CC) $(FLAGS) $^ -o $@$(EXT)
|
||||
$(CC) $(ALLFLAGS) $^ -o $@$(EXT)
|
||||
|
||||
CLEAN += unlz4
|
||||
unlz4: lz4
|
||||
$(LN_SF) lz4$(EXT) unlz4$(EXT)
|
||||
|
||||
CLEAN += lz4cat
|
||||
lz4cat: lz4
|
||||
$(LN_SF) lz4$(EXT) lz4cat$(EXT)
|
||||
|
||||
lz4.1: lz4.1.md $(LIBVER_SRC)
|
||||
cat $< | $(MD2ROFF) $(MD2ROFF_FLAGS) | $(SED) -n '/^\.\\\".*/!p' > $@
|
||||
|
||||
.PHONY:man
|
||||
man: lz4.1
|
||||
|
||||
.PHONY:clean-man
|
||||
clean-man:
|
||||
$(RM) lz4.1
|
||||
|
||||
.PHONY:preview-man
|
||||
preview-man: clean-man man
|
||||
man ./lz4.1
|
||||
|
||||
.PHONY:clean
|
||||
clean:
|
||||
ifeq ($(WINBASED),yes)
|
||||
$(RM) *.rc
|
||||
endif
|
||||
$(MAKE) -C $(LZ4DIR) $@ > $(VOID)
|
||||
$(RM) core *.o *.test tmp* \
|
||||
lz4$(EXT) lz4c$(EXT) lz4c32$(EXT) lz4-wlib$(EXT) \
|
||||
unlz4$(EXT) lz4cat$(EXT)
|
||||
$(MAKE) -C $(LIBDIR) $@ > $(VOID)
|
||||
$(RM) $(CLEAN) *.o tmp* *.test core
|
||||
@echo Cleaning completed
|
||||
|
||||
|
||||
@@ -147,12 +189,6 @@ endif
|
||||
#-----------------------------------------------------------------------------
|
||||
ifeq ($(POSIX_ENV),Yes)
|
||||
|
||||
unlz4: lz4
|
||||
$(LN_SF) lz4$(EXT) unlz4$(EXT)
|
||||
|
||||
lz4cat: lz4
|
||||
$(LN_SF) lz4$(EXT) lz4cat$(EXT)
|
||||
|
||||
DESTDIR ?=
|
||||
# directory variables : GNU conventions prefer lowercase
|
||||
# see https://www.gnu.org/prep/standards/html_node/Makefile-Conventions.html
|
||||
@@ -170,9 +206,10 @@ mandir ?= $(MANDIR)
|
||||
MAN1DIR ?= $(mandir)/man1
|
||||
man1dir ?= $(MAN1DIR)
|
||||
|
||||
.PHONY: install
|
||||
install: lz4
|
||||
@echo Installing binaries in $(DESTDIR)$(bindir)
|
||||
$(INSTALL_DIR) $(DESTDIR)$(bindir)/ $(DESTDIR)$(man1dir)/
|
||||
$(MAKE_DIR) $(DESTDIR)$(bindir)/ $(DESTDIR)$(man1dir)/
|
||||
$(INSTALL_PROGRAM) lz4$(EXT) $(DESTDIR)$(bindir)/lz4$(EXT)
|
||||
$(LN_SF) lz4$(EXT) $(DESTDIR)$(bindir)/lz4c$(EXT)
|
||||
$(LN_SF) lz4$(EXT) $(DESTDIR)$(bindir)/lz4cat$(EXT)
|
||||
@@ -184,6 +221,7 @@ install: lz4
|
||||
$(LN_SF) lz4.1 $(DESTDIR)$(man1dir)/unlz4.1
|
||||
@echo lz4 installation completed
|
||||
|
||||
.PHONY: uninstall
|
||||
uninstall:
|
||||
$(RM) $(DESTDIR)$(bindir)/lz4cat$(EXT)
|
||||
$(RM) $(DESTDIR)$(bindir)/unlz4$(EXT)
|
||||
|
||||
+52
-22
@@ -2,38 +2,68 @@ Command Line Interface for LZ4 library
|
||||
============================================
|
||||
|
||||
### Build
|
||||
The Command Line Interface (CLI) can be generated
|
||||
using the `make` command without any additional parameters.
|
||||
|
||||
The `Makefile` script supports all [standard conventions](https://www.gnu.org/prep/standards/html_node/Makefile-Conventions.html),
|
||||
including standard targets (`all`, `install`, `clean`, etc.)
|
||||
and standard variables (`CC`, `CFLAGS`, `CPPFLAGS`, etc.).
|
||||
|
||||
For advanced use cases, there are targets to different variations of the CLI:
|
||||
- `lz4` : default CLI, with a command line syntax close to gzip
|
||||
- `lz4c` : Same as `lz4` with additional support legacy lz4 commands (incompatible with gzip)
|
||||
- `lz4c32` : Same as `lz4c`, but forced to compile in 32-bits mode
|
||||
The `lz4` Command Line Interface (CLI) is generated
|
||||
using the `make` command, no additional parameter required.
|
||||
|
||||
The CLI generates and decodes [LZ4-compressed frames](../doc/lz4_Frame_format.md).
|
||||
|
||||
For more control over the build process,
|
||||
the `Makefile` script supports all [standard conventions](https://www.gnu.org/prep/standards/html_node/Makefile-Conventions.html),
|
||||
including standard targets (`all`, `install`, `clean`, etc.)
|
||||
and standard variables (`CC`, `CFLAGS`, `CPPFLAGS`, etc.).
|
||||
|
||||
#### Aggregation of parameters
|
||||
CLI supports aggregation of parameters i.e. `-b1`, `-e18`, and `-i1` can be joined into `-b1e18i1`.
|
||||
The makefile offer several targets for various use cases:
|
||||
- `lz4` : default CLI, with a command line syntax similar to gzip
|
||||
- `lz4c` : supports legacy lz4 commands (incompatible with gzip)
|
||||
- `lz4c32` : Same as `lz4c`, but generates a 32-bits executable
|
||||
- `unlz4`, `lz4cat` : symlinks to `lz4`, default to decompression and `cat` compressed files
|
||||
- `man` : generates the man page, from `lz4.1.md` markdown source
|
||||
|
||||
#### Makefile Build variables
|
||||
- `HAVE_MULTITHREAD` : build with multithreading support. Detection is generally automatic, but can be forced to `0` or `1` if needed. This is for example useful when cross-compiling for Windows from Linux.
|
||||
- `HAVE_PTHREAD` : determines presence of `<pthread>` support. Detection is automatic, but can be forced to `0` or `1` if needed. This is in turn used by `make` to automatically trigger multithreading support.
|
||||
|
||||
#### C Preprocessor Build variables
|
||||
These variables are read by the preprocessor at compilation time. They influence executable behavior, such as default starting values, and are exposed from `programs/lz4conf.h`. These variables can manipulated by any build system.
|
||||
Assignment methods vary depending on environments.
|
||||
On a typical `posix` + `gcc` + `make` setup, they can be defined with `CPPFLAGS=-DVARIABLE=value` assignment.
|
||||
- `LZ4_CLEVEL_DEFAULT`: default compression level when none provided. Default is `1`.
|
||||
- `LZ4IO_MULTITHREAD`: enable multithreading support. Default is disabled.
|
||||
- `LZ4_NBWORKERS_DEFAULT`: default nb of worker threads used in multithreading mode (can be overridden with command `-T#`).
|
||||
Default is `0`, which means "auto-determine" based on local cpu.
|
||||
- `LZ4_NBWORKERS_MAX`: absolute maximum nb of workers that can be requested at runtime.
|
||||
Currently set to 200 by default.
|
||||
This is mostly meant to protect the system against unreasonable and likely bogus requests, such as a million threads.
|
||||
- `LZ4_BLOCKSIZEID_DEFAULT`: default `lz4` block size code. Valid values are [4-7], corresponding to 64 KB, 256 KB, 1 MB and 4 MB. At the time of this writing, default is 7, corresponding to 4 MB block size.
|
||||
|
||||
#### Environment Variables
|
||||
It's possible to pass some parameters to `lz4` via environment variables.
|
||||
This can be useful in situations where `lz4` is known to be invoked (from within a script for example) but there is no way to pass `lz4` parameters to influence the compression session.
|
||||
The environment variable has higher priority than binary default, but lower priority than corresponding runtime command.
|
||||
When set as global environment variables, it can enforce personalized defaults different from the binary set ones.
|
||||
|
||||
`LZ4_CLEVEL` can be used to specify a default compression level that `lz4` employs for compression when no other compression level is specified on command line. Executable default is generally `1`.
|
||||
|
||||
`LZ4_NBWORKERS` can be used to specify a default number of threads that `lz4` will employ for compression. Executable default is generally `0`, which means auto-determined based on local cpu. This functionality is only relevant when `lz4` is compiled with multithreading support. The maximum number of workers is capped at `LZ4_NBWORKERS_MAX` (`200` by default).
|
||||
|
||||
### Aggregation of parameters
|
||||
The `lz4` CLI supports aggregation for short commands. For example, `-d`, `-q`, and `-f` can be joined into `-dqf`.
|
||||
Aggregation doesn't work for `--long-commands`, which **must** be separated.
|
||||
|
||||
|
||||
#### Benchmark in Command Line Interface
|
||||
CLI includes in-memory compression benchmark module for lz4.
|
||||
The benchmark is conducted using a given filename.
|
||||
The file is read into memory.
|
||||
It makes benchmark more precise as it eliminates I/O overhead.
|
||||
### Benchmark in Command Line Interface
|
||||
`lz4` CLI includes an in-memory compression benchmark module, triggered by command `-b#`, with `#` representing the compression level.
|
||||
The benchmark is conducted on a provided list of filenames.
|
||||
The files are then read entirely into memory, to eliminate I/O overhead.
|
||||
When multiple files are provided, they are bundled into the same benchmark session (though each file is a separate compression / decompression). Using `-S` command separates them (one session per file).
|
||||
When no file is provided, uses an internal Lorem Ipsum generator instead.
|
||||
|
||||
The benchmark measures ratio, compressed size, compression and decompression speed.
|
||||
One can select compression levels starting from `-b` and ending with `-e`.
|
||||
The `-i` parameter selects a number of seconds used for each of tested levels.
|
||||
One can select multiple compression levels starting from `-b` and ending with `-e` (ascending).
|
||||
The `-i` parameter selects a number of seconds used for each session.
|
||||
|
||||
|
||||
|
||||
#### Usage of Command Line Interface
|
||||
### Usage of Command Line Interface
|
||||
The full list of commands can be obtained with `-h` or `-H` parameter:
|
||||
```
|
||||
Usage :
|
||||
|
||||
+122
-94
@@ -43,9 +43,10 @@
|
||||
#include <time.h> /* clock_t, clock, CLOCKS_PER_SEC */
|
||||
#include <assert.h> /* assert */
|
||||
|
||||
#include "datagen.h" /* RDG_genBuffer */
|
||||
#include "lorem.h" /* LOREM_genBuffer */
|
||||
#include "xxhash.h"
|
||||
#include "bench.h"
|
||||
#include "timefn.h"
|
||||
|
||||
#define LZ4_STATIC_LINKING_ONLY
|
||||
#include "lz4.h"
|
||||
@@ -66,7 +67,7 @@
|
||||
#define NBSECONDS 3
|
||||
#define TIMELOOP_MICROSEC 1*1000000ULL /* 1 second */
|
||||
#define TIMELOOP_NANOSEC 1*1000000000ULL /* 1 second */
|
||||
#define ACTIVEPERIOD_MICROSEC 70*1000000ULL /* 70 seconds */
|
||||
#define ACTIVEPERIOD_NANOSEC 70*1000000000ULL /* 70 seconds */
|
||||
#define COOLPERIOD_SEC 10
|
||||
#define DECOMP_MULT 1 /* test decompression DECOMP_MULT times longer than compression */
|
||||
|
||||
@@ -78,14 +79,14 @@
|
||||
|
||||
static const size_t maxMemory = (sizeof(size_t)==4) ? (2 GB - 64 MB) : (size_t)(1ULL << ((sizeof(size_t)*8)-31));
|
||||
|
||||
static U32 g_compressibilityDefault = 50;
|
||||
|
||||
|
||||
/* *************************************
|
||||
* console display
|
||||
***************************************/
|
||||
#define DISPLAYOUT(...) fprintf(stdout, __VA_ARGS__)
|
||||
#define OUTLEVEL(l, ...) if (g_displayLevel>=(l)) { DISPLAYOUT(__VA_ARGS__); }
|
||||
#define DISPLAY(...) fprintf(stderr, __VA_ARGS__)
|
||||
#define DISPLAYLEVEL(l, ...) if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); }
|
||||
#define DISPLAYLEVEL(l, ...) if (g_displayLevel>=(l)) { DISPLAY(__VA_ARGS__); }
|
||||
static U32 g_displayLevel = 2; /* 0 : no display; 1: errors; 2 : + result + interaction + warnings; 3 : + progression; 4 : + information */
|
||||
|
||||
#define DISPLAYUPDATE(l, ...) if (g_displayLevel>=l) { \
|
||||
@@ -103,14 +104,14 @@ static clock_t g_time = 0;
|
||||
# define DEBUG 0
|
||||
#endif
|
||||
#define DEBUGOUTPUT(...) if (DEBUG) DISPLAY(__VA_ARGS__);
|
||||
#define END_PROCESS(error, ...) \
|
||||
{ \
|
||||
#define END_PROCESS(error, ...) \
|
||||
do { \
|
||||
DEBUGOUTPUT("Error defined at %s, line %i : \n", __FILE__, __LINE__); \
|
||||
DISPLAYLEVEL(1, "Error %i : ", error); \
|
||||
DISPLAYLEVEL(1, __VA_ARGS__); \
|
||||
DISPLAYLEVEL(1, "\n"); \
|
||||
exit(error); \
|
||||
}
|
||||
} while (0)
|
||||
|
||||
#define LZ4_isError(errcode) (errcode==0)
|
||||
|
||||
@@ -186,7 +187,7 @@ LZ4_compressInitStream(struct compressionParameters* pThis)
|
||||
pThis->LZ4_dictStream = LZ4_createStream();
|
||||
pThis->LZ4_streamHC = NULL;
|
||||
pThis->LZ4_dictStreamHC = NULL;
|
||||
LZ4_loadDict(pThis->LZ4_dictStream, pThis->dictBuf, pThis->dictSize);
|
||||
LZ4_loadDictSlow(pThis->LZ4_dictStream, pThis->dictBuf, pThis->dictSize);
|
||||
}
|
||||
|
||||
static void
|
||||
@@ -196,81 +197,84 @@ LZ4_compressInitStreamHC(struct compressionParameters* pThis)
|
||||
pThis->LZ4_dictStream = NULL;
|
||||
pThis->LZ4_streamHC = LZ4_createStreamHC();
|
||||
pThis->LZ4_dictStreamHC = LZ4_createStreamHC();
|
||||
LZ4_resetStreamHC_fast(pThis->LZ4_dictStreamHC, pThis->cLevel);
|
||||
LZ4_loadDictHC(pThis->LZ4_dictStreamHC, pThis->dictBuf, pThis->dictSize);
|
||||
}
|
||||
|
||||
static void
|
||||
LZ4_compressResetNoStream(const struct compressionParameters* pThis)
|
||||
LZ4_compressResetNoStream(const struct compressionParameters* cparams)
|
||||
{
|
||||
(void)pThis;
|
||||
(void)cparams;
|
||||
}
|
||||
|
||||
static void
|
||||
LZ4_compressResetStream(const struct compressionParameters* pThis)
|
||||
LZ4_compressResetStream(const struct compressionParameters* cparams)
|
||||
{
|
||||
LZ4_resetStream_fast(pThis->LZ4_stream);
|
||||
LZ4_attach_dictionary(pThis->LZ4_stream, pThis->LZ4_dictStream);
|
||||
LZ4_resetStream_fast(cparams->LZ4_stream);
|
||||
LZ4_attach_dictionary(cparams->LZ4_stream, cparams->LZ4_dictStream);
|
||||
}
|
||||
|
||||
static void
|
||||
LZ4_compressResetStreamHC(const struct compressionParameters* pThis)
|
||||
LZ4_compressResetStreamHC(const struct compressionParameters* cparams)
|
||||
{
|
||||
LZ4_resetStreamHC_fast(pThis->LZ4_streamHC, pThis->cLevel);
|
||||
LZ4_attach_HC_dictionary(pThis->LZ4_streamHC, pThis->LZ4_dictStreamHC);
|
||||
LZ4_resetStreamHC_fast(cparams->LZ4_streamHC, cparams->cLevel);
|
||||
LZ4_attach_HC_dictionary(cparams->LZ4_streamHC, cparams->LZ4_dictStreamHC);
|
||||
}
|
||||
|
||||
static int
|
||||
LZ4_compressBlockNoStream(const struct compressionParameters* pThis,
|
||||
LZ4_compressBlockNoStream(const struct compressionParameters* cparams,
|
||||
const char* src, char* dst,
|
||||
int srcSize, int dstSize)
|
||||
{
|
||||
int const acceleration = (pThis->cLevel < 0) ? -pThis->cLevel + 1 : 1;
|
||||
int const acceleration = (cparams->cLevel < 0) ? -cparams->cLevel + 1 : 1;
|
||||
return LZ4_compress_fast(src, dst, srcSize, dstSize, acceleration);
|
||||
}
|
||||
|
||||
static int
|
||||
LZ4_compressBlockNoStreamHC(const struct compressionParameters* pThis,
|
||||
LZ4_compressBlockNoStreamHC(const struct compressionParameters* cparams,
|
||||
const char* src, char* dst,
|
||||
int srcSize, int dstSize)
|
||||
{
|
||||
return LZ4_compress_HC(src, dst, srcSize, dstSize, pThis->cLevel);
|
||||
return LZ4_compress_HC(src, dst, srcSize, dstSize, cparams->cLevel);
|
||||
}
|
||||
|
||||
static int
|
||||
LZ4_compressBlockStream(const struct compressionParameters* pThis,
|
||||
LZ4_compressBlockStream(const struct compressionParameters* cparams,
|
||||
const char* src, char* dst,
|
||||
int srcSize, int dstSize)
|
||||
{
|
||||
int const acceleration = (pThis->cLevel < 0) ? -pThis->cLevel + 1 : 1;
|
||||
return LZ4_compress_fast_continue(pThis->LZ4_stream, src, dst, srcSize, dstSize, acceleration);
|
||||
int const acceleration = (cparams->cLevel < 0) ? -cparams->cLevel + 1 : 1;
|
||||
LZ4_compressResetStream(cparams);
|
||||
return LZ4_compress_fast_continue(cparams->LZ4_stream, src, dst, srcSize, dstSize, acceleration);
|
||||
}
|
||||
|
||||
static int
|
||||
LZ4_compressBlockStreamHC(const struct compressionParameters* pThis,
|
||||
LZ4_compressBlockStreamHC(const struct compressionParameters* cparams,
|
||||
const char* src, char* dst,
|
||||
int srcSize, int dstSize)
|
||||
{
|
||||
return LZ4_compress_HC_continue(pThis->LZ4_streamHC, src, dst, srcSize, dstSize);
|
||||
LZ4_compressResetStreamHC(cparams);
|
||||
return LZ4_compress_HC_continue(cparams->LZ4_streamHC, src, dst, srcSize, dstSize);
|
||||
}
|
||||
|
||||
static void
|
||||
LZ4_compressCleanupNoStream(const struct compressionParameters* pThis)
|
||||
LZ4_compressCleanupNoStream(const struct compressionParameters* cparams)
|
||||
{
|
||||
(void)pThis;
|
||||
(void)cparams;
|
||||
}
|
||||
|
||||
static void
|
||||
LZ4_compressCleanupStream(const struct compressionParameters* pThis)
|
||||
LZ4_compressCleanupStream(const struct compressionParameters* cparams)
|
||||
{
|
||||
LZ4_freeStream(pThis->LZ4_stream);
|
||||
LZ4_freeStream(pThis->LZ4_dictStream);
|
||||
LZ4_freeStream(cparams->LZ4_stream);
|
||||
LZ4_freeStream(cparams->LZ4_dictStream);
|
||||
}
|
||||
|
||||
static void
|
||||
LZ4_compressCleanupStreamHC(const struct compressionParameters* pThis)
|
||||
LZ4_compressCleanupStreamHC(const struct compressionParameters* cparams)
|
||||
{
|
||||
LZ4_freeStreamHC(pThis->LZ4_streamHC);
|
||||
LZ4_freeStreamHC(pThis->LZ4_dictStreamHC);
|
||||
LZ4_freeStreamHC(cparams->LZ4_streamHC);
|
||||
LZ4_freeStreamHC(cparams->LZ4_dictStreamHC);
|
||||
}
|
||||
|
||||
static void
|
||||
@@ -367,6 +371,7 @@ static int BMK_benchMem(const void* srcBuffer, size_t srcSize,
|
||||
size_t const maxInSize = (size_t)LZ4_MAX_INPUT_SIZE / decMultiplier;
|
||||
size_t const maxDecSize = srcSize < maxInSize ? srcSize * decMultiplier : LZ4_MAX_INPUT_SIZE;
|
||||
void* const resultBuffer = malloc(maxDecSize);
|
||||
int benchError = 0;
|
||||
U32 nbBlocks;
|
||||
struct compressionParameters compP;
|
||||
|
||||
@@ -410,7 +415,7 @@ static int BMK_benchMem(const void* srcBuffer, size_t srcSize,
|
||||
} } }
|
||||
|
||||
/* warming up memory */
|
||||
RDG_genBuffer(compressedBuffer, maxCompressedSize, 0.10, 0.50, 1);
|
||||
memset(compressedBuffer, ' ', maxCompressedSize);
|
||||
|
||||
/* decode-only mode : copy input to @compressedBuffer */
|
||||
if (g_decodeOnly) {
|
||||
@@ -423,11 +428,11 @@ static int BMK_benchMem(const void* srcBuffer, size_t srcSize,
|
||||
/* Bench */
|
||||
{ U64 fastestC = (U64)(-1LL), fastestD = (U64)(-1LL);
|
||||
U64 const crcOrig = XXH64(srcBuffer, srcSize, 0);
|
||||
UTIL_time_t coolTime = UTIL_getTime();
|
||||
TIME_t coolTime = TIME_getTime();
|
||||
U64 const maxTime = (g_nbSeconds * TIMELOOP_NANOSEC) + 100;
|
||||
U32 nbCompressionLoops = (U32)((5 MB) / (srcSize+1)) + 1; /* conservative initial compression speed estimate */
|
||||
U32 nbDecodeLoops = (U32)((200 MB) / (srcSize+1)) + 1; /* conservative initial decode speed estimate */
|
||||
U64 totalCTime=0, totalDTime=0;
|
||||
Duration_ns totalCTime=0, totalDTime=0;
|
||||
U32 cCompleted=(g_decodeOnly==1), dCompleted=0;
|
||||
# define NB_MARKS 4
|
||||
const char* const marks[NB_MARKS] = { " |", " /", " =", "\\" };
|
||||
@@ -437,23 +442,27 @@ static int BMK_benchMem(const void* srcBuffer, size_t srcSize,
|
||||
double ratio = 0.;
|
||||
|
||||
DISPLAYLEVEL(2, "\r%79s\r", "");
|
||||
if (g_nbSeconds==0) { nbCompressionLoops = 1; nbDecodeLoops = 1; }
|
||||
while (!cCompleted || !dCompleted) {
|
||||
/* overheat protection */
|
||||
if (UTIL_clockSpanMicro(coolTime) > ACTIVEPERIOD_MICROSEC) {
|
||||
if (TIME_clockSpan_ns(coolTime) > ACTIVEPERIOD_NANOSEC) {
|
||||
DISPLAYLEVEL(2, "\rcooling down ... \r");
|
||||
UTIL_sleep(COOLPERIOD_SEC);
|
||||
coolTime = UTIL_getTime();
|
||||
coolTime = TIME_getTime();
|
||||
}
|
||||
|
||||
/* Compression */
|
||||
DISPLAYLEVEL(2, "%2s-%-17.17s :%10u ->\r", marks[markNb], displayName, (U32)totalRSize);
|
||||
if (!cCompleted) memset(compressedBuffer, 0xE5, maxCompressedSize); /* warm up and erase compressed buffer */
|
||||
if (!cCompleted) {
|
||||
memset(compressedBuffer, 0xE5, maxCompressedSize); /* warm up and erase compressed buffer */
|
||||
{ U32 blockNb; for (blockNb=0; blockNb<nbBlocks; blockNb++) blockTable[blockNb].cSize = 0; }
|
||||
}
|
||||
|
||||
UTIL_sleepMilli(1); /* give processor time to other processes */
|
||||
UTIL_waitForNextTick();
|
||||
TIME_waitForNextTick();
|
||||
|
||||
if (!cCompleted) { /* still some time to do compression tests */
|
||||
UTIL_time_t const clockStart = UTIL_getTime();
|
||||
TIME_t const timeStart = TIME_getTime();
|
||||
U32 nbLoops;
|
||||
for (nbLoops=0; nbLoops < nbCompressionLoops; nbLoops++) {
|
||||
U32 blockNb;
|
||||
@@ -463,20 +472,23 @@ static int BMK_benchMem(const void* srcBuffer, size_t srcSize,
|
||||
&compP,
|
||||
blockTable[blockNb].srcPtr, blockTable[blockNb].cPtr,
|
||||
(int)blockTable[blockNb].srcSize, (int)blockTable[blockNb].cRoom);
|
||||
if (LZ4_isError(rSize)) END_PROCESS(1, "LZ4 compression failed");
|
||||
if (LZ4_isError(rSize)) {
|
||||
DISPLAY("LZ4 compression failed on block %u \n", blockNb);
|
||||
benchError =1 ;
|
||||
}
|
||||
blockTable[blockNb].cSize = rSize;
|
||||
} }
|
||||
{ U64 const clockSpan = UTIL_clockSpanNano(clockStart);
|
||||
if (clockSpan > 0) {
|
||||
if (clockSpan < fastestC * nbCompressionLoops)
|
||||
fastestC = clockSpan / nbCompressionLoops;
|
||||
{ Duration_ns const duration_ns = TIME_clockSpan_ns(timeStart);
|
||||
if (duration_ns > 0) {
|
||||
if (duration_ns < fastestC * nbCompressionLoops)
|
||||
fastestC = duration_ns / nbCompressionLoops;
|
||||
assert(fastestC > 0);
|
||||
nbCompressionLoops = (U32)(TIMELOOP_NANOSEC / fastestC) + 1; /* aim for ~1sec */
|
||||
} else {
|
||||
assert(nbCompressionLoops < 40000000); /* avoid overflow */
|
||||
nbCompressionLoops *= 100;
|
||||
}
|
||||
totalCTime += clockSpan;
|
||||
totalCTime += duration_ns;
|
||||
cCompleted = totalCTime>maxTime;
|
||||
}
|
||||
|
||||
@@ -485,10 +497,11 @@ static int BMK_benchMem(const void* srcBuffer, size_t srcSize,
|
||||
cSize += !cSize; /* avoid div by 0 */
|
||||
ratio = (double)totalRSize / (double)cSize;
|
||||
markNb = (markNb+1) % NB_MARKS;
|
||||
DISPLAYLEVEL(2, "%2s-%-17.17s :%10u ->%10u (%5.3f),%6.1f MB/s\r",
|
||||
OUTLEVEL(2, "%2s-%-17.17s :%10u ->%10u (%5.3f),%6.1f MB/s\r",
|
||||
marks[markNb], displayName,
|
||||
(U32)totalRSize, (U32)cSize, ratio,
|
||||
((double)totalRSize / fastestC) * 1000 );
|
||||
((double)totalRSize / (double)fastestC) * 1000 );
|
||||
fflush(NULL);
|
||||
}
|
||||
(void)fastestD; (void)crcOrig; /* unused when decompression disabled */
|
||||
#if 1
|
||||
@@ -496,14 +509,14 @@ static int BMK_benchMem(const void* srcBuffer, size_t srcSize,
|
||||
if (!dCompleted) memset(resultBuffer, 0xD6, srcSize); /* warm result buffer */
|
||||
|
||||
UTIL_sleepMilli(5); /* give processor time to other processes */
|
||||
UTIL_waitForNextTick();
|
||||
TIME_waitForNextTick();
|
||||
|
||||
if (!dCompleted) {
|
||||
const DecFunction_f decFunction = g_decodeOnly ?
|
||||
LZ4F_decompress_binding : LZ4_decompress_safe_usingDict;
|
||||
const char* const decString = g_decodeOnly ?
|
||||
"LZ4F_decompress" : "LZ4_decompress_safe_usingDict";
|
||||
UTIL_time_t const clockStart = UTIL_getTime();
|
||||
TIME_t const timeStart = TIME_getTime();
|
||||
U32 nbLoops;
|
||||
|
||||
for (nbLoops=0; nbLoops < nbDecodeLoops; nbLoops++) {
|
||||
@@ -522,22 +535,22 @@ static int BMK_benchMem(const void* srcBuffer, size_t srcSize,
|
||||
decString, blockNb, (unsigned)blockTable[blockNb].srcSize);
|
||||
if (g_decodeOnly)
|
||||
DISPLAY("Is input using LZ4 Frame format ? \n");
|
||||
END_PROCESS(2, "error during decoding");
|
||||
benchError = 1;
|
||||
break;
|
||||
}
|
||||
blockTable[blockNb].resSize = (size_t)regenSize;
|
||||
} }
|
||||
{ U64 const clockSpan = UTIL_clockSpanNano(clockStart);
|
||||
if (clockSpan > 0) {
|
||||
if (clockSpan < fastestD * nbDecodeLoops)
|
||||
fastestD = clockSpan / nbDecodeLoops;
|
||||
{ Duration_ns const duration_ns = TIME_clockSpan_ns(timeStart);
|
||||
if (duration_ns > 0) {
|
||||
if (duration_ns < fastestD * nbDecodeLoops)
|
||||
fastestD = duration_ns / nbDecodeLoops;
|
||||
assert(fastestD > 0);
|
||||
nbDecodeLoops = (U32)(TIMELOOP_NANOSEC / fastestD) + 1; /* aim for ~1sec */
|
||||
} else {
|
||||
assert(nbDecodeLoops < 40000000); /* avoid overflow */
|
||||
nbDecodeLoops *= 100;
|
||||
}
|
||||
totalDTime += clockSpan;
|
||||
totalDTime += duration_ns;
|
||||
dCompleted = totalDTime > (DECOMP_MULT*maxTime);
|
||||
} }
|
||||
|
||||
@@ -548,11 +561,12 @@ static int BMK_benchMem(const void* srcBuffer, size_t srcSize,
|
||||
}
|
||||
markNb = (markNb+1) % NB_MARKS;
|
||||
ratio = (double)totalRSize / (double)cSize;
|
||||
DISPLAYLEVEL(2, "%2s-%-17.17s :%10u ->%10u (%5.3f),%6.1f MB/s ,%6.1f MB/s\r",
|
||||
OUTLEVEL(2, "%2s-%-17.17s :%10u ->%10u (%5.3f),%6.1f MB/s, %6.1f MB/s\r",
|
||||
marks[markNb], displayName,
|
||||
(U32)totalRSize, (U32)cSize, ratio,
|
||||
((double)totalRSize / fastestC) * 1000,
|
||||
((double)totalRSize / fastestD) * 1000);
|
||||
((double)totalRSize / (double)fastestC) * 1000,
|
||||
((double)totalRSize / (double)fastestD) * 1000);
|
||||
fflush(NULL);
|
||||
|
||||
/* CRC Checking (not possible in decode-only mode)*/
|
||||
if (!g_decodeOnly) {
|
||||
@@ -560,6 +574,7 @@ static int BMK_benchMem(const void* srcBuffer, size_t srcSize,
|
||||
if (crcOrig!=crcCheck) {
|
||||
size_t u;
|
||||
DISPLAY("\n!!! WARNING !!! %17s : Invalid Checksum : %x != %x \n", displayName, (unsigned)crcOrig, (unsigned)crcCheck);
|
||||
benchError = 1;
|
||||
for (u=0; u<srcSize; u++) {
|
||||
if (((const BYTE*)srcBuffer)[u] != ((const BYTE*)resultBuffer)[u]) {
|
||||
U32 segNb, bNb, pos;
|
||||
@@ -582,15 +597,17 @@ static int BMK_benchMem(const void* srcBuffer, size_t srcSize,
|
||||
#endif
|
||||
} /* for (testNb = 1; testNb <= (g_nbSeconds + !g_nbSeconds); testNb++) */
|
||||
|
||||
OUTLEVEL(2, "%2i#\n", cLevel);
|
||||
|
||||
/* quiet mode */
|
||||
if (g_displayLevel == 1) {
|
||||
double const cSpeed = ((double)srcSize / fastestC) * 1000;
|
||||
double const dSpeed = ((double)srcSize / fastestD) * 1000;
|
||||
double const cSpeed = ((double)srcSize / (double)fastestC) * 1000;
|
||||
double const dSpeed = ((double)srcSize / (double)fastestD) * 1000;
|
||||
DISPLAYOUT("-%-3i%11i (%5.3f) %6.2f MB/s %6.1f MB/s %s ", cLevel, (int)cSize, ratio, cSpeed, dSpeed, displayName);
|
||||
if (g_additionalParam)
|
||||
DISPLAY("-%-3i%11i (%5.3f) %6.2f MB/s %6.1f MB/s %s (param=%d)\n", cLevel, (int)cSize, ratio, cSpeed, dSpeed, displayName, g_additionalParam);
|
||||
else
|
||||
DISPLAY("-%-3i%11i (%5.3f) %6.2f MB/s %6.1f MB/s %s\n", cLevel, (int)cSize, ratio, cSpeed, dSpeed, displayName);
|
||||
DISPLAYOUT("(param=%d)", g_additionalParam);
|
||||
DISPLAYOUT("\n");
|
||||
}
|
||||
DISPLAYLEVEL(2, "%2i#\n", cLevel);
|
||||
} /* Bench */
|
||||
|
||||
/* clean up */
|
||||
@@ -598,7 +615,7 @@ static int BMK_benchMem(const void* srcBuffer, size_t srcSize,
|
||||
free(blockTable);
|
||||
free(compressedBuffer);
|
||||
free(resultBuffer);
|
||||
return 0;
|
||||
return benchError;
|
||||
}
|
||||
|
||||
|
||||
@@ -626,13 +643,13 @@ static size_t BMK_findMaxMem(U64 requiredMem)
|
||||
}
|
||||
|
||||
|
||||
static void BMK_benchCLevel(void* srcBuffer, size_t benchedSize,
|
||||
static int BMK_benchCLevel(void* srcBuffer, size_t benchedSize,
|
||||
const char* displayName, int cLevel, int cLevelLast,
|
||||
const size_t* fileSizes, unsigned nbFiles,
|
||||
const char* dictBuf, int dictSize)
|
||||
{
|
||||
int l;
|
||||
|
||||
int benchError = 0;
|
||||
const char* pch = strrchr(displayName, '\\'); /* Windows */
|
||||
if (!pch) pch = strrchr(displayName, '/'); /* Linux */
|
||||
if (pch) displayName = pch+1;
|
||||
@@ -645,11 +662,13 @@ static void BMK_benchCLevel(void* srcBuffer, size_t benchedSize,
|
||||
if (cLevelLast < cLevel) cLevelLast = cLevel;
|
||||
|
||||
for (l=cLevel; l <= cLevelLast; l++) {
|
||||
BMK_benchMem(srcBuffer, benchedSize,
|
||||
displayName, l,
|
||||
fileSizes, nbFiles,
|
||||
dictBuf, dictSize);
|
||||
benchError |= BMK_benchMem(
|
||||
srcBuffer, benchedSize,
|
||||
displayName, l,
|
||||
fileSizes, nbFiles,
|
||||
dictBuf, dictSize);
|
||||
}
|
||||
return benchError;
|
||||
}
|
||||
|
||||
|
||||
@@ -688,12 +707,13 @@ static void BMK_loadFiles(void* buffer, size_t bufferSize,
|
||||
if (totalSize == 0) END_PROCESS(12, "no data to bench");
|
||||
}
|
||||
|
||||
static void BMK_benchFileTable(const char** fileNamesTable, unsigned nbFiles,
|
||||
int cLevel, int cLevelLast,
|
||||
const char* dictBuf, int dictSize)
|
||||
static int BMK_benchFileTable(const char** fileNamesTable, unsigned nbFiles,
|
||||
int cLevel, int cLevelLast,
|
||||
const char* dictBuf, int dictSize)
|
||||
{
|
||||
void* srcBuffer;
|
||||
size_t benchedSize;
|
||||
int benchError = 0;
|
||||
size_t* fileSizes = (size_t*)malloc(nbFiles * sizeof(size_t));
|
||||
U64 const totalSizeToLoad = UTIL_getTotalFileSize(fileNamesTable, nbFiles);
|
||||
char mfName[20] = {0};
|
||||
@@ -720,7 +740,7 @@ static void BMK_benchFileTable(const char** fileNamesTable, unsigned nbFiles,
|
||||
/* Bench */
|
||||
snprintf (mfName, sizeof(mfName), " %u files", nbFiles);
|
||||
{ const char* displayName = (nbFiles > 1) ? mfName : fileNamesTable[0];
|
||||
BMK_benchCLevel(srcBuffer, benchedSize,
|
||||
benchError = BMK_benchCLevel(srcBuffer, benchedSize,
|
||||
displayName, cLevel, cLevelLast,
|
||||
fileSizes, nbFiles,
|
||||
dictBuf, dictSize);
|
||||
@@ -729,28 +749,35 @@ static void BMK_benchFileTable(const char** fileNamesTable, unsigned nbFiles,
|
||||
/* clean up */
|
||||
free(srcBuffer);
|
||||
free(fileSizes);
|
||||
return benchError;
|
||||
}
|
||||
|
||||
|
||||
static void BMK_syntheticTest(int cLevel, int cLevelLast, double compressibility,
|
||||
const char* dictBuf, int dictSize)
|
||||
static int BMK_syntheticTest(int cLevel, int cLevelLast,
|
||||
const char* dictBuf, int dictSize)
|
||||
{
|
||||
char name[20] = {0};
|
||||
size_t benchedSize = 10000000;
|
||||
int benchError = 0;
|
||||
size_t const benchedSize = 10000000;
|
||||
void* const srcBuffer = malloc(benchedSize);
|
||||
|
||||
/* Memory allocation */
|
||||
if (!srcBuffer) END_PROCESS(21, "not enough memory");
|
||||
|
||||
/* Fill input buffer */
|
||||
RDG_genBuffer(srcBuffer, benchedSize, compressibility, 0.0, 0);
|
||||
LOREM_genBuffer(srcBuffer, benchedSize, 0);
|
||||
|
||||
/* Bench */
|
||||
snprintf (name, sizeof(name), "Synthetic %2u%%", (unsigned)(compressibility*100));
|
||||
BMK_benchCLevel(srcBuffer, benchedSize, name, cLevel, cLevelLast, &benchedSize, 1, dictBuf, dictSize);
|
||||
benchError = BMK_benchCLevel(srcBuffer, benchedSize,
|
||||
"Lorem ipsum",
|
||||
cLevel, cLevelLast,
|
||||
&benchedSize,
|
||||
1,
|
||||
dictBuf, dictSize);
|
||||
|
||||
/* clean up */
|
||||
free(srcBuffer);
|
||||
|
||||
return benchError;
|
||||
}
|
||||
|
||||
|
||||
@@ -759,15 +786,16 @@ BMK_benchFilesSeparately(const char** fileNamesTable, unsigned nbFiles,
|
||||
int cLevel, int cLevelLast,
|
||||
const char* dictBuf, int dictSize)
|
||||
{
|
||||
int benchError = 0;
|
||||
unsigned fileNb;
|
||||
if (cLevel > LZ4HC_CLEVEL_MAX) cLevel = LZ4HC_CLEVEL_MAX;
|
||||
if (cLevelLast > LZ4HC_CLEVEL_MAX) cLevelLast = LZ4HC_CLEVEL_MAX;
|
||||
if (cLevelLast < cLevel) cLevelLast = cLevel;
|
||||
|
||||
for (fileNb=0; fileNb<nbFiles; fileNb++)
|
||||
BMK_benchFileTable(fileNamesTable+fileNb, 1, cLevel, cLevelLast, dictBuf, dictSize);
|
||||
benchError |= BMK_benchFileTable(fileNamesTable+fileNb, 1, cLevel, cLevelLast, dictBuf, dictSize);
|
||||
|
||||
return 0;
|
||||
return benchError;
|
||||
}
|
||||
|
||||
|
||||
@@ -775,7 +803,7 @@ int BMK_benchFiles(const char** fileNamesTable, unsigned nbFiles,
|
||||
int cLevel, int cLevelLast,
|
||||
const char* dictFileName)
|
||||
{
|
||||
double const compressibility = (double)g_compressibilityDefault / 100;
|
||||
int benchError = 0;
|
||||
char* dictBuf = NULL;
|
||||
size_t dictSize = 0;
|
||||
|
||||
@@ -823,15 +851,15 @@ int BMK_benchFiles(const char** fileNamesTable, unsigned nbFiles,
|
||||
fclose(dictFile);
|
||||
}
|
||||
|
||||
if (nbFiles == 0)
|
||||
BMK_syntheticTest(cLevel, cLevelLast, compressibility, dictBuf, (int)dictSize);
|
||||
else {
|
||||
if (nbFiles == 0) {
|
||||
benchError = BMK_syntheticTest(cLevel, cLevelLast, dictBuf, (int)dictSize);
|
||||
} else {
|
||||
if (g_benchSeparately)
|
||||
BMK_benchFilesSeparately(fileNamesTable, nbFiles, cLevel, cLevelLast, dictBuf, (int)dictSize);
|
||||
benchError = BMK_benchFilesSeparately(fileNamesTable, nbFiles, cLevel, cLevelLast, dictBuf, (int)dictSize);
|
||||
else
|
||||
BMK_benchFileTable(fileNamesTable, nbFiles, cLevel, cLevelLast, dictBuf, (int)dictSize);
|
||||
benchError = BMK_benchFileTable(fileNamesTable, nbFiles, cLevel, cLevelLast, dictBuf, (int)dictSize);
|
||||
}
|
||||
|
||||
free(dictBuf);
|
||||
return 0;
|
||||
return benchError;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,366 @@
|
||||
/*
|
||||
lorem.c - lorem ipsum generator
|
||||
Copyright (C) Yann Collet 2024
|
||||
|
||||
GPL v2 License
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
You can contact the author at :
|
||||
- LZ4 source repository : https://github.com/lz4/lz4
|
||||
- Public forum : https://groups.google.com/forum/#!forum/lz4c
|
||||
*/
|
||||
|
||||
/* Implementation notes:
|
||||
*
|
||||
* This is a very simple lorem ipsum generator
|
||||
* which features a static list of words
|
||||
* and print them one after another randomly
|
||||
* with a fake sentence / paragraph structure.
|
||||
*
|
||||
* The goal is to generate a printable text
|
||||
* that can be used to fake a text compression scenario.
|
||||
* The resulting compression / ratio curve of the lorem ipsum generator
|
||||
* is more satisfying than the previous statistical generator,
|
||||
* which was initially designed for entropy compression,
|
||||
* and lacks a regularity more representative of text.
|
||||
*
|
||||
* The compression ratio achievable on the generated lorem ipsum
|
||||
* is still a bit too good, presumably because the dictionary is a bit too
|
||||
* small. It would be possible to create some more complex scheme, notably by
|
||||
* enlarging the dictionary with a word generator, and adding grammatical rules
|
||||
* (composition) and syntax rules. But that's probably overkill for the intended
|
||||
* goal.
|
||||
*/
|
||||
|
||||
#include "lorem.h"
|
||||
#include <assert.h>
|
||||
#include <limits.h> /* INT_MAX */
|
||||
#include <stdlib.h> /* malloc, abort */
|
||||
#include <string.h> /* memcpy */
|
||||
|
||||
/* Define the word pool
|
||||
* Note: all words must have a len <= 16 */
|
||||
static const char* kWords[] = {
|
||||
"lorem", "ipsum", "dolor", "sit", "amet",
|
||||
"consectetur", "adipiscing", "elit", "sed", "do",
|
||||
"eiusmod", "tempor", "incididunt", "ut", "labore",
|
||||
"et", "dolore", "magna", "aliqua", "dis",
|
||||
"lectus", "vestibulum", "mattis", "ullamcorper", "velit",
|
||||
"commodo", "a", "lacus", "arcu", "magnis",
|
||||
"parturient", "montes", "nascetur", "ridiculus", "mus",
|
||||
"mauris", "nulla", "malesuada", "pellentesque", "eget",
|
||||
"gravida", "in", "dictum", "non", "erat",
|
||||
"nam", "voluptat", "maecenas", "blandit", "aliquam",
|
||||
"etiam", "enim", "lobortis", "scelerisque", "fermentum",
|
||||
"dui", "faucibus", "ornare", "at", "elementum",
|
||||
"eu", "facilisis", "odio", "morbi", "quis",
|
||||
"eros", "donec", "ac", "orci", "purus",
|
||||
"turpis", "cursus", "leo", "vel", "porta",
|
||||
"consequat", "interdum", "varius", "vulputate", "aliquet",
|
||||
"pharetra", "nunc", "auctor", "urna", "id",
|
||||
"metus", "viverra", "nibh", "cras", "mi",
|
||||
"unde", "omnis", "iste", "natus", "error",
|
||||
"perspiciatis", "voluptatem", "accusantium", "doloremque", "laudantium",
|
||||
"totam", "rem", "aperiam", "eaque", "ipsa",
|
||||
"quae", "ab", "illo", "inventore", "veritatis",
|
||||
"quasi", "architecto", "beatae", "vitae", "dicta",
|
||||
"sunt", "explicabo", "nemo", "ipsam", "quia",
|
||||
"voluptas", "aspernatur", "aut", "odit", "fugit",
|
||||
"consequuntur", "magni", "dolores", "eos", "qui",
|
||||
"ratione", "sequi", "nesciunt", "neque", "porro",
|
||||
"quisquam", "est", "dolorem", "adipisci", "numquam",
|
||||
"eius", "modi", "tempora", "incidunt", "magnam",
|
||||
"quaerat", "ad", "minima", "veniam", "nostrum",
|
||||
"ullam", "corporis", "suscipit", "laboriosam", "nisi",
|
||||
"aliquid", "ex", "ea", "commodi", "consequatur",
|
||||
"autem", "eum", "iure", "voluptate", "esse",
|
||||
"quam", "nihil", "molestiae", "illum", "fugiat",
|
||||
"quo", "pariatur", "vero", "accusamus", "iusto",
|
||||
"dignissimos", "ducimus", "blanditiis", "praesentium", "voluptatum",
|
||||
"deleniti", "atque", "corrupti", "quos", "quas",
|
||||
"molestias", "excepturi", "sint", "occaecati", "cupiditate",
|
||||
"provident", "similique", "culpa", "officia", "deserunt",
|
||||
"mollitia", "animi", "laborum", "dolorum", "fuga",
|
||||
"harum", "quidem", "rerum", "facilis", "expedita",
|
||||
"distinctio", "libero", "tempore", "cum", "soluta",
|
||||
"nobis", "eligendi", "optio", "cumque", "impedit",
|
||||
"minus", "quod", "maxime", "placeat", "facere",
|
||||
"possimus", "assumenda", "repellendus", "temporibus", "quibusdam",
|
||||
"officiis", "debitis", "saepe", "eveniet", "voluptates",
|
||||
"repudiandae", "recusandae", "itaque", "earum", "hic",
|
||||
"tenetur", "sapiente", "delectus", "reiciendis", "cillum",
|
||||
"maiores", "alias", "perferendis", "doloribus", "asperiores",
|
||||
"repellat", "minim", "nostrud", "exercitation", "ullamco",
|
||||
"laboris", "aliquip", "duis", "aute", "irure",
|
||||
};
|
||||
#define KNBWORDS (sizeof(kWords) / sizeof(kWords[0]))
|
||||
static const unsigned kNbWords = KNBWORDS;
|
||||
|
||||
static const char* g_words[KNBWORDS] = { NULL };
|
||||
static unsigned g_wordLen[KNBWORDS] = {0};
|
||||
static char* g_wordBuffer = NULL;
|
||||
|
||||
/* simple 1-dimension distribution, based on word's length, favors small words
|
||||
*/
|
||||
static const int kWeights[] = { 0, 8, 6, 4, 3, 2 };
|
||||
static const unsigned kNbWeights = sizeof(kWeights) / sizeof(kWeights[0]);
|
||||
|
||||
#define DISTRIB_SIZE_MAX 650
|
||||
static int g_distrib[DISTRIB_SIZE_MAX] = { 0 };
|
||||
static unsigned g_distribCount = 0;
|
||||
|
||||
static void countFreqs(
|
||||
const unsigned wordLen[],
|
||||
size_t nbWords,
|
||||
const int* weights,
|
||||
unsigned long nbWeights)
|
||||
{
|
||||
unsigned total = 0;
|
||||
size_t w;
|
||||
for (w = 0; w < nbWords; w++) {
|
||||
size_t len = wordLen[w];
|
||||
int lmax;
|
||||
if (len >= nbWeights)
|
||||
len = nbWeights - 1;
|
||||
lmax = weights[len];
|
||||
total += (unsigned)lmax;
|
||||
}
|
||||
g_distribCount = total;
|
||||
assert(g_distribCount <= DISTRIB_SIZE_MAX);
|
||||
}
|
||||
|
||||
static void init_word_len(
|
||||
const char* words[],
|
||||
size_t nbWords)
|
||||
{
|
||||
size_t n;
|
||||
assert(words != NULL);
|
||||
for (n=0; n<nbWords; n++) {
|
||||
assert(words[n] != NULL);
|
||||
assert(strlen(words[n]) < 256);
|
||||
g_wordLen[n] = (unsigned char)strlen(words[n]);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static size_t sumLen(const unsigned* sizes, size_t s)
|
||||
{
|
||||
size_t total = 0;
|
||||
size_t n;
|
||||
assert(sizes != NULL);
|
||||
for (n=0; n<s; n++) {
|
||||
total += sizes[n];
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
static void init_word_buffer(void)
|
||||
{
|
||||
size_t n;
|
||||
size_t const bufSize = sumLen(g_wordLen, kNbWords) + 16;
|
||||
char* ptr;
|
||||
assert(g_wordBuffer == NULL);
|
||||
g_wordBuffer = (char*)calloc(1, bufSize);
|
||||
if (g_wordBuffer == NULL) abort();
|
||||
ptr = g_wordBuffer;
|
||||
for (n=0; n<kNbWords; n++) {
|
||||
memcpy(ptr, kWords[n], g_wordLen[n]);
|
||||
g_words[n] = ptr;
|
||||
ptr += g_wordLen[n];
|
||||
}
|
||||
}
|
||||
|
||||
static void init_word_distrib(
|
||||
const unsigned wordLen[],
|
||||
size_t nbWords,
|
||||
const int* weights,
|
||||
unsigned long nbWeights)
|
||||
{
|
||||
size_t w, d = 0;
|
||||
countFreqs(wordLen, nbWords, weights, nbWeights);
|
||||
for (w = 0; w < nbWords; w++) {
|
||||
size_t len = wordLen[w];
|
||||
int l, lmax;
|
||||
if (len >= nbWeights)
|
||||
len = nbWeights - 1;
|
||||
lmax = weights[len];
|
||||
for (l = 0; l < lmax; l++) {
|
||||
g_distrib[d++] = (int)w;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Note: this unit only works when invoked sequentially.
|
||||
* No concurrent access is allowed */
|
||||
static char* g_ptr = NULL;
|
||||
static size_t g_nbChars = 0;
|
||||
static size_t g_maxChars = 10000000;
|
||||
static unsigned g_randRoot = 0;
|
||||
|
||||
#define RDG_rotl32(x, r) ((x << r) | (x >> (32 - r)))
|
||||
static unsigned LOREM_rand(unsigned range)
|
||||
{
|
||||
static const unsigned prime1 = 2654435761U;
|
||||
static const unsigned prime2 = 2246822519U;
|
||||
unsigned rand32 = g_randRoot;
|
||||
rand32 *= prime1;
|
||||
rand32 ^= prime2;
|
||||
rand32 = RDG_rotl32(rand32, 13);
|
||||
g_randRoot = rand32;
|
||||
return (unsigned)(((unsigned long long)rand32 * range) >> 32);
|
||||
}
|
||||
|
||||
static void writeLastCharacters(void)
|
||||
{
|
||||
size_t lastChars = g_maxChars - g_nbChars;
|
||||
assert(g_maxChars >= g_nbChars);
|
||||
if (lastChars == 0)
|
||||
return;
|
||||
g_ptr[g_nbChars++] = '.';
|
||||
if (lastChars > 2) {
|
||||
memset(g_ptr + g_nbChars, ' ', lastChars - 2);
|
||||
}
|
||||
if (lastChars > 1) {
|
||||
g_ptr[g_maxChars - 1] = '\n';
|
||||
}
|
||||
g_nbChars = g_maxChars;
|
||||
}
|
||||
|
||||
static void generateLastWord(const char* word, size_t wordLen, int upCase)
|
||||
{
|
||||
if (g_nbChars + wordLen + 2 > g_maxChars) {
|
||||
writeLastCharacters();
|
||||
return;
|
||||
}
|
||||
memcpy(g_ptr + g_nbChars, word, wordLen);
|
||||
if (upCase) {
|
||||
static const char toUp = 'A' - 'a';
|
||||
g_ptr[g_nbChars] = (char)(g_ptr[g_nbChars] + toUp);
|
||||
}
|
||||
g_nbChars += wordLen;
|
||||
writeLastCharacters();
|
||||
}
|
||||
|
||||
#define MAX(a,b) ((a)<(b)?(b):(a))
|
||||
static void generateWord(const char* word, size_t wordLen, const char* separator, size_t sepLen, int upCase)
|
||||
{
|
||||
size_t const wlen = MAX(16, wordLen + 2);
|
||||
if (g_nbChars + wlen > g_maxChars) {
|
||||
generateLastWord(word, wordLen, upCase);
|
||||
return;
|
||||
}
|
||||
assert(wordLen <= 16);
|
||||
memcpy(g_ptr + g_nbChars, word, 16);
|
||||
if (upCase) {
|
||||
static const char toUp = 'A' - 'a';
|
||||
g_ptr[g_nbChars] = (char)(g_ptr[g_nbChars] + toUp);
|
||||
}
|
||||
g_nbChars += wordLen;
|
||||
assert(sepLen <= 2);
|
||||
memcpy(g_ptr + g_nbChars, separator, 2);
|
||||
g_nbChars += sepLen;
|
||||
}
|
||||
|
||||
static int about(unsigned target)
|
||||
{
|
||||
return (int)(LOREM_rand(target) + LOREM_rand(target) + 1);
|
||||
}
|
||||
|
||||
/* Function to generate a random sentence */
|
||||
static void generateSentence(int nbWords)
|
||||
{
|
||||
int commaPos = about(9);
|
||||
int comma2 = commaPos + about(7);
|
||||
int qmark = (LOREM_rand(11) == 7);
|
||||
const char* endSep = qmark ? "? " : ". ";
|
||||
int i;
|
||||
for (i = 0; i < nbWords; i++) {
|
||||
int const wordID = g_distrib[LOREM_rand(g_distribCount)];
|
||||
const char* sep = " ";
|
||||
size_t sepLen = 1;
|
||||
if (i == commaPos)
|
||||
sep = ", ", sepLen=2;
|
||||
if (i == comma2)
|
||||
sep = ", ", sepLen=2;
|
||||
if (i == nbWords - 1)
|
||||
sep = endSep, sepLen=2;
|
||||
generateWord(g_words[wordID], g_wordLen[wordID], sep, sepLen, i == 0);
|
||||
}
|
||||
}
|
||||
|
||||
static void generateParagraph(int nbSentences)
|
||||
{
|
||||
int i;
|
||||
for (i = 0; i < nbSentences; i++) {
|
||||
int wordsPerSentence = about(11);
|
||||
generateSentence(wordsPerSentence);
|
||||
}
|
||||
if (g_nbChars < g_maxChars) {
|
||||
g_ptr[g_nbChars++] = '\n';
|
||||
}
|
||||
if (g_nbChars < g_maxChars) {
|
||||
g_ptr[g_nbChars++] = '\n';
|
||||
}
|
||||
}
|
||||
|
||||
/* It's "common" for lorem ipsum generators to start with the same first
|
||||
* pre-defined sentence */
|
||||
static void generateFirstSentence(void)
|
||||
{
|
||||
int i;
|
||||
for (i = 0; i < 18; i++) {
|
||||
const char* separator = " ";
|
||||
size_t sepLen = 1;
|
||||
if (i == 4)
|
||||
separator = ", ", sepLen=2;
|
||||
if (i == 7)
|
||||
separator = ", ", sepLen=2;
|
||||
generateWord(g_words[i], g_wordLen[i], separator, sepLen, i == 0);
|
||||
}
|
||||
generateWord(g_words[18], g_wordLen[18], ". ", 2, 0);
|
||||
}
|
||||
|
||||
size_t
|
||||
LOREM_genBlock(void* buffer, size_t size, unsigned seed, int first, int fill)
|
||||
{
|
||||
g_ptr = (char*)buffer;
|
||||
assert(size < INT_MAX);
|
||||
g_maxChars = size;
|
||||
g_nbChars = 0;
|
||||
g_randRoot = seed;
|
||||
if (g_distribCount == 0) {
|
||||
init_word_len(kWords, kNbWords);
|
||||
init_word_buffer();
|
||||
init_word_distrib(g_wordLen, kNbWords, kWeights, kNbWeights);
|
||||
}
|
||||
|
||||
if (first) {
|
||||
generateFirstSentence();
|
||||
}
|
||||
while (g_nbChars < g_maxChars) {
|
||||
int sentencePerParagraph = about(7);
|
||||
generateParagraph(sentencePerParagraph);
|
||||
if (!fill)
|
||||
break; /* only generate one paragraph in not-fill mode */
|
||||
}
|
||||
g_ptr = NULL;
|
||||
return g_nbChars;
|
||||
}
|
||||
|
||||
void LOREM_genBuffer(void* buffer, size_t size, unsigned seed)
|
||||
{
|
||||
LOREM_genBlock(buffer, size, seed, 1, 1);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
lorem.h - lorem ipsum generator
|
||||
Copyright (C) Yann Collet 2024
|
||||
|
||||
GPL v2 License
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
You can contact the author at :
|
||||
- LZ4 source repository : https://github.com/lz4/lz4
|
||||
- Public forum : https://groups.google.com/forum/#!forum/lz4c
|
||||
*/
|
||||
|
||||
|
||||
#include <stddef.h> /* size_t */
|
||||
|
||||
/*
|
||||
* LOREM_genBuffer():
|
||||
* Generate @size bytes of compressible data using lorem ipsum generator
|
||||
* into provided @buffer.
|
||||
*/
|
||||
void LOREM_genBuffer(void* buffer, size_t size, unsigned seed);
|
||||
|
||||
/*
|
||||
* LOREM_genBlock():
|
||||
* Similar to LOREM_genBuffer, with additional controls :
|
||||
* - @first : generate the first sentence
|
||||
* - @fill : fill the entire @buffer,
|
||||
* if ==0: generate one paragraph at most.
|
||||
* @return : nb of bytes generated into @buffer.
|
||||
*/
|
||||
size_t LOREM_genBlock(void* buffer, size_t size,
|
||||
unsigned seed,
|
||||
int first, int fill);
|
||||
+19
-4
@@ -1,5 +1,5 @@
|
||||
.
|
||||
.TH "LZ4" "1" "August 2022" "lz4 v1.9.4" "User Commands"
|
||||
.TH "LZ4" "1" "July 2024" "lz4 1.10.0" "User Commands"
|
||||
.
|
||||
.SH "NAME"
|
||||
\fBlz4\fR \- lz4, unlz4, lz4cat \- Compress or decompress \.lz4 files
|
||||
@@ -17,7 +17,7 @@
|
||||
When writing scripts that need to decompress files, it is recommended to always use the name \fBlz4\fR with appropriate arguments (\fBlz4 \-d\fR or \fBlz4 \-dc\fR) instead of the names \fBunlz4\fR and \fBlz4cat\fR\.
|
||||
.
|
||||
.SH "DESCRIPTION"
|
||||
\fBlz4\fR is an extremely fast lossless compression algorithm, based on \fBbyte\-aligned LZ77\fR family of compression scheme\. \fBlz4\fR offers compression speeds > 500 MB/s per core, linearly scalable with multi\-core CPUs\. It features an extremely fast decoder, offering speed in multiple GB/s per core, typically reaching RAM speed limit on multi\-core systems\. The native file format is the \fB\.lz4\fR format\.
|
||||
\fBlz4\fR is a CLI based on \fBliblz4\fR, an extremely fast implementation of lossless compression algorithm\. It provides a default compression speed of typically > 500 MB/s per core\. Speed can traded for higher compression ratio, by increasing the compression level parameter\. While decompression is single\-threaded, it reaches multiple GB/s, generally fast enough to be I/O bound\. \fBlz4\fR native file format is the \fB\.lz4\fR format\.
|
||||
.
|
||||
.SS "Difference between lz4 and gzip"
|
||||
\fBlz4\fR supports a command line syntax similar \fIbut not identical\fR to \fBgzip(1)\fR\. Differences are :
|
||||
@@ -58,7 +58,7 @@ Similarly, \fBlz4 \-m \-d\fR can decompress multiple \fB*\.lz4\fR files\.
|
||||
It\'s possible to opt\-in to erase source files on successful compression or decompression, using \fB\-\-rm\fR command\.
|
||||
.
|
||||
.IP "\(bu" 4
|
||||
Consequently, \fBlz4 \-m \-\-rm\fR behaves the same as \fBgzip\fR\.
|
||||
Consequently, \fBlz4 \-m \-\-rm\fR features a behavior closer to the \fBgzip\fR one\.
|
||||
.
|
||||
.IP "" 0
|
||||
.
|
||||
@@ -107,7 +107,7 @@ Benchmark mode, using \fB#\fR compression level\.
|
||||
.
|
||||
.TP
|
||||
\fB\-\-list\fR
|
||||
List information about \.lz4 files\. note : current implementation is limited to single\-frame \.lz4 files\.
|
||||
List information about \.lz4 files\. For detailed information on files with multiple frames, use \fB\-v\fR\. \fB\-\-list\fR automatically triggers \fB\-m\fR modifier\.
|
||||
.
|
||||
.SS "Operation modifiers"
|
||||
.
|
||||
@@ -124,6 +124,10 @@ Switch to ultra\-fast compression levels\. The higher the value, the faster the
|
||||
Set highest compression level\. Same as \-12\.
|
||||
.
|
||||
.TP
|
||||
\fB\-T#\fR, \fB\-\-threads=#\fR
|
||||
Use \fB#\fR threads for compression\. When \fB0\fR, or none provided: automatically determined from nb of detected cores\.
|
||||
.
|
||||
.TP
|
||||
\fB\-\-favor\-decSpeed\fR
|
||||
Generate compressed data optimized for decompression speed\. Compressed data will be larger as a consequence (typically by ~0\.5%), while decompression speed will be improved by 5\-20%, depending on use cases\. This option only works in combination with very high compression levels (>=10)\.
|
||||
.
|
||||
@@ -242,6 +246,17 @@ Benchmark multiple compression levels, from b# to e# (included)
|
||||
\fB\-i#\fR
|
||||
Minimum evaluation time in seconds [1\-9] (default : 3)
|
||||
.
|
||||
.SS "Environment Variables"
|
||||
It\'s possible to pass some parameters to \fBlz4\fR via environment variables\. This can be useful in situations where \fBlz4\fR is known to be invoked (from a script for example) but there is no way to pass \fBlz4\fR parameters to influence the compression session\. The environment variable has higher priority than executable default, but lower priority than corresponding runtime command\. When set as global environment variables, it can be a way to enforce personalized defaults different from the executable set ones\.
|
||||
.
|
||||
.TP
|
||||
\fBLZ4_CLEVEL\fR
|
||||
specify a default compression level that \fBlz4\fR employs for compression when no other compression level is specified on command line\. Executable default is generally \fB1\fR\.
|
||||
.
|
||||
.TP
|
||||
\fBLZ4_NBWORKERS\fR
|
||||
specify a default number of threads that \fBlz4\fR will employ for compression\. Executable default is generally \fB0\fR, which means auto\-determined based on local cpu\. This functionality is only relevant when \fBlz4\fR is compiled with multithreading support\. The maximum number of workers is capped at \fBLZ4_NBWORKERS_MAX\fR (\fB200\fR by default)\.
|
||||
.
|
||||
.SH "BUGS"
|
||||
Report bugs at: https://github\.com/lz4/lz4/issues
|
||||
.
|
||||
|
||||
+26
-9
@@ -18,13 +18,11 @@ it is recommended to always use the name `lz4` with appropriate arguments
|
||||
DESCRIPTION
|
||||
-----------
|
||||
|
||||
`lz4` is an extremely fast lossless compression algorithm,
|
||||
based on **byte-aligned LZ77** family of compression scheme.
|
||||
`lz4` offers compression speeds > 500 MB/s per core,
|
||||
linearly scalable with multi-core CPUs.
|
||||
It features an extremely fast decoder, offering speed in multiple GB/s per core,
|
||||
typically reaching RAM speed limit on multi-core systems.
|
||||
The native file format is the `.lz4` format.
|
||||
`lz4` is a CLI based on `liblz4`, an extremely fast implementation of lossless compression algorithm.
|
||||
It provides a default compression speed of typically > 500 MB/s per core.
|
||||
Speed can traded for higher compression ratio, by increasing the compression level parameter.
|
||||
While decompression is single-threaded, it reaches multiple GB/s, generally fast enough to be I/O bound.
|
||||
`lz4` native file format is the `.lz4` format.
|
||||
|
||||
### Difference between lz4 and gzip
|
||||
|
||||
@@ -59,7 +57,7 @@ Default behaviors can be modified by opt-in commands, detailed below.
|
||||
* Similarly, `lz4 -m -d` can decompress multiple `*.lz4` files.
|
||||
* It's possible to opt-in to erase source files
|
||||
on successful compression or decompression, using `--rm` command.
|
||||
* Consequently, `lz4 -m --rm` behaves the same as `gzip`.
|
||||
* Consequently, `lz4 -m --rm` features a behavior closer to the `gzip` one.
|
||||
|
||||
### Concatenation of .lz4 files
|
||||
|
||||
@@ -115,7 +113,8 @@ only the latest one will be applied.
|
||||
|
||||
* `--list`:
|
||||
List information about .lz4 files.
|
||||
note : current implementation is limited to single-frame .lz4 files.
|
||||
For detailed information on files with multiple frames, use `-v`.
|
||||
`--list` automatically triggers `-m` modifier.
|
||||
|
||||
### Operation modifiers
|
||||
|
||||
@@ -138,6 +137,10 @@ only the latest one will be applied.
|
||||
* `--best`:
|
||||
Set highest compression level. Same as -12.
|
||||
|
||||
* `-T#`, `--threads=#`:
|
||||
Use `#` threads for compression.
|
||||
When `0`, or none provided: automatically determined from nb of detected cores.
|
||||
|
||||
* `--favor-decSpeed`:
|
||||
Generate compressed data optimized for decompression speed.
|
||||
Compressed data will be larger as a consequence (typically by ~0.5%),
|
||||
@@ -244,6 +247,20 @@ only the latest one will be applied.
|
||||
Minimum evaluation time in seconds \[1-9\] (default : 3)
|
||||
|
||||
|
||||
### Environment Variables
|
||||
|
||||
It's possible to pass some parameters to `lz4` via environment variables.
|
||||
This can be useful in situations where `lz4` is known to be invoked (from a script for example) but there is no way to pass `lz4` parameters to influence the compression session.
|
||||
The environment variable has higher priority than executable default, but lower priority than corresponding runtime command.
|
||||
When set as global environment variables, it can be a way to enforce personalized defaults different from the executable set ones.
|
||||
|
||||
* `LZ4_CLEVEL`:
|
||||
specify a default compression level that `lz4` employs for compression when no other compression level is specified on command line. Executable default is generally `1`.
|
||||
|
||||
* `LZ4_NBWORKERS`:
|
||||
specify a default number of threads that `lz4` will employ for compression. Executable default is generally `0`, which means auto-determined based on local cpu. This functionality is only relevant when `lz4` is compiled with multithreading support. The maximum number of workers is capped at `LZ4_NBWORKERS_MAX` (`200` by default).
|
||||
|
||||
|
||||
BUGS
|
||||
----
|
||||
|
||||
|
||||
+167
-64
@@ -1,6 +1,6 @@
|
||||
/*
|
||||
LZ4cli - LZ4 Command Line Interface
|
||||
Copyright (C) Yann Collet 2011-2020
|
||||
Copyright (C) Yann Collet 2011-2023
|
||||
|
||||
GPL v2 License
|
||||
|
||||
@@ -31,6 +31,14 @@
|
||||
*/
|
||||
|
||||
|
||||
/*-************************************
|
||||
* Compiler options
|
||||
**************************************/
|
||||
#ifdef _MSC_VER /* Visual Studio */
|
||||
# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
|
||||
#endif
|
||||
|
||||
|
||||
/****************************
|
||||
* Includes
|
||||
*****************************/
|
||||
@@ -39,6 +47,7 @@
|
||||
#include <stdio.h> /* fprintf, getchar */
|
||||
#include <stdlib.h> /* exit, calloc, free */
|
||||
#include <string.h> /* strcmp, strlen */
|
||||
#include "lz4conf.h" /* compile-time constants */
|
||||
#include "bench.h" /* BMK_benchFile, BMK_SetNbIterations, BMK_SetBlocksize, BMK_SetPause */
|
||||
#include "lz4io.h" /* LZ4IO_compressFilename, LZ4IO_decompressFilename, LZ4IO_compressMultipleFilenames */
|
||||
#include "lz4hc.h" /* LZ4HC_CLEVEL_MAX */
|
||||
@@ -48,9 +57,14 @@
|
||||
/*****************************
|
||||
* Constants
|
||||
******************************/
|
||||
#define COMPRESSOR_NAME "LZ4 command line interface"
|
||||
#if LZ4IO_MULTITHREAD
|
||||
# define IO_MT "multithread"
|
||||
#else
|
||||
# define IO_MT "single-thread"
|
||||
#endif
|
||||
#define COMPRESSOR_NAME "lz4"
|
||||
#define AUTHOR "Yann Collet"
|
||||
#define WELCOME_MESSAGE "*** %s %i-bits v%s, by %s ***\n", COMPRESSOR_NAME, (int)(sizeof(void*)*8), LZ4_versionString(), AUTHOR
|
||||
#define WELCOME_MESSAGE "*** %s v%s %i-bit %s, by %s ***\n", COMPRESSOR_NAME, LZ4_versionString(), (int)(sizeof(void*)*8), IO_MT, AUTHOR
|
||||
#define LZ4_EXTENSION ".lz4"
|
||||
#define LZ4CAT "lz4cat"
|
||||
#define UNLZ4 "unlz4"
|
||||
@@ -61,30 +75,35 @@ static int g_lz4c_legacy_commands = 0;
|
||||
#define MB *(1U<<20)
|
||||
#define GB *(1U<<30)
|
||||
|
||||
#define LZ4_BLOCKSIZEID_DEFAULT 7
|
||||
|
||||
|
||||
/*-************************************
|
||||
* Macros
|
||||
***************************************/
|
||||
#define DISPLAYOUT(...) fprintf(stdout, __VA_ARGS__)
|
||||
#define DISPLAY(...) fprintf(stderr, __VA_ARGS__)
|
||||
#define DISPLAYLEVEL(l, ...) if (displayLevel>=l) { DISPLAY(__VA_ARGS__); }
|
||||
#define DISPLAYLEVEL(l, ...) do { if (displayLevel>=l) DISPLAY(__VA_ARGS__); } while (0)
|
||||
static unsigned displayLevel = 2; /* 0 : no display ; 1: errors only ; 2 : downgradable normal ; 3 : non-downgradable normal; 4 : + information */
|
||||
|
||||
|
||||
/*-************************************
|
||||
* Exceptions
|
||||
* Errors and Messages
|
||||
***************************************/
|
||||
#define DEBUG 0
|
||||
#define DEBUGOUTPUT(...) if (DEBUG) DISPLAY(__VA_ARGS__);
|
||||
#define EXM_THROW(error, ...) \
|
||||
{ \
|
||||
DEBUGOUTPUT("Error defined at %s, line %i : \n", __FILE__, __LINE__); \
|
||||
DISPLAYLEVEL(1, "Error %i : ", error); \
|
||||
DISPLAYLEVEL(1, __VA_ARGS__); \
|
||||
DISPLAYLEVEL(1, "\n"); \
|
||||
exit(error); \
|
||||
#ifndef DEBUG
|
||||
# define DEBUG 0
|
||||
#endif
|
||||
#define DEBUGOUTPUT(...) do { if (DEBUG) DISPLAY(__VA_ARGS__); } while (0)
|
||||
#define END_PROCESS(error, ...) \
|
||||
do { \
|
||||
DEBUGOUTPUT("Error in %s, line %i : \n", __FILE__, __LINE__); \
|
||||
DISPLAYLEVEL(1, "Error %i : ", error); \
|
||||
DISPLAYLEVEL(1, __VA_ARGS__); \
|
||||
DISPLAYLEVEL(1, "\n"); \
|
||||
exit(error); \
|
||||
} while (0)
|
||||
|
||||
static void errorOut(const char* msg)
|
||||
{
|
||||
DISPLAYLEVEL(1, "%s \n", msg); exit(1);
|
||||
}
|
||||
|
||||
|
||||
@@ -110,11 +129,10 @@ static int usage(const char* exeName)
|
||||
DISPLAY( "input : a filename \n");
|
||||
DISPLAY( " with no FILE, or when FILE is - or %s, read standard input\n", stdinmark);
|
||||
DISPLAY( "Arguments : \n");
|
||||
DISPLAY( " -1 : Fast compression (default) \n");
|
||||
DISPLAY( " -9 : High compression \n");
|
||||
DISPLAY( " -1 : fast compression (default) \n");
|
||||
DISPLAY( " -%2d : slowest compression level \n", LZ4HC_CLEVEL_MAX);
|
||||
DISPLAY( " -T# : use # threads for compression (default:%i==auto) \n", LZ4_NBWORKERS_DEFAULT);
|
||||
DISPLAY( " -d : decompression (default for %s extension)\n", LZ4_EXTENSION);
|
||||
DISPLAY( " -z : force compression \n");
|
||||
DISPLAY( " -D FILE: use FILE as dictionary \n");
|
||||
DISPLAY( " -f : overwrite output without prompting \n");
|
||||
DISPLAY( " -k : preserve source files(s) (default) \n");
|
||||
DISPLAY( "--rm : remove source file(s) after successful de/compression \n");
|
||||
@@ -138,8 +156,10 @@ static int usage_advanced(const char* exeName)
|
||||
DISPLAY( " -r : operate recursively on directories (sets also -m) \n");
|
||||
#endif
|
||||
DISPLAY( " -l : compress using Legacy format (Linux kernel compression)\n");
|
||||
DISPLAY( " -z : force compression \n");
|
||||
DISPLAY( " -D FILE: use FILE as dictionary (compression & decompression)\n");
|
||||
DISPLAY( " -B# : cut file into blocks of size # bytes [32+] \n");
|
||||
DISPLAY( " or predefined block size [4-7] (default: 7) \n");
|
||||
DISPLAY( " or predefined block size [4-7] (default: %i) \n", LZ4_BLOCKSIZEID_DEFAULT);
|
||||
DISPLAY( " -BI : Block Independence (default) \n");
|
||||
DISPLAY( " -BD : Block dependency (improves compression ratio) \n");
|
||||
DISPLAY( " -BX : enable block checksum (default:disabled) \n");
|
||||
@@ -279,6 +299,34 @@ static unsigned readU32FromChar(const char** stringPtr)
|
||||
return result;
|
||||
}
|
||||
|
||||
#define CLEAN_RETURN(i) { operationResult = (i); goto _cleanup; }
|
||||
|
||||
#define NEXT_FIELD(ptr) { \
|
||||
if (*argument == '=') { \
|
||||
ptr = ++argument; \
|
||||
argument += strlen(ptr); \
|
||||
} else { \
|
||||
argNb++; \
|
||||
if (argNb >= argCount) { \
|
||||
DISPLAYLEVEL(1, "error: missing command argument \n"); \
|
||||
CLEAN_RETURN(1); \
|
||||
} \
|
||||
ptr = argv[argNb]; \
|
||||
assert(ptr != NULL); \
|
||||
if (ptr[0]=='-') { \
|
||||
DISPLAYLEVEL(1, "error: command cannot be separated from its argument by another command \n"); \
|
||||
CLEAN_RETURN(1); \
|
||||
} } }
|
||||
|
||||
#define NEXT_UINT32(val32) { \
|
||||
const char* __nb; \
|
||||
NEXT_FIELD(__nb); \
|
||||
val32 = readU32FromChar(&__nb); \
|
||||
if(*__nb != 0) { \
|
||||
errorOut("error: only numeric values with optional suffixes K, KB, KiB, M, MB, MiB are allowed"); \
|
||||
} \
|
||||
}
|
||||
|
||||
/** longCommandWArg() :
|
||||
* check if *stringPtr is the same as longCommand.
|
||||
* If yes, @return 1 and advances *stringPtr to the position which immediately follows longCommand.
|
||||
@@ -307,10 +355,40 @@ static operationMode_e determineOpMode(const char* inputFilename)
|
||||
else return om_compress;
|
||||
}
|
||||
|
||||
int main(int argc, const char** argv)
|
||||
#define ENV_NBTHREADS "LZ4_NBWORKERS"
|
||||
|
||||
static unsigned init_nbWorkers(void)
|
||||
{
|
||||
int i,
|
||||
cLevel=1,
|
||||
const char* const env = getenv(ENV_NBTHREADS);
|
||||
if (env != NULL) {
|
||||
const char* ptr = env;
|
||||
if ((*ptr>='0') && (*ptr<='9')) {
|
||||
return readU32FromChar(&ptr);
|
||||
}
|
||||
DISPLAYLEVEL(2, "Ignore environment variable setting %s=%s: not a valid unsigned value \n", ENV_NBTHREADS, env);
|
||||
}
|
||||
return LZ4_NBWORKERS_DEFAULT;
|
||||
}
|
||||
|
||||
#define ENV_CLEVEL "LZ4_CLEVEL"
|
||||
|
||||
static int init_cLevel(void)
|
||||
{
|
||||
const char* const env = getenv(ENV_CLEVEL);
|
||||
if (env != NULL) {
|
||||
const char* ptr = env;
|
||||
if ((*ptr>='0') && (*ptr<='9')) {
|
||||
return (int)readU32FromChar(&ptr);
|
||||
}
|
||||
DISPLAYLEVEL(2, "Ignore environment variable setting %s=%s: not a valid unsigned value \n", ENV_CLEVEL, env);
|
||||
}
|
||||
return LZ4_CLEVEL_DEFAULT;
|
||||
}
|
||||
|
||||
int main(int argCount, const char** argv)
|
||||
{
|
||||
int argNb,
|
||||
cLevel=init_cLevel(),
|
||||
cLevelLast=-10000,
|
||||
legacy_format=0,
|
||||
forceStdout=0,
|
||||
@@ -319,12 +397,13 @@ int main(int argc, const char** argv)
|
||||
multiple_inputs=0,
|
||||
all_arguments_are_files=0,
|
||||
operationResult=0;
|
||||
unsigned nbWorkers = init_nbWorkers();
|
||||
operationMode_e mode = om_auto;
|
||||
const char* input_filename = NULL;
|
||||
const char* output_filename= NULL;
|
||||
const char* dictionary_filename = NULL;
|
||||
char* dynNameSpace = NULL;
|
||||
const char** inFileNames = (const char**)calloc((size_t)argc, sizeof(char*));
|
||||
const char** inFileNames = (const char**)calloc((size_t)argCount, sizeof(char*));
|
||||
unsigned ifnIdx=0;
|
||||
LZ4IO_prefs_t* const prefs = LZ4IO_defaultPreferences();
|
||||
const char nullOutput[] = NULL_OUTPUT;
|
||||
@@ -339,7 +418,8 @@ int main(int argc, const char** argv)
|
||||
/* Init */
|
||||
if (inFileNames==NULL) {
|
||||
DISPLAY("Allocation error : not enough memory \n");
|
||||
return 1;
|
||||
operationResult = 1;
|
||||
goto _cleanup;
|
||||
}
|
||||
inFileNames[0] = stdinmark;
|
||||
LZ4IO_setOverwrite(prefs, 0);
|
||||
@@ -359,8 +439,8 @@ int main(int argc, const char** argv)
|
||||
if (exeNameMatch(exeName, LZ4_LEGACY)) { g_lz4c_legacy_commands=1; }
|
||||
|
||||
/* command switches */
|
||||
for(i=1; i<argc; i++) {
|
||||
const char* argument = argv[i];
|
||||
for(argNb=1; argNb<argCount; argNb++) {
|
||||
const char* argument = argv[argNb];
|
||||
|
||||
if(!argument) continue; /* Protection if argument empty */
|
||||
|
||||
@@ -382,7 +462,7 @@ int main(int argc, const char** argv)
|
||||
if (mode != om_bench) mode = om_decompress;
|
||||
BMK_setDecodeOnlyMode(1);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (!strcmp(argument, "--multiple")) { multiple_inputs = 1; continue; }
|
||||
if (!strcmp(argument, "--test")) { mode = om_test; continue; }
|
||||
if (!strcmp(argument, "--force")) { LZ4IO_setOverwrite(prefs, 1); continue; }
|
||||
@@ -394,7 +474,7 @@ int main(int argc, const char** argv)
|
||||
if (!strcmp(argument, "--no-crc")) { LZ4IO_setStreamChecksumMode(prefs, 0); LZ4IO_setBlockChecksumMode(prefs, 0); BMK_skipChecksums(1); continue; }
|
||||
if (!strcmp(argument, "--content-size")) { LZ4IO_setContentSize(prefs, 1); continue; }
|
||||
if (!strcmp(argument, "--no-content-size")) { LZ4IO_setContentSize(prefs, 0); continue; }
|
||||
if (!strcmp(argument, "--list")) { mode = om_list; continue; }
|
||||
if (!strcmp(argument, "--list")) { mode = om_list; multiple_inputs = 1; continue; }
|
||||
if (!strcmp(argument, "--sparse")) { LZ4IO_setSparseFile(prefs, 2); continue; }
|
||||
if (!strcmp(argument, "--no-sparse")) { LZ4IO_setSparseFile(prefs, 0); continue; }
|
||||
if (!strcmp(argument, "--favor-decSpeed")) { LZ4IO_favorDecSpeed(prefs, 1); continue; }
|
||||
@@ -404,25 +484,30 @@ int main(int argc, const char** argv)
|
||||
if (!strcmp(argument, "--help")) { usage_advanced(exeName); goto _cleanup; }
|
||||
if (!strcmp(argument, "--keep")) { LZ4IO_setRemoveSrcFile(prefs, 0); continue; } /* keep source file (default) */
|
||||
if (!strcmp(argument, "--rm")) { LZ4IO_setRemoveSrcFile(prefs, 1); continue; }
|
||||
|
||||
if (longCommandWArg(&argument, "--threads")) {
|
||||
NEXT_UINT32(nbWorkers);
|
||||
continue;
|
||||
}
|
||||
if (longCommandWArg(&argument, "--fast")) {
|
||||
/* Parse optional acceleration factor */
|
||||
if (*argument == '=') {
|
||||
U32 fastLevel;
|
||||
++argument;
|
||||
fastLevel = readU32FromChar(&argument);
|
||||
if (fastLevel) {
|
||||
cLevel = -(int)fastLevel;
|
||||
} else {
|
||||
badusage(exeName);
|
||||
}
|
||||
} else if (*argument != 0) {
|
||||
/* Invalid character following --fast */
|
||||
badusage(exeName);
|
||||
/* Parse optional acceleration factor */
|
||||
if (*argument == '=') {
|
||||
U32 fastLevel;
|
||||
++argument;
|
||||
fastLevel = readU32FromChar(&argument);
|
||||
if (fastLevel) {
|
||||
cLevel = -(int)fastLevel;
|
||||
} else {
|
||||
cLevel = -1; /* default for --fast */
|
||||
badusage(exeName);
|
||||
}
|
||||
continue;
|
||||
} else if (*argument != 0) {
|
||||
/* Invalid character following --fast */
|
||||
badusage(exeName);
|
||||
} else {
|
||||
cLevel = -1; /* default for --fast */
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
/* For gzip(1) compatibility */
|
||||
if (!strcmp(argument, "--best")) { cLevel=LZ4HC_CLEVEL_MAX; continue; }
|
||||
@@ -463,14 +548,22 @@ int main(int argc, const char** argv)
|
||||
/* Compression (default) */
|
||||
case 'z': mode = om_compress; break;
|
||||
|
||||
/* Modify Nb Worker threads (compression only) */
|
||||
case 'T':
|
||||
{ argument++;
|
||||
nbWorkers = readU32FromChar(&argument);
|
||||
argument--;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'D':
|
||||
if (argument[1] == '\0') {
|
||||
/* path is next arg */
|
||||
if (i + 1 == argc) {
|
||||
if (argNb + 1 == argCount) {
|
||||
/* there is no next arg */
|
||||
badusage(exeName);
|
||||
}
|
||||
dictionary_filename = argv[++i];
|
||||
dictionary_filename = argv[++argNb];
|
||||
} else {
|
||||
/* path follows immediately */
|
||||
dictionary_filename = argument + 1;
|
||||
@@ -620,10 +713,16 @@ int main(int argc, const char** argv)
|
||||
DISPLAYLEVEL(4, "PLATFORM_POSIX_VERSION defined: %ldL\n", (long) PLATFORM_POSIX_VERSION);
|
||||
#endif
|
||||
#ifdef _FILE_OFFSET_BITS
|
||||
DISPLAYLEVEL(4, "_FILE_OFFSET_BITS defined: %ldL\n", (long) _FILE_OFFSET_BITS);
|
||||
DISPLAYLEVEL(5, "_FILE_OFFSET_BITS defined: %ldL\n", (long) _FILE_OFFSET_BITS);
|
||||
#endif
|
||||
if ((mode == om_compress) || (mode == om_bench))
|
||||
#if !LZ4IO_MULTITHREAD
|
||||
if (nbWorkers > 1) {
|
||||
DISPLAYLEVEL(2, "warning: this executable doesn't support multithreading \n");
|
||||
}
|
||||
#endif
|
||||
if ((mode == om_compress) || (mode == om_bench)) {
|
||||
DISPLAYLEVEL(4, "Blocks size : %u KB\n", (U32)(blockSize>>10));
|
||||
}
|
||||
|
||||
if (multiple_inputs) {
|
||||
input_filename = inFileNames[0];
|
||||
@@ -676,16 +775,7 @@ int main(int argc, const char** argv)
|
||||
}
|
||||
|
||||
/* No output filename ==> try to select one automatically (when possible) */
|
||||
while ((!output_filename) && (multiple_inputs==0)) {
|
||||
if (!IS_CONSOLE(stdout) && mode != om_list) {
|
||||
/* Default to stdout whenever stdout is not the console.
|
||||
* Note : this policy may change in the future, therefore don't rely on it !
|
||||
* To ensure `stdout` is explicitly selected, use `-c` command flag.
|
||||
* Conversely, to ensure output will not become `stdout`, use `-m` command flag */
|
||||
DISPLAYLEVEL(1, "Warning : using stdout as default output. Do not rely on this behavior: use explicit `-c` instead ! \n");
|
||||
output_filename = stdoutmark;
|
||||
break;
|
||||
}
|
||||
if ((!output_filename) && (multiple_inputs==0)) {
|
||||
if (mode == om_auto) { /* auto-determine compression or decompression, based on file extension */
|
||||
mode = determineOpMode(input_filename);
|
||||
}
|
||||
@@ -697,9 +787,9 @@ int main(int argc, const char** argv)
|
||||
strcat(dynNameSpace, LZ4_EXTENSION);
|
||||
output_filename = dynNameSpace;
|
||||
DISPLAYLEVEL(2, "Compressed filename will be : %s \n", output_filename);
|
||||
break;
|
||||
}
|
||||
if (mode == om_decompress) {/* decompress to file (automatic output name only works if input filename has correct format extension) */
|
||||
if (mode == om_decompress) {
|
||||
/* decompress to file (automatic output name only works if input filename has correct format extension) */
|
||||
size_t outl;
|
||||
size_t const inl = strlen(input_filename);
|
||||
dynNameSpace = (char*)calloc(1,inl+1);
|
||||
@@ -712,7 +802,6 @@ int main(int argc, const char** argv)
|
||||
output_filename = dynNameSpace;
|
||||
DISPLAYLEVEL(2, "Decoding file %s \n", output_filename);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
if (mode == om_list) {
|
||||
@@ -757,13 +846,27 @@ int main(int argc, const char** argv)
|
||||
} else if (mode == om_list){
|
||||
operationResult = LZ4IO_displayCompressedFilesInfo(inFileNames, ifnIdx);
|
||||
} else { /* compression is default action */
|
||||
#if LZ4IO_MULTITHREAD
|
||||
if (nbWorkers != 1) {
|
||||
if (nbWorkers==0)
|
||||
nbWorkers = (unsigned)LZ4IO_defaultNbWorkers();
|
||||
if (nbWorkers > LZ4_NBWORKERS_MAX) {
|
||||
DISPLAYLEVEL(3, "Requested %u threads too large => automatically reduced to %u \n",
|
||||
nbWorkers, LZ4_NBWORKERS_MAX);
|
||||
nbWorkers = LZ4_NBWORKERS_MAX;
|
||||
} else {
|
||||
DISPLAYLEVEL(3, "Using %u threads for compression \n", nbWorkers);
|
||||
}
|
||||
}
|
||||
LZ4IO_setNbWorkers(prefs, (int)nbWorkers);
|
||||
#endif
|
||||
if (legacy_format) {
|
||||
DISPLAYLEVEL(3, "! Generating LZ4 Legacy format (deprecated) ! \n");
|
||||
if(multiple_inputs){
|
||||
const char* const leg_extension = !strcmp(output_filename,stdoutmark) ? stdoutmark : LZ4_EXTENSION;
|
||||
LZ4IO_compressMultipleFilenames_Legacy(inFileNames, (int)ifnIdx, leg_extension, cLevel, prefs);
|
||||
operationResult = LZ4IO_compressMultipleFilenames_Legacy(inFileNames, (int)ifnIdx, leg_extension, cLevel, prefs);
|
||||
} else {
|
||||
LZ4IO_compressFilename_Legacy(input_filename, output_filename, cLevel, prefs);
|
||||
operationResult = LZ4IO_compressFilename_Legacy(input_filename, output_filename, cLevel, prefs);
|
||||
}
|
||||
} else {
|
||||
if (multiple_inputs) {
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
/*
|
||||
LZ4conf.h - compile-time parameters
|
||||
Copyright (C) Yann Collet 2011-2024
|
||||
GPL v2 License
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
You can contact the author at :
|
||||
- LZ4 source repository : https://github.com/lz4/lz4
|
||||
- LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c
|
||||
*/
|
||||
|
||||
#ifndef LZ4CONF_H_32432
|
||||
#define LZ4CONF_H_32432
|
||||
|
||||
|
||||
/* Default compression level.
|
||||
* Can be overridden by environment variable LZ4_CLEVEL.
|
||||
* Can be overridden at runtime using -# command */
|
||||
#ifndef LZ4_CLEVEL_DEFAULT
|
||||
# define LZ4_CLEVEL_DEFAULT 1
|
||||
#endif
|
||||
|
||||
/* Determines if multithreading is enabled or not
|
||||
* Default: disabled */
|
||||
#ifndef LZ4IO_MULTITHREAD
|
||||
# ifdef _WIN32
|
||||
/* Windows support Completion Ports */
|
||||
# define LZ4IO_MULTITHREAD 1
|
||||
# else
|
||||
/* Requires <pthread> support.
|
||||
* Can't be reliably and portably tested at source code level */
|
||||
# define LZ4IO_MULTITHREAD 0
|
||||
# endif
|
||||
#endif
|
||||
|
||||
/* Determines default nb of threads for compression
|
||||
* Default value is 0, which means "auto" :
|
||||
* nb of threads is determined from detected local cpu.
|
||||
* Can be overriden by Environment Variable LZ4_NBWORKERS.
|
||||
* Can be overridden at runtime using -T# command */
|
||||
#ifndef LZ4_NBWORKERS_DEFAULT
|
||||
# define LZ4_NBWORKERS_DEFAULT 0
|
||||
#endif
|
||||
|
||||
/* Maximum nb of compression threads selectable at runtime */
|
||||
#ifndef LZ4_NBWORKERS_MAX
|
||||
# define LZ4_NBWORKERS_MAX 200
|
||||
#endif
|
||||
|
||||
/* Determines default lz4 block size when none provided.
|
||||
* Default value is 7, which represents 4 MB.
|
||||
* Can be overridden at runtime using -B# command */
|
||||
#ifndef LZ4_BLOCKSIZEID_DEFAULT
|
||||
# define LZ4_BLOCKSIZEID_DEFAULT 7
|
||||
#endif
|
||||
|
||||
|
||||
#endif /* LZ4CONF_H_32432 */
|
||||
+1429
-284
File diff suppressed because it is too large
Load Diff
+7
-4
@@ -1,6 +1,6 @@
|
||||
/*
|
||||
LZ4io.h - LZ4 File/Stream Interface
|
||||
Copyright (C) Yann Collet 2011-2020
|
||||
Copyright (C) Yann Collet 2011-2023
|
||||
GPL v2 License
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
@@ -58,9 +58,9 @@ LZ4IO_prefs_t* LZ4IO_defaultPreferences(void);
|
||||
void LZ4IO_freePreferences(LZ4IO_prefs_t* prefs);
|
||||
|
||||
|
||||
/* ************************************************** */
|
||||
/* ****************** Functions ********************* */
|
||||
/* ************************************************** */
|
||||
/* *************************************************** */
|
||||
/* ****************** Processing ********************* */
|
||||
/* *************************************************** */
|
||||
|
||||
/* if output_filename == stdoutmark, writes to stdout */
|
||||
int LZ4IO_compressFilename(const char* input_filename, const char* output_filename, int compressionlevel, const LZ4IO_prefs_t* prefs);
|
||||
@@ -75,6 +75,9 @@ int LZ4IO_decompressMultipleFilenames(const char** inFileNamesTable, int ifntSiz
|
||||
/* ****************** Parameters ******************** */
|
||||
/* ************************************************** */
|
||||
|
||||
int LZ4IO_setNbWorkers(LZ4IO_prefs_t* const prefs, int nbWorkers);
|
||||
int LZ4IO_defaultNbWorkers(void);
|
||||
|
||||
int LZ4IO_setDictionaryFilename(LZ4IO_prefs_t* const prefs, const char* dictionaryFilename);
|
||||
|
||||
/* Default setting : passThrough = 0;
|
||||
|
||||
+3
-1
@@ -48,7 +48,9 @@ extern "C" {
|
||||
|| defined __x86_64__s || defined _M_X64 /* x86 64-bit */ \
|
||||
|| defined __arm64__ || defined __aarch64__ || defined __ARM64_ARCH_8__ /* ARM 64-bit */ \
|
||||
|| (defined __mips && (__mips == 64 || __mips == 4 || __mips == 3)) /* MIPS 64-bit */ \
|
||||
|| defined _LP64 || defined __LP64__ /* NetBSD, OpenBSD */ || defined __64BIT__ /* AIX */ || defined _ADDR64 /* Cray */ \
|
||||
|| defined __loongarch64 /* LoongArch 64-bit */ \
|
||||
|| (defined __riscv && defined __riscv_xlen && (__riscv_xlen == 64)) /* Riscv 64-bit */ \
|
||||
|| defined _LP64 || defined __LP64__ /* NetBSD, OpenBSD */ || defined __64BIT__ /* AIX */ || defined _ADDR64 /* Cray */ \
|
||||
|| (defined __SIZEOF_POINTER__ && __SIZEOF_POINTER__ == 8) /* gcc */
|
||||
# if !defined(__64BIT__)
|
||||
# define __64BIT__ 1
|
||||
|
||||
@@ -0,0 +1,430 @@
|
||||
/*
|
||||
threadpool.h - part of lz4 project
|
||||
Copyright (C) Yann Collet 2023
|
||||
GPL v2 License
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
You can contact the author at :
|
||||
- LZ4 source repository : https://github.com/lz4/lz4
|
||||
- LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c
|
||||
*/
|
||||
|
||||
|
||||
/* ====== Dependencies ======= */
|
||||
#include <assert.h>
|
||||
#include "lz4conf.h" /* LZ4IO_MULTITHREAD */
|
||||
#include "threadpool.h"
|
||||
|
||||
|
||||
/* ====== Compiler specifics ====== */
|
||||
#if defined(_MSC_VER)
|
||||
# pragma warning(disable : 4204) /* disable: C4204: non-constant aggregate initializer */
|
||||
#endif
|
||||
|
||||
#if !LZ4IO_MULTITHREAD
|
||||
|
||||
/* ===================================================== */
|
||||
/* Backup implementation with no multi-threading support */
|
||||
/* ===================================================== */
|
||||
|
||||
/* Non-zero size, to ensure g_poolCtx != NULL */
|
||||
struct TPool_s {
|
||||
int dummy;
|
||||
};
|
||||
static TPool g_poolCtx;
|
||||
|
||||
TPool* TPool_create(int numThreads, int queueSize) {
|
||||
(void)numThreads;
|
||||
(void)queueSize;
|
||||
return &g_poolCtx;
|
||||
}
|
||||
|
||||
void TPool_free(TPool* ctx) {
|
||||
assert(!ctx || ctx == &g_poolCtx);
|
||||
(void)ctx;
|
||||
}
|
||||
|
||||
void TPool_submitJob(TPool* ctx, void (*job_function)(void*), void* arg) {
|
||||
(void)ctx;
|
||||
job_function(arg);
|
||||
}
|
||||
|
||||
void TPool_jobsCompleted(TPool* ctx) {
|
||||
assert(!ctx || ctx == &g_poolCtx);
|
||||
(void)ctx;
|
||||
}
|
||||
|
||||
|
||||
#elif defined(_WIN32)
|
||||
|
||||
/* Window TPool implementation using Completion Ports */
|
||||
#include <windows.h>
|
||||
|
||||
typedef struct TPool_s {
|
||||
HANDLE completionPort;
|
||||
HANDLE* workerThreads;
|
||||
int nbWorkers;
|
||||
int queueSize;
|
||||
LONG nbPendingJobs;
|
||||
HANDLE jobSlotAvail; /* For queue size control */
|
||||
HANDLE allJobsCompleted; /* Event */
|
||||
} TPool;
|
||||
|
||||
void TPool_free(TPool* pool)
|
||||
{
|
||||
if (!pool) return;
|
||||
|
||||
/* Signal workers to exit by posting NULL completions */
|
||||
{ int i;
|
||||
for (i = 0; i < pool->nbWorkers; i++) {
|
||||
PostQueuedCompletionStatus(pool->completionPort, 0, 0, NULL);
|
||||
}
|
||||
}
|
||||
|
||||
/* Wait for worker threads to finish */
|
||||
WaitForMultipleObjects(pool->nbWorkers, pool->workerThreads, TRUE, INFINITE);
|
||||
|
||||
/* Close thread handles and completion port */
|
||||
{ int i;
|
||||
for (i = 0; i < pool->nbWorkers; i++) {
|
||||
CloseHandle(pool->workerThreads[i]);
|
||||
}
|
||||
}
|
||||
free(pool->workerThreads);
|
||||
CloseHandle(pool->completionPort);
|
||||
|
||||
/* Clean up synchronization objects */
|
||||
CloseHandle(pool->jobSlotAvail);
|
||||
CloseHandle(pool->allJobsCompleted);
|
||||
|
||||
free(pool);
|
||||
}
|
||||
|
||||
static DWORD WINAPI WorkerThread(LPVOID lpParameter)
|
||||
{
|
||||
TPool* const pool = (TPool*)lpParameter;
|
||||
DWORD bytesTransferred;
|
||||
ULONG_PTR completionKey;
|
||||
LPOVERLAPPED overlapped;
|
||||
|
||||
while (GetQueuedCompletionStatus(pool->completionPort,
|
||||
&bytesTransferred, &completionKey,
|
||||
&overlapped, INFINITE)) {
|
||||
|
||||
/* End signal */
|
||||
if (overlapped == NULL) { break; }
|
||||
|
||||
/* Execute job */
|
||||
((void (*)(void*))completionKey)(overlapped);
|
||||
|
||||
/* Signal job completion */
|
||||
if (InterlockedDecrement(&pool->nbPendingJobs) == 0) {
|
||||
SetEvent(pool->allJobsCompleted);
|
||||
}
|
||||
ReleaseSemaphore(pool->jobSlotAvail, 1, NULL);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
TPool* TPool_create(int nbWorkers, int queueSize)
|
||||
{
|
||||
TPool* pool;
|
||||
|
||||
/* parameters sanitization */
|
||||
if (nbWorkers <= 0 || queueSize <= 0) return NULL;
|
||||
if (nbWorkers>LZ4_NBWORKERS_MAX) nbWorkers=LZ4_NBWORKERS_MAX;
|
||||
|
||||
pool = calloc(1, sizeof(TPool));
|
||||
if (!pool) return NULL;
|
||||
|
||||
/* Create completion port */
|
||||
pool->completionPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, nbWorkers);
|
||||
if (!pool->completionPort) { goto _cleanup; }
|
||||
|
||||
/* Create worker threads */
|
||||
pool->nbWorkers = nbWorkers;
|
||||
pool->workerThreads = (HANDLE*)malloc(sizeof(HANDLE) * nbWorkers);
|
||||
if (pool->workerThreads == NULL) { goto _cleanup; }
|
||||
|
||||
{ int i;
|
||||
for (i = 0; i < nbWorkers; i++) {
|
||||
pool->workerThreads[i] = CreateThread(NULL, 0, WorkerThread, pool, 0, NULL);
|
||||
if (!pool->workerThreads[i]) { goto _cleanup; }
|
||||
}
|
||||
}
|
||||
|
||||
/* Initialize sync objects members */
|
||||
pool->queueSize = queueSize;
|
||||
pool->nbPendingJobs = 0;
|
||||
|
||||
pool->jobSlotAvail = CreateSemaphore(NULL, queueSize+nbWorkers, queueSize+nbWorkers, NULL);
|
||||
if (!pool->jobSlotAvail) { goto _cleanup; }
|
||||
|
||||
pool->allJobsCompleted = CreateEvent(NULL, FALSE, FALSE, NULL);
|
||||
if (!pool->allJobsCompleted) { goto _cleanup; }
|
||||
|
||||
return pool;
|
||||
|
||||
_cleanup:
|
||||
TPool_free(pool);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
|
||||
void TPool_submitJob(TPool* pool, void (*job_function)(void*), void* arg)
|
||||
{
|
||||
assert(pool);
|
||||
|
||||
/* Atomically increment pending jobs and check for overflow */
|
||||
WaitForSingleObject(pool->jobSlotAvail, INFINITE);
|
||||
ResetEvent(pool->allJobsCompleted);
|
||||
InterlockedIncrement(&pool->nbPendingJobs);
|
||||
|
||||
/* Post the job directly to the completion port */
|
||||
PostQueuedCompletionStatus(pool->completionPort,
|
||||
0, /* Bytes transferred not used */
|
||||
(ULONG_PTR)job_function, /* Store function pointer in completionKey */
|
||||
(LPOVERLAPPED)arg); /* Store argument in overlapped */
|
||||
}
|
||||
|
||||
void TPool_jobsCompleted(TPool* pool)
|
||||
{
|
||||
assert(pool);
|
||||
WaitForSingleObject(pool->allJobsCompleted, INFINITE);
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
/* pthread availability assumed */
|
||||
#include <stdlib.h> /* malloc, free */
|
||||
#include <pthread.h> /* pthread_* */
|
||||
|
||||
/* A job is just a function with an opaque argument */
|
||||
typedef struct TPool_job_s {
|
||||
void (*job_function)(void*);
|
||||
void *arg;
|
||||
} TPool_job;
|
||||
|
||||
struct TPool_s {
|
||||
pthread_t* threads;
|
||||
size_t threadCapacity;
|
||||
size_t threadLimit;
|
||||
|
||||
/* The queue is a circular buffer */
|
||||
TPool_job* queue;
|
||||
size_t queueHead;
|
||||
size_t queueTail;
|
||||
size_t queueSize;
|
||||
|
||||
/* The number of threads working on jobs */
|
||||
size_t numThreadsBusy;
|
||||
/* Indicates if the queue is empty */
|
||||
int queueEmpty;
|
||||
|
||||
/* The mutex protects the queue */
|
||||
pthread_mutex_t queueMutex;
|
||||
/* Condition variable for pushers to wait on when the queue is full */
|
||||
pthread_cond_t queuePushCond;
|
||||
/* Condition variables for poppers to wait on when the queue is empty */
|
||||
pthread_cond_t queuePopCond;
|
||||
/* Indicates if the queue is shutting down */
|
||||
int shutdown;
|
||||
};
|
||||
|
||||
static void TPool_shutdown(TPool* ctx);
|
||||
|
||||
void TPool_free(TPool* ctx) {
|
||||
if (!ctx) { return; }
|
||||
TPool_shutdown(ctx);
|
||||
pthread_mutex_destroy(&ctx->queueMutex);
|
||||
pthread_cond_destroy(&ctx->queuePushCond);
|
||||
pthread_cond_destroy(&ctx->queuePopCond);
|
||||
free(ctx->queue);
|
||||
free(ctx->threads);
|
||||
free(ctx);
|
||||
}
|
||||
|
||||
static void* TPool_thread(void* opaque);
|
||||
|
||||
TPool* TPool_create(int nbThreads, int queueSize)
|
||||
{
|
||||
TPool* ctx;
|
||||
/* Check parameters */
|
||||
if (nbThreads<1 || queueSize<1) { return NULL; }
|
||||
/* Allocate the context and zero initialize */
|
||||
ctx = (TPool*)calloc(1, sizeof(TPool));
|
||||
if (!ctx) { return NULL; }
|
||||
/* init pthread variables */
|
||||
{ int error = 0;
|
||||
error |= pthread_mutex_init(&ctx->queueMutex, NULL);
|
||||
error |= pthread_cond_init(&ctx->queuePushCond, NULL);
|
||||
error |= pthread_cond_init(&ctx->queuePopCond, NULL);
|
||||
if (error) { TPool_free(ctx); return NULL; }
|
||||
}
|
||||
/* Initialize the job queue.
|
||||
* It needs one extra space since one space is wasted to differentiate
|
||||
* empty and full queues.
|
||||
*/
|
||||
ctx->queueSize = (size_t)queueSize + 1;
|
||||
ctx->queue = (TPool_job*)calloc(1, ctx->queueSize * sizeof(TPool_job));
|
||||
if (ctx->queue == NULL) {
|
||||
TPool_free(ctx);
|
||||
return NULL;
|
||||
}
|
||||
ctx->queueHead = 0;
|
||||
ctx->queueTail = 0;
|
||||
ctx->numThreadsBusy = 0;
|
||||
ctx->queueEmpty = 1;
|
||||
ctx->shutdown = 0;
|
||||
/* Allocate space for the thread handles */
|
||||
ctx->threads = (pthread_t*)calloc(1, (size_t)nbThreads * sizeof(pthread_t));
|
||||
if (ctx->threads == NULL) {
|
||||
TPool_free(ctx);
|
||||
return NULL;
|
||||
}
|
||||
ctx->threadCapacity = 0;
|
||||
/* Initialize the threads */
|
||||
{ int i;
|
||||
for (i = 0; i < nbThreads; ++i) {
|
||||
if (pthread_create(&ctx->threads[i], NULL, &TPool_thread, ctx)) {
|
||||
ctx->threadCapacity = (size_t)i;
|
||||
TPool_free(ctx);
|
||||
return NULL;
|
||||
} }
|
||||
ctx->threadCapacity = (size_t)nbThreads;
|
||||
ctx->threadLimit = (size_t)nbThreads;
|
||||
}
|
||||
return ctx;
|
||||
}
|
||||
|
||||
/* TPool_thread() :
|
||||
* Work thread for the thread pool.
|
||||
* Waits for jobs and executes them.
|
||||
* @returns : NULL on failure else non-null.
|
||||
*/
|
||||
static void* TPool_thread(void* opaque) {
|
||||
TPool* const ctx = (TPool*)opaque;
|
||||
if (!ctx) { return NULL; }
|
||||
for (;;) {
|
||||
/* Lock the mutex and wait for a non-empty queue or until shutdown */
|
||||
pthread_mutex_lock(&ctx->queueMutex);
|
||||
|
||||
while ( ctx->queueEmpty
|
||||
|| (ctx->numThreadsBusy >= ctx->threadLimit) ) {
|
||||
if (ctx->shutdown) {
|
||||
/* even if !queueEmpty, (possible if numThreadsBusy >= threadLimit),
|
||||
* a few threads will be shutdown while !queueEmpty,
|
||||
* but enough threads will remain active to finish the queue */
|
||||
pthread_mutex_unlock(&ctx->queueMutex);
|
||||
return opaque;
|
||||
}
|
||||
pthread_cond_wait(&ctx->queuePopCond, &ctx->queueMutex);
|
||||
}
|
||||
/* Pop a job off the queue */
|
||||
{ TPool_job const job = ctx->queue[ctx->queueHead];
|
||||
ctx->queueHead = (ctx->queueHead + 1) % ctx->queueSize;
|
||||
ctx->numThreadsBusy++;
|
||||
ctx->queueEmpty = (ctx->queueHead == ctx->queueTail);
|
||||
/* Unlock the mutex, signal a pusher, and run the job */
|
||||
pthread_cond_signal(&ctx->queuePushCond);
|
||||
pthread_mutex_unlock(&ctx->queueMutex);
|
||||
|
||||
job.job_function(job.arg);
|
||||
|
||||
/* If the intended queue size was 0, signal after finishing job */
|
||||
pthread_mutex_lock(&ctx->queueMutex);
|
||||
ctx->numThreadsBusy--;
|
||||
pthread_cond_signal(&ctx->queuePushCond);
|
||||
pthread_mutex_unlock(&ctx->queueMutex);
|
||||
}
|
||||
} /* for (;;) */
|
||||
assert(0); /* Unreachable */
|
||||
}
|
||||
|
||||
/*! TPool_shutdown() :
|
||||
Shutdown the queue, wake any sleeping threads, and join all of the threads.
|
||||
*/
|
||||
static void TPool_shutdown(TPool* ctx) {
|
||||
/* Shut down the queue */
|
||||
pthread_mutex_lock(&ctx->queueMutex);
|
||||
ctx->shutdown = 1;
|
||||
pthread_mutex_unlock(&ctx->queueMutex);
|
||||
/* Wake up sleeping threads */
|
||||
pthread_cond_broadcast(&ctx->queuePushCond);
|
||||
pthread_cond_broadcast(&ctx->queuePopCond);
|
||||
/* Join all of the threads */
|
||||
{ size_t i;
|
||||
for (i = 0; i < ctx->threadCapacity; ++i) {
|
||||
pthread_join(ctx->threads[i], NULL); /* note : could fail */
|
||||
} }
|
||||
}
|
||||
|
||||
|
||||
/*! TPool_jobsCompleted() :
|
||||
* Waits for all queued jobs to finish executing.
|
||||
*/
|
||||
void TPool_jobsCompleted(TPool* ctx){
|
||||
pthread_mutex_lock(&ctx->queueMutex);
|
||||
while(!ctx->queueEmpty || ctx->numThreadsBusy > 0) {
|
||||
pthread_cond_wait(&ctx->queuePushCond, &ctx->queueMutex);
|
||||
}
|
||||
pthread_mutex_unlock(&ctx->queueMutex);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns 1 if the queue is full and 0 otherwise.
|
||||
*
|
||||
* When queueSize is 1 (pool was created with an intended queueSize of 0),
|
||||
* then a queue is empty if there is a thread free _and_ no job is waiting.
|
||||
*/
|
||||
static int isQueueFull(TPool const* ctx) {
|
||||
if (ctx->queueSize > 1) {
|
||||
return ctx->queueHead == ((ctx->queueTail + 1) % ctx->queueSize);
|
||||
} else {
|
||||
return (ctx->numThreadsBusy == ctx->threadLimit) ||
|
||||
!ctx->queueEmpty;
|
||||
}
|
||||
}
|
||||
|
||||
static void
|
||||
TPool_submitJob_internal(TPool* ctx, void (*job_function)(void*), void *arg)
|
||||
{
|
||||
TPool_job job;
|
||||
job.job_function = job_function;
|
||||
job.arg = arg;
|
||||
assert(ctx != NULL);
|
||||
if (ctx->shutdown) return;
|
||||
|
||||
ctx->queueEmpty = 0;
|
||||
ctx->queue[ctx->queueTail] = job;
|
||||
ctx->queueTail = (ctx->queueTail + 1) % ctx->queueSize;
|
||||
pthread_cond_signal(&ctx->queuePopCond);
|
||||
}
|
||||
|
||||
void TPool_submitJob(TPool* ctx, void (*job_function)(void*), void* arg)
|
||||
{
|
||||
assert(ctx != NULL);
|
||||
pthread_mutex_lock(&ctx->queueMutex);
|
||||
/* Wait until there is space in the queue for the new job */
|
||||
while (isQueueFull(ctx) && (!ctx->shutdown)) {
|
||||
pthread_cond_wait(&ctx->queuePushCond, &ctx->queueMutex);
|
||||
}
|
||||
TPool_submitJob_internal(ctx, job_function, arg);
|
||||
pthread_mutex_unlock(&ctx->queueMutex);
|
||||
}
|
||||
|
||||
#endif /* LZ4IO_NO_MT */
|
||||
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
threadpool.h - part of lz4 project
|
||||
Copyright (C) Yann Collet 2023
|
||||
GPL v2 License
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
You can contact the author at :
|
||||
- LZ4 source repository : https://github.com/lz4/lz4
|
||||
- LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c
|
||||
*/
|
||||
|
||||
#ifndef THREADPOOL_H
|
||||
#define THREADPOOL_H
|
||||
|
||||
#if defined (__cplusplus)
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
typedef struct TPool_s TPool;
|
||||
|
||||
/*! TPool_create() :
|
||||
* Create a thread pool with at most @nbThreads.
|
||||
* @nbThreads must be at least 1.
|
||||
* @queueSize is the maximum number of pending jobs before blocking.
|
||||
* @return : TPool* pointer on success, else NULL.
|
||||
*/
|
||||
TPool* TPool_create(int nbThreads, int queueSize);
|
||||
|
||||
/*! TPool_free() :
|
||||
* Free a thread pool returned by TPool_create().
|
||||
* Waits for the completion of running jobs before freeing resources.
|
||||
*/
|
||||
void TPool_free(TPool* ctx);
|
||||
|
||||
/*! TPool_submitJob() :
|
||||
* Add @job_function(arg) to the thread pool.
|
||||
* @ctx must be valid.
|
||||
* Invocation can block if queue is full.
|
||||
* Note: Ensure @arg's lifetime extends until @job_function completes.
|
||||
* Alternatively, @arg's lifetime must be managed by @job_function.
|
||||
*/
|
||||
void TPool_submitJob(TPool* ctx, void (*job_function)(void*), void* arg);
|
||||
|
||||
/*! TPool_jobsCompleted() :
|
||||
* Blocks until all queued jobs are completed.
|
||||
*/
|
||||
void TPool_jobsCompleted(TPool* ctx);
|
||||
|
||||
|
||||
|
||||
#if defined (__cplusplus)
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* THREADPOOL_H */
|
||||
@@ -0,0 +1,175 @@
|
||||
/*
|
||||
timefn.c - portable time measurement functions
|
||||
Copyright (C) Yann Collet 2023
|
||||
|
||||
GPL v2 License
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
You can contact the author at :
|
||||
- LZ4 source repository : https://github.com/lz4/lz4
|
||||
- LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c
|
||||
*/
|
||||
|
||||
/* === Dependencies === */
|
||||
|
||||
#include "timefn.h"
|
||||
#include <time.h> /* CLOCK_MONOTONIC, TIME_UTC */
|
||||
|
||||
/*-****************************************
|
||||
* Time functions
|
||||
******************************************/
|
||||
|
||||
#if defined(_WIN32) /* Windows */
|
||||
|
||||
# include <stdio.h> /* perror */
|
||||
# include <stdlib.h> /* abort */
|
||||
# include <windows.h> /* LARGE_INTEGER */
|
||||
|
||||
TIME_t TIME_getTime(void)
|
||||
{
|
||||
static LARGE_INTEGER ticksPerSecond;
|
||||
static int init = 0;
|
||||
if (!init) {
|
||||
if (!QueryPerformanceFrequency(&ticksPerSecond)) {
|
||||
perror("timefn::QueryPerformanceFrequency");
|
||||
abort();
|
||||
}
|
||||
init = 1;
|
||||
}
|
||||
{
|
||||
TIME_t r;
|
||||
LARGE_INTEGER x;
|
||||
QueryPerformanceCounter(&x);
|
||||
r.t = (Duration_ns)(x.QuadPart * 1000000000ULL / ticksPerSecond.QuadPart);
|
||||
return r;
|
||||
}
|
||||
}
|
||||
|
||||
#elif defined(__APPLE__) && defined(__MACH__)
|
||||
|
||||
# include <mach/mach_time.h> /* mach_timebase_info_data_t, mach_timebase_info, mach_absolute_time */
|
||||
|
||||
TIME_t TIME_getTime(void)
|
||||
{
|
||||
static mach_timebase_info_data_t rate;
|
||||
static int init = 0;
|
||||
if (!init) {
|
||||
mach_timebase_info(&rate);
|
||||
init = 1;
|
||||
}
|
||||
{
|
||||
TIME_t r;
|
||||
r.t = mach_absolute_time() * (Duration_ns)rate.numer
|
||||
/ (Duration_ns)rate.denom;
|
||||
return r;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* POSIX.1-2001 (optional) */
|
||||
#elif defined(CLOCK_MONOTONIC)
|
||||
|
||||
#include <stdlib.h> /* abort */
|
||||
#include <stdio.h> /* perror */
|
||||
|
||||
TIME_t TIME_getTime(void)
|
||||
{
|
||||
/* time must be initialized, othersize it may fail msan test.
|
||||
* No good reason, likely a limitation of timespec_get() for some target */
|
||||
struct timespec time = { 0, 0 };
|
||||
if (clock_gettime(CLOCK_MONOTONIC, &time) != 0) {
|
||||
perror("timefn::clock_gettime(CLOCK_MONOTONIC)");
|
||||
abort();
|
||||
}
|
||||
{ TIME_t r;
|
||||
r.t = (Duration_ns)time.tv_sec * 1000000000ULL
|
||||
+ (Duration_ns)time.tv_nsec;
|
||||
return r;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* C11 requires support of timespec_get().
|
||||
* However, FreeBSD 11 claims C11 compliance while lacking timespec_get().
|
||||
* Double confirm timespec_get() support by checking the definition of TIME_UTC.
|
||||
* However, some versions of Android manage to simultaneously define TIME_UTC
|
||||
* and lack timespec_get() support... */
|
||||
#elif (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) /* C11 */) \
|
||||
&& defined(TIME_UTC) && !defined(__ANDROID__)
|
||||
|
||||
# include <stdio.h> /* perror */
|
||||
# include <stdlib.h> /* abort */
|
||||
|
||||
TIME_t TIME_getTime(void)
|
||||
{
|
||||
/* time must be initialized, othersize it may fail msan test */
|
||||
struct timespec time = { 0, 0 };
|
||||
if (timespec_get(&time, TIME_UTC) != TIME_UTC) {
|
||||
perror("timefn::timespec_get(TIME_UTC)");
|
||||
abort();
|
||||
}
|
||||
{
|
||||
TIME_t r;
|
||||
r.t = (Duration_ns)time.tv_sec * 1000000000ULL
|
||||
+ (Duration_ns)time.tv_nsec;
|
||||
return r;
|
||||
}
|
||||
}
|
||||
|
||||
#else /* relies on standard C90 (note : clock_t produces wrong measurements \
|
||||
for multi-threaded workloads) */
|
||||
|
||||
TIME_t TIME_getTime(void)
|
||||
{
|
||||
TIME_t r;
|
||||
r.t = (Duration_ns)clock() * 1000000000ULL / CLOCKS_PER_SEC;
|
||||
return r;
|
||||
}
|
||||
|
||||
# define TIME_MT_MEASUREMENTS_NOT_SUPPORTED
|
||||
|
||||
#endif
|
||||
|
||||
/* ==== Common functions, valid for all time API ==== */
|
||||
|
||||
Duration_ns TIME_span_ns(TIME_t clockStart, TIME_t clockEnd)
|
||||
{
|
||||
return clockEnd.t - clockStart.t;
|
||||
}
|
||||
|
||||
Duration_ns TIME_clockSpan_ns(TIME_t clockStart)
|
||||
{
|
||||
TIME_t const clockEnd = TIME_getTime();
|
||||
return TIME_span_ns(clockStart, clockEnd);
|
||||
}
|
||||
|
||||
void TIME_waitForNextTick(void)
|
||||
{
|
||||
TIME_t const clockStart = TIME_getTime();
|
||||
TIME_t clockEnd;
|
||||
do {
|
||||
clockEnd = TIME_getTime();
|
||||
} while (TIME_span_ns(clockStart, clockEnd) == 0);
|
||||
}
|
||||
|
||||
int TIME_support_MT_measurements(void)
|
||||
{
|
||||
#if defined(TIME_MT_MEASUREMENTS_NOT_SUPPORTED)
|
||||
return 0;
|
||||
#else
|
||||
return 1;
|
||||
#endif
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
timefn.h - portable time measurement functions
|
||||
Copyright (C) Yann Collet 2023
|
||||
|
||||
GPL v2 License
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
You can contact the author at :
|
||||
- LZ4 source repository : https://github.com/lz4/lz4
|
||||
- LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c
|
||||
*/
|
||||
|
||||
#ifndef TIMEFN
|
||||
#define TIMEFN
|
||||
|
||||
#if defined(__cplusplus)
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/*-****************************************
|
||||
* Types
|
||||
******************************************/
|
||||
|
||||
typedef unsigned long long Duration_ns;
|
||||
|
||||
/* TIME_t contains a nanosecond time counter.
|
||||
* The absolute value is not meaningful.
|
||||
* It's only valid to compute Duration_ns between 2 measurements. */
|
||||
typedef struct {
|
||||
Duration_ns t;
|
||||
} TIME_t;
|
||||
#define TIME_INITIALIZER { 0 }
|
||||
|
||||
/*-****************************************
|
||||
* Time functions
|
||||
******************************************/
|
||||
|
||||
/* @return a TIME_t value to be compared to another one in order to compute a duration.
|
||||
* The absolute value returned is meaningless */
|
||||
TIME_t TIME_getTime(void);
|
||||
|
||||
/* Timer resolution can be low on some platforms.
|
||||
* To improve accuracy, it's recommended to wait for a new tick
|
||||
* before starting benchmark measurements */
|
||||
void TIME_waitForNextTick(void);
|
||||
|
||||
/* tells if TIME_getTime() returns correct time measurements
|
||||
* in scenarios involving multi-threaded workload.
|
||||
* note : this is not the case if only C90 clock_t measurements are available */
|
||||
int TIME_support_MT_measurements(void);
|
||||
|
||||
Duration_ns TIME_span_ns(TIME_t clockStart, TIME_t clockEnd);
|
||||
Duration_ns TIME_clockSpan_ns(TIME_t clockStart);
|
||||
|
||||
#if defined(__cplusplus)
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* TIMEFN */
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
/*
|
||||
util.h - utility functions
|
||||
Copyright (C) 2023, Yann Collet
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*/
|
||||
|
||||
#if defined (__cplusplus)
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
|
||||
/*-****************************************
|
||||
* Dependencies
|
||||
******************************************/
|
||||
#include "util.h" /* note : ensure that platform.h is included first ! */
|
||||
|
||||
/*-****************************************
|
||||
* count the number of cores
|
||||
******************************************/
|
||||
|
||||
#if defined(_WIN32)
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
int UTIL_countCores(void)
|
||||
{
|
||||
static int numCores = 0;
|
||||
if (numCores != 0) return numCores;
|
||||
|
||||
{ SYSTEM_INFO sysinfo;
|
||||
GetSystemInfo(&sysinfo);
|
||||
numCores = sysinfo.dwNumberOfProcessors;
|
||||
}
|
||||
|
||||
if (numCores == 0) {
|
||||
/* Unexpected result, fall back on 1 */
|
||||
return numCores = 1;
|
||||
}
|
||||
|
||||
return numCores;
|
||||
}
|
||||
|
||||
#elif defined(__APPLE__)
|
||||
|
||||
#include <sys/sysctl.h>
|
||||
|
||||
/* Use apple-provided syscall
|
||||
* see: man 3 sysctl */
|
||||
int UTIL_countCores(void)
|
||||
{
|
||||
static S32 numCores = 0; /* apple specifies int32_t */
|
||||
if (numCores != 0) return (int)numCores;
|
||||
|
||||
{ size_t size = sizeof(S32);
|
||||
int const ret = sysctlbyname("hw.logicalcpu", &numCores, &size, NULL, 0);
|
||||
if (ret != 0) {
|
||||
/* error: fall back on 1 */
|
||||
numCores = 1;
|
||||
}
|
||||
}
|
||||
return (int)numCores;
|
||||
}
|
||||
|
||||
#elif defined(__linux__)
|
||||
|
||||
int UTIL_countCores(void)
|
||||
{
|
||||
static int numCores = 0;
|
||||
|
||||
if (numCores != 0) return numCores;
|
||||
|
||||
numCores = (int)sysconf(_SC_NPROCESSORS_ONLN);
|
||||
if (numCores == -1) {
|
||||
/* value not queryable, fall back on 1 */
|
||||
return numCores = 1;
|
||||
}
|
||||
|
||||
return numCores;
|
||||
}
|
||||
|
||||
#elif defined(__FreeBSD__)
|
||||
|
||||
#include <stdio.h> /* perror */
|
||||
#include <errno.h>
|
||||
#include <sys/param.h>
|
||||
#include <sys/sysctl.h>
|
||||
|
||||
/* Use physical core sysctl when available
|
||||
* see: man 4 smp, man 3 sysctl */
|
||||
int UTIL_countCores(void)
|
||||
{
|
||||
static int numCores = 0; /* freebsd sysctl is native int sized */
|
||||
if (numCores != 0) return numCores;
|
||||
|
||||
#if __FreeBSD_version >= 1300008
|
||||
{ size_t size = sizeof(numCores);
|
||||
int ret = sysctlbyname("kern.smp.cores", &numCores, &size, NULL, 0);
|
||||
if (ret == 0) {
|
||||
int perCore = 1;
|
||||
ret = sysctlbyname("kern.smp.threads_per_core", &perCore, &size, NULL, 0);
|
||||
/* default to physical cores if logical cannot be read */
|
||||
if (ret != 0) /* error */
|
||||
return numCores;
|
||||
numCores *= perCore;
|
||||
return numCores;
|
||||
}
|
||||
if (errno != ENOENT) {
|
||||
perror("lz4: can't get number of cpus");
|
||||
exit(1);
|
||||
}
|
||||
/* sysctl not present, fall through to older sysconf method */
|
||||
}
|
||||
#endif
|
||||
|
||||
numCores = (int)sysconf(_SC_NPROCESSORS_ONLN);
|
||||
if (numCores == -1) {
|
||||
/* value not queryable, fall back on 1 */
|
||||
numCores = 1;
|
||||
}
|
||||
return numCores;
|
||||
}
|
||||
|
||||
#elif defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__CYGWIN__)
|
||||
|
||||
/* Use POSIX sysconf
|
||||
* see: man 3 sysconf */
|
||||
int UTIL_countCores(void)
|
||||
{
|
||||
static int numCores = 0;
|
||||
if (numCores != 0) return numCores;
|
||||
|
||||
numCores = (int)sysconf(_SC_NPROCESSORS_ONLN);
|
||||
if (numCores == -1) {
|
||||
/* value not queryable, fall back on 1 */
|
||||
numCores = 1;
|
||||
}
|
||||
return numCores;
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
int UTIL_countCores(void)
|
||||
{
|
||||
/* no clue */
|
||||
return 1;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
#if defined (__cplusplus)
|
||||
}
|
||||
#endif
|
||||
+13
-143
@@ -1,6 +1,6 @@
|
||||
/*
|
||||
util.h - utility functions
|
||||
Copyright (C) 2016-2020, Przemyslaw Skibinski, Yann Collet
|
||||
Copyright (C) 2016-2023, Przemyslaw Skibinski, Yann Collet
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -91,6 +91,10 @@ extern "C" {
|
||||
# define UTIL_fseek fseek
|
||||
#endif
|
||||
|
||||
/*-****************************************
|
||||
* Local host Core counting
|
||||
******************************************/
|
||||
int UTIL_countCores(void);
|
||||
|
||||
/*-****************************************
|
||||
* Sleep functions: Windows - Posix - others
|
||||
@@ -195,148 +199,16 @@ UTIL_STATIC void* UTIL_realloc(void* ptr, size_t size)
|
||||
/*-****************************************
|
||||
* String functions
|
||||
******************************************/
|
||||
/*
|
||||
* A modified version of realloc().
|
||||
* If UTIL_realloc() fails the original block is freed.
|
||||
*/
|
||||
/* supports a==NULL or b==NULL */
|
||||
UTIL_STATIC int UTIL_sameString(const char* a, const char* b)
|
||||
{
|
||||
assert(a!=NULL && b!=NULL); /* unsupported scenario */
|
||||
assert(a != NULL || b != NULL); /* unsupported scenario */
|
||||
if (a==NULL) return 0;
|
||||
if (b==NULL) return 0;
|
||||
return !strcmp(a,b);
|
||||
}
|
||||
|
||||
|
||||
/*-****************************************
|
||||
* Time functions
|
||||
******************************************/
|
||||
#if defined(_WIN32) /* Windows */
|
||||
|
||||
typedef LARGE_INTEGER UTIL_time_t;
|
||||
UTIL_STATIC UTIL_time_t UTIL_getTime(void) { UTIL_time_t x; QueryPerformanceCounter(&x); return x; }
|
||||
UTIL_STATIC U64 UTIL_getSpanTimeMicro(UTIL_time_t clockStart, UTIL_time_t clockEnd)
|
||||
{
|
||||
static LARGE_INTEGER ticksPerSecond;
|
||||
static int init = 0;
|
||||
if (!init) {
|
||||
if (!QueryPerformanceFrequency(&ticksPerSecond))
|
||||
fprintf(stderr, "ERROR: QueryPerformanceFrequency() failure\n");
|
||||
init = 1;
|
||||
}
|
||||
return 1000000ULL*(clockEnd.QuadPart - clockStart.QuadPart)/ticksPerSecond.QuadPart;
|
||||
}
|
||||
UTIL_STATIC U64 UTIL_getSpanTimeNano(UTIL_time_t clockStart, UTIL_time_t clockEnd)
|
||||
{
|
||||
static LARGE_INTEGER ticksPerSecond;
|
||||
static int init = 0;
|
||||
if (!init) {
|
||||
if (!QueryPerformanceFrequency(&ticksPerSecond))
|
||||
fprintf(stderr, "ERROR: QueryPerformanceFrequency() failure\n");
|
||||
init = 1;
|
||||
}
|
||||
return 1000000000ULL*(clockEnd.QuadPart - clockStart.QuadPart)/ticksPerSecond.QuadPart;
|
||||
}
|
||||
|
||||
#elif defined(__APPLE__) && defined(__MACH__)
|
||||
|
||||
#include <mach/mach_time.h>
|
||||
typedef U64 UTIL_time_t;
|
||||
UTIL_STATIC UTIL_time_t UTIL_getTime(void) { return mach_absolute_time(); }
|
||||
UTIL_STATIC U64 UTIL_getSpanTimeMicro(UTIL_time_t clockStart, UTIL_time_t clockEnd)
|
||||
{
|
||||
static mach_timebase_info_data_t rate;
|
||||
static int init = 0;
|
||||
if (!init) {
|
||||
mach_timebase_info(&rate);
|
||||
init = 1;
|
||||
}
|
||||
return (((clockEnd - clockStart) * (U64)rate.numer) / ((U64)rate.denom)) / 1000ULL;
|
||||
}
|
||||
UTIL_STATIC U64 UTIL_getSpanTimeNano(UTIL_time_t clockStart, UTIL_time_t clockEnd)
|
||||
{
|
||||
static mach_timebase_info_data_t rate;
|
||||
static int init = 0;
|
||||
if (!init) {
|
||||
mach_timebase_info(&rate);
|
||||
init = 1;
|
||||
}
|
||||
return ((clockEnd - clockStart) * (U64)rate.numer) / ((U64)rate.denom);
|
||||
}
|
||||
|
||||
#elif (PLATFORM_POSIX_VERSION >= 200112L) && (defined __UCLIBC__ || (defined(__GLIBC__) && ((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 17) || __GLIBC__ > 2) ) )
|
||||
|
||||
#include <time.h>
|
||||
typedef struct timespec UTIL_time_t;
|
||||
UTIL_STATIC UTIL_time_t UTIL_getTime(void)
|
||||
{
|
||||
UTIL_time_t now;
|
||||
if (clock_gettime(CLOCK_MONOTONIC, &now))
|
||||
fprintf(stderr, "ERROR: Failed to get time\n"); /* we could also exit() */
|
||||
return now;
|
||||
}
|
||||
UTIL_STATIC UTIL_time_t UTIL_getSpanTime(UTIL_time_t begin, UTIL_time_t end)
|
||||
{
|
||||
UTIL_time_t diff;
|
||||
if (end.tv_nsec < begin.tv_nsec) {
|
||||
diff.tv_sec = (end.tv_sec - 1) - begin.tv_sec;
|
||||
diff.tv_nsec = (end.tv_nsec + 1000000000ULL) - begin.tv_nsec;
|
||||
} else {
|
||||
diff.tv_sec = end.tv_sec - begin.tv_sec;
|
||||
diff.tv_nsec = end.tv_nsec - begin.tv_nsec;
|
||||
}
|
||||
return diff;
|
||||
}
|
||||
UTIL_STATIC U64 UTIL_getSpanTimeMicro(UTIL_time_t begin, UTIL_time_t end)
|
||||
{
|
||||
UTIL_time_t const diff = UTIL_getSpanTime(begin, end);
|
||||
U64 micro = 0;
|
||||
micro += 1000000ULL * diff.tv_sec;
|
||||
micro += diff.tv_nsec / 1000ULL;
|
||||
return micro;
|
||||
}
|
||||
UTIL_STATIC U64 UTIL_getSpanTimeNano(UTIL_time_t begin, UTIL_time_t end)
|
||||
{
|
||||
UTIL_time_t const diff = UTIL_getSpanTime(begin, end);
|
||||
U64 nano = 0;
|
||||
nano += 1000000000ULL * diff.tv_sec;
|
||||
nano += diff.tv_nsec;
|
||||
return nano;
|
||||
}
|
||||
|
||||
#else /* relies on standard C (note : clock_t measurements can be wrong when using multi-threading) */
|
||||
|
||||
typedef clock_t UTIL_time_t;
|
||||
UTIL_STATIC UTIL_time_t UTIL_getTime(void) { return clock(); }
|
||||
UTIL_STATIC U64 UTIL_getSpanTimeMicro(UTIL_time_t clockStart, UTIL_time_t clockEnd) { return 1000000ULL * (clockEnd - clockStart) / CLOCKS_PER_SEC; }
|
||||
UTIL_STATIC U64 UTIL_getSpanTimeNano(UTIL_time_t clockStart, UTIL_time_t clockEnd) { return 1000000000ULL * (clockEnd - clockStart) / CLOCKS_PER_SEC; }
|
||||
#endif
|
||||
|
||||
|
||||
/* returns time span in microseconds */
|
||||
UTIL_STATIC U64 UTIL_clockSpanMicro(UTIL_time_t clockStart)
|
||||
{
|
||||
UTIL_time_t const clockEnd = UTIL_getTime();
|
||||
return UTIL_getSpanTimeMicro(clockStart, clockEnd);
|
||||
}
|
||||
|
||||
/* returns time span in nanoseconds */
|
||||
UTIL_STATIC U64 UTIL_clockSpanNano(UTIL_time_t clockStart)
|
||||
{
|
||||
UTIL_time_t const clockEnd = UTIL_getTime();
|
||||
return UTIL_getSpanTimeNano(clockStart, clockEnd);
|
||||
}
|
||||
|
||||
UTIL_STATIC void UTIL_waitForNextTick(void)
|
||||
{
|
||||
UTIL_time_t const clockStart = UTIL_getTime();
|
||||
UTIL_time_t clockEnd;
|
||||
do {
|
||||
clockEnd = UTIL_getTime();
|
||||
} while (UTIL_getSpanTimeNano(clockStart, clockEnd) == 0);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*-****************************************
|
||||
* File functions
|
||||
@@ -412,7 +284,6 @@ UTIL_STATIC int UTIL_getFileStat(const char* infilename, stat_t *statbuf)
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
||||
UTIL_STATIC int UTIL_isRegFD(int fd)
|
||||
{
|
||||
stat_t statbuf;
|
||||
@@ -423,26 +294,25 @@ UTIL_STATIC int UTIL_isRegFD(int fd)
|
||||
return UTIL_getFDStat(fd, &statbuf); /* Only need to know whether it is a regular file */
|
||||
}
|
||||
|
||||
|
||||
UTIL_STATIC int UTIL_isRegFile(const char* infilename)
|
||||
{
|
||||
stat_t statbuf;
|
||||
return UTIL_getFileStat(infilename, &statbuf); /* Only need to know whether it is a regular file */
|
||||
}
|
||||
|
||||
|
||||
UTIL_STATIC U32 UTIL_isDirectory(const char* infilename)
|
||||
UTIL_STATIC int UTIL_isDirectory(const char* infilename)
|
||||
{
|
||||
int r;
|
||||
stat_t statbuf;
|
||||
int r;
|
||||
#if defined(_MSC_VER)
|
||||
r = _stat64(infilename, &statbuf);
|
||||
if (!r && (statbuf.st_mode & _S_IFDIR)) return 1;
|
||||
if (r) return 0;
|
||||
return (statbuf.st_mode & S_IFDIR);
|
||||
#else
|
||||
r = stat(infilename, &statbuf);
|
||||
if (!r && S_ISDIR(statbuf.st_mode)) return 1;
|
||||
if (r) return 0;
|
||||
return (S_ISDIR(statbuf.st_mode));
|
||||
#endif
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user