pax_global_header00006660000000000000000000000064133644177270014530gustar00rootroot0000000000000052 comment=9b212156a7f8a920ac79bbdde24e8fcf2043dcc1 res-5.0.1/000077500000000000000000000000001336441772700123245ustar00rootroot00000000000000res-5.0.1/.gitignore000066400000000000000000000000401336441772700143060ustar00rootroot00000000000000.*.swp .merlin *.install _build res-5.0.1/CHANGES.md000066400000000000000000000002061336441772700137140ustar00rootroot00000000000000### 5.0.1 (2018-10-25) * Switched to dune, dune-release, and OPAM 2.0 ### 5.0.0 (2017-08-02) * Switched to jbuilder and topkg res-5.0.1/LICENSE.md000066400000000000000000000654331336441772700137430ustar00rootroot00000000000000Copyright (c) 1999- Markus Mottl The Library is distributed under the terms of the GNU Lesser General Public License version 2.1 (included below). As a special exception to the GNU Lesser General Public License, you may link, statically or dynamically, a "work that uses the Library" with a publicly distributed version of the Library to produce an executable file containing portions of the Library, and distribute that executable file under terms of your choice, without any of the additional requirements listed in clause 6 of the GNU Lesser General Public License. By "a publicly distributed version of the Library", we mean either the unmodified Library as distributed by the authors, or a modified version of the Library that is distributed under the conditions defined in clause 3 of the GNU Lesser General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU Lesser General Public License. --------------------------------------------------------------------------- ### GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 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. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] ### Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, 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 and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. ### TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION **0.** This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, 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 library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. **1.** You may copy and distribute verbatim copies of the Library's complete 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 distribute a copy of this License along with the Library. 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. **2.** You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, 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)** The modified work must itself be a software library. - **b)** You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. - **c)** You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. - **d)** If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, 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 Library, 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. 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 Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. **3.** You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. **4.** You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you 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. If distribution of 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 satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. **5.** A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. **6.** As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: - **a)** Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) - **b)** Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. - **c)** Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. - **d)** If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. - **e)** Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be 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. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. **7.** You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: - **a)** Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. - **b)** Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. **8.** You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library 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.** 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 Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. **10.** Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library 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 with this License. **11.** 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 Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library 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 Library. 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. **12.** If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library 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. **13.** The Free Software Foundation may publish revised and/or new versions of the Lesser 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 Library 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 Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. **14.** If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, 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** **15.** BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "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 LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. **16.** 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 LIBRARY 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 LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), 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 Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. 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 library's name and an idea of what it does. Copyright (C) year name of author This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; 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. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. signature of Ty Coon, 1 April 1990 Ty Coon, President of Vice That's all there is to it! res-5.0.1/Makefile000066400000000000000000000001341336441772700137620ustar00rootroot00000000000000.PHONY: all clean doc all: dune build @install clean: dune clean doc: dune build @doc res-5.0.1/README.md000066400000000000000000000150361336441772700136100ustar00rootroot00000000000000## RES - Automatically Resizing Contiguous Memory for OCaml ### What is RES? This OCaml-library consists of a set of modules which implement automatically resizing (= reallocating) data structures that consume a contiguous part of memory. This allows appending and removing of elements to/from arrays (both boxed and unboxed), strings (buffers), bit strings and weak arrays while still maintaining fast constant-time access to elements. There are also functors that allow the generation of similar modules which use different reallocation strategies. ### Features * Fast constant-time access to indexed elements (e.g. in arrays and strings) is often a prerequisite for short execution times of programs. Still, operations like adding and/or removing elements to/from the end of such data structures are often needed. Unfortunately, having both properties at the same time sometimes requires reallocating this contiguous part of memory. This module does not eliminate this problem, but hides the process of reallocation from the user, i.e. it happens automatically. Thus, the user is liberated from this bug-attracting (e.g. index errors) task. * This library allows the user to parameterize allocation strategies at runtime. This is an important feature, because it is impossible for any allocation algorithm to perform optimally without having knowledge about the user program. For example, the programmer might know that a consecutive series of operations will alternately add and remove large batches of elements. In such a case it would be wise to keep a high reserve of available slots in the data structure, because otherwise it will resize very often during this procedure which requires a significant amount of time. By raising a corresponding threshold in appropriate places at runtime, programmers can fine-tune the behavior of e.g. their buffers for optimal performance and set this parameter back later to save memory. * Because optimal reallocation strategies may be quite complex, it was also a design goal to have users supply their own ones (if required). By using functors users can parameterize these data structures with their own reallocation strategies, giving them even more control over how and when reallocations are triggered. * Users may want to add support for additional low-level implementations that require reallocations. In this case, too, it is fairly easy to create new modules by using functors. * The library implements a large interface of functions, all of which are completely independent of the reallocation strategy and the low-level implementation. All the interfaces of the corresponding low-level implementations of data structures (e.g. array, string) are fully supported and have been extended with further functionality. There is even a new buffer module which can be used in every context of the standard one. * OCaml makes a distinction between unboxed and boxed arrays. If the type of an array is `float`, the representation will be unboxed in cases in which the array is not used in a polymorphic context (native code only). To benefit from these much faster representations there are specialized versions of automatically resizing arrays in the distribution. ### Usage The API is fully documented and can be built as HTML using `make doc`. It is also available [online](http://mmottl.github.io/res/api/res). The preparameterized modules (default strategy) and the functors for mapping strategy-implementations to this kind of modules are contained and documented in file `lib/res.mli`. For examples of how to use the functors to implement new strategies and/or low-level representations, take a look at the implementation in `lib/res.ml`. Their function interface, however, is documented in files `lib/pres_intf.ml` (for parameterized "low-level" types like e.g. normal arrays) and in `lib/nopres_intf.ml` (for non-parameterized "low-level" types like e.g. float arrays, strings (buffers), etc.). #### Convenience It should be noted that it is possible to use the standard notation for accessing elements (e.g. `ar.(42)`) with resizable arrays (and even with `Buffer`, `Bits`, etc...). This requires a short explanation of how OCaml treats such syntactic sugar: All that OCaml does is that it replaces such syntax with an appropriate `Array.get` or `Array.set`. This may be _any_ module that happens to be bound to this name in the current scope. The same principle is true for the `String`-module and the `.[]`-operator. Thus, the following works: ```ocaml module Array = Res.Bits module String = Res.Buffer let () = let ar = Array.empty () in Array.add_one ar true; print_endline (string_of_bool ar.(0)); let str = String.empty () in String.add_one str 'x'; print_char str.[0]; print_newline () ``` Do not forget that it is even possible to bind modules locally. Example: ```ocaml let () = let module Array = Res.Array in Printf.printf "%d\n" (Array.init 10 (fun x -> x * x)).(7) ``` If you want to change one of your files to make use of resizable arrays instead of standard ones without much trouble, please read the following: You may want to "save" the standard `Array`-module and its type for later access: ```ocaml module StdArray = Array type 'a std_array = 'a array ``` Make the resizable implementation (includes the index operators!) available: ```ocaml open Res ``` Or more explicitly: ```ocaml module Array = Res.Array ``` Or if you want to use a specific `Array`-implementation: ```ocaml module Array = Res.Bits ``` Then set the type: ```ocaml type 'a array = 'a Array.t ``` If you create standard arrays with the built-in syntax, change lines like: ```ocaml let ar = [| 1; 2; 3; 4 |] in ``` to: ```ocaml let ar = Array.of_array [| 1; 2; 3; 4 |] in ``` This should allow all of your sources to compile out-of-the-box with the additional functionality. In places where you still need the standard implementation you should have no problems to use the rebound module and type to do so. This trick works similarly for the old and the new Buffer-module. You might also want to replace the `String`-module in this fashion. The latter one, however, supports a number of functions like e.g. `escape`, which are not available then. ### Contact Information and Contributing Please submit bugs reports, feature requests, contributions and similar to the [GitHub issue tracker](https://github.com/mmottl/res/issues). Up-to-date information is available at: res-5.0.1/TODO.md000066400000000000000000000001501336441772700134070ustar00rootroot00000000000000 * Extend the functionality of bit-vectors with efficient functions for e.g. "land", "lor", etc... res-5.0.1/dune000066400000000000000000000001411336441772700131760ustar00rootroot00000000000000(env (dev (flags (:standard -w -9 -principal))) (release (ocamlopt_flags (:standard -O3))) ) res-5.0.1/dune-project000066400000000000000000000000331336441772700146420ustar00rootroot00000000000000(lang dune 1.1) (name res) res-5.0.1/examples/000077500000000000000000000000001336441772700141425ustar00rootroot00000000000000res-5.0.1/examples/Makefile000066400000000000000000000002071336441772700156010ustar00rootroot00000000000000TARGETS = $(addsuffix .bc, buffer_ex defstrat stupid_ga weak_ex) .PHONY: all clean all: @dune build $(TARGETS) clean: @dune clean res-5.0.1/examples/buffer_ex.ml000066400000000000000000000005301336441772700164370ustar00rootroot00000000000000(* Reads a file given as first argument into a buffer and prints it out again. Uses an exponentially growing read-ahead during reading (just for demonstration). *) let _ = let buf = Res.Buffer.empty () and file = open_in Sys.argv.(1) in Res.Buffer.add_full_channel_f buf file 50000 (( * ) 2); Res.Buffer.output_buffer stdout buf res-5.0.1/examples/defstrat.ml000066400000000000000000000005761336441772700163200ustar00rootroot00000000000000(* Demonstration of the default reallocation strategy in action *) open Res.Array let info v r = Printf.printf "virtual length: %3d real length: %3d\n" v r let _ = let ar = empty () in for _i = 1 to 100 do info (length ar) (real_length ar); add_one ar 42 done; for _i = 1 to 20 do info (length ar) (real_length ar); remove_n ar 5 done; info (length ar) (real_length ar) res-5.0.1/examples/dune000066400000000000000000000001201336441772700150110ustar00rootroot00000000000000(executables (names buffer_ex defstrat stupid_ga weak_ex) (libraries res) ) res-5.0.1/examples/stupid_ga.ml000066400000000000000000000060641336441772700164610ustar00rootroot00000000000000(* You want to write a GA in less than 100 lines using bit-vectors? Here you go... (brain-dead implementation) *) module type GA_SPEC = sig val ngenes : int (* Number of genes *) val mut_prob : int (* Mutation probability in % *) val recomb_prob : int (* Recombination probability *) val evaluate_indiv : Res.Bits.t -> float (* Evaluate Individual *) end module Ga (Spec : GA_SPEC) = struct open Spec module Genes = Res.Bits type genes = Genes.t type indiv = {mutable genes : genes; mutable fitness : float option} type population = indiv array let random_bit () = Random.int 2 > 0 let create_indiv () = {genes = Genes.init ngenes (fun _ -> random_bit ()); fitness = None} let print_indiv ch indiv = let print_genes ch = Genes.iter (fun g -> output_char ch (if g then '1' else '0')) and fitness = match indiv.fitness with None -> "N/A" | Some f -> string_of_float f in Printf.fprintf ch "%a -> (%s)" print_genes indiv.genes fitness let mutate_indiv indiv = let mutate_gene i _gene = if Random.int 100 < mut_prob then Genes.set indiv.genes i (if Genes.get indiv.genes i then false else true) in Genes.iteri mutate_gene indiv.genes; indiv.fitness <- None let evaluate_indiv indiv = match indiv.fitness with | Some x -> x | None -> let x = Spec.evaluate_indiv indiv.genes in indiv.fitness <- Some x; x let create_pop size = Array.init size (fun _ -> create_indiv ()) let mutate_pop = Array.iter mutate_indiv let recombine_indiv i1 i2 c = Genes.blit i2.genes c i1.genes c (ngenes - c); i1.fitness <- None let evaluate_pop pop = Array.fold_left (fun acc indiv -> if evaluate_indiv indiv < evaluate_indiv acc then indiv else acc) pop.(0) pop let recombine_pop p = let len = Array.length p in let recombine i indiv = if i + 1 < len && Random.int 100 < recomb_prob then let mate = i + Random.int (len - i - 1) + 1 in recombine_indiv indiv p.(mate) (Random.int ngenes) in Array.iteri recombine p let select_pop p = let compare a b = match a.fitness, b.fitness with | Some af, Some bf -> compare bf af | _ -> failwith "select_pop: unevaluated individual!" in Array.sort compare p; for i = 0 to Array.length p / 2 do p.(i) <- create_indiv () done; end module MyGA_Spec = struct let ngenes = 20 let mut_prob = 3 let recomb_prob = 70 (* Tries to evolve binary representation of 42 - cool! *) let evaluate_indiv genes = let sum = ref 0 in Res.Bits.iter (fun g -> sum := (!sum lsl 1) + (if g then 1 else 0)) genes; let res = float !sum -. float 42 in res *. res end module MyGA = Ga(MyGA_Spec) open MyGA let _ = Random.self_init (); let p = create_pop 100 in let best = ref p.(0) in while best := evaluate_pop p; !best.fitness <> Some 0.0 do Printf.printf "best so far: %a\n" print_indiv !best; flush stdout; select_pop p; recombine_pop p; mutate_pop p done; Printf.printf "The winner is: %a\n" print_indiv !best res-5.0.1/examples/weak_ex.ml000066400000000000000000000007671336441772700161310ustar00rootroot00000000000000(* Demonstrates the correct behaviour of resizable weak arrays. *) module W = Res.Weak module Array = W (* allows more convenient array access *) class foo = object end let ra = W.empty () let _ = W.add_one ra (Some (new foo)); match ra.(0) with | Some _ -> print_endline "Correctly allocated!" | _ -> print_endline "Already deallocated??" let _ = Gc.full_major (); match ra.(0) with | Some _ -> print_endline "Still not deallocated?" | _ -> print_endline "Correctly deallocated!" res-5.0.1/pre-v5.0.0-CHANGES.txt000066400000000000000000000133451336441772700155530ustar00rootroot000000000000002017-01-18: Changed license to LGPL 2.1 2014-12-18: Fixed a bug in the "remove_range" function. 2014-10-23: Fixed string handling for new OCaml version 4.02 (String/Bytes modules). Requires new findlib version (>= 1.5). 2014-07-06: Moved to GitHub. 2013-06-12: Fixed a bug in the fill functions that made them not behave according to specification when filling past the end. 2012-07-20: Downgraded findlib version requirement to support the Debian testing branch. 2012-07-15: New major release version 4.0.0: * Upgraded to OCaml 4.00 * Switched to Oasis for packaging * Switched to OCamlBuild for the build process * Rewrote README in Markdown * Added stricter compilation flags 2009-06-01: Robustified implementation to avoid internal use of Obg.magic. 2008-09-16: Changed strategy API to greatly improve performance of growing/shrinking. 2008-05-09: Added unsafe_expose_array to parameterized resizable arrays. 2006-11-22: Updated OCamlMakefile. 2005-12-26: Fixed a build problem. 2005-10-24: Added sof_list. 2004-04-11: Removed use of unsafe external function that depends on current CVS-version. 2004-01-28: Renamed external function for compatibility with most recent OCaml-version. Updated OCamlMakefile. 2003-04-09: Updated OCamlMakefile. Fixed an installation problem. 2003-01-07: Updated OCamlMakefile to make use of "findlib". 2002-09-23: Fixed a bug in "remove_n" (arguments not fully checked). Slightly improved efficiency. 2002-09-11: Updated OCamlMakefile and license. Documented all modules for ocamldoc. Changed module Res for better accessibility. Made resizable weak arrays conform to module Weak again. 2002-05-04: Revised the whole installation procedure. See INSTALL for details. 2002-04-30: Updated OCamlMakefile: it does not ask for confirmation during installation anymore! 2001-06-30: Removed "Printexc.catch" from stupid_ga-example: is going to be deprecated in upcoming OCaml-release. 2001-06-24: Added special module for resizable integer arrays (again), because it is faster on many operations. 2001-01-30: Made Makefile more general (allows simpler addition of further examples). 2001-01-26: Made use of the new OCaml-keyword "include" for module inclusion. This makes the file "lib/res.ml" significantly shorter. This change requires an OCaml-version higher than 3.00. 2001-01-24: Updated OCamlMakefile 2000-06-24: Updated OCamlMakefile 2000-06-13: Updated OCamlMakefile 2000-06-11: Updated OCamlMakefile 2000-06-08: Added installation routine + updated OCamlMakefile again: This upgrade makes installation much easier! Read the updated INSTALL-file! 2000-06-07: Upgraded to new OCamlMakefile. 2000-04-28: Fixed *critical* bug: Filling and blitting accidently truncated the array if the last index of the operation was smaller than the one of the target array. Resizable bit-vectors should be *much* more efficient now (blitting, resizing, etc. about 30 (60) times faster, depending on your architecture!): I took the new implementation of Jean-Christophe Filliatre's bitv-library, which uses some very clever algorithms for efficient blitting. In the near (?) future I'll also add his functions for common logical, efficient operations on bit-strings (unless somebody wants to volunteer... ;-) 2000-03-23: Removed special module for resizable integer arrays: Integer arrays are not unboxed and won't be in the (near?) future: this would cause generic polymorphic functions such as equality, hashing and output_value to produce wrong results. Therefore, use the parameterized version instead. It is equally fast. 2000-03-08: New function (in all implementations): find_index - takes a predicate, a resizable array and a start index and returns the index of the first element that satisfies the predicate - see interface documentation for details. Fixed documentation of interfaces: in some cases the wrong name for possibly raised exceptions was provided. 2000-01-10: Added functions for converting standard arrays to resizable ones and strings to buffers. Added "create" and "screate" to the interface of parameterized arrays. This makes it easier to use it in place of the standard array. Removed "make" and "smake" from resizable weak arrays - not useful there. Updated documentation on how to use the index operators with the resizable datastructures and how to easily replace the standard arrays/strings with the resizable ones in large sources. 1999-12-25: Added support for weak arrays + small example 1999-11-04: Added support for bit-vectors (peeked at Jean-Christophe Filliatre's bitv-library for this). Added new example: stupid_ga.ml (a brain-dead genetic algorithm using bit-vectors) We now have a TODO-list ;-) 1999-10-23: Added three new functions: remove_range - removes a range of elements within a resizable array pos - returns the index of the first logically equal element posq - returns the index of the first physically equal element 1999-10-13: First release. res-5.0.1/res.opam000066400000000000000000000012461336441772700137760ustar00rootroot00000000000000opam-version: "2.0" maintainer: "Markus Mottl " authors: [ "Markus Mottl " ] license: "LGPL-2.1+ with OCaml linking exception" homepage: "https://mmottl.github.io/res" doc: "https://mmottl.github.io/res/api" dev-repo: "git+https://github.com/mmottl/res.git" bug-reports: "https://github.com/mmottl/res/issues" build: [ ["dune" "subst"] {pinned} ["dune" "build" "-p" name "-j" jobs] ] depends: [ "ocaml" {>= "4.04"} "dune" {build & >= "1.4.0"} "base-bytes" ] synopsis: "RES - Library for resizable, contiguous datastructures" description: """ RES is a library containing resizable arrays, strings, and bitvectors.""" res-5.0.1/src/000077500000000000000000000000001336441772700131135ustar00rootroot00000000000000res-5.0.1/src/Makefile000066400000000000000000000001301336441772700145450ustar00rootroot00000000000000TARGETS = res.cma .PHONY: all clean all: @dune build $(TARGETS) clean: @dune clean res-5.0.1/src/dune000066400000000000000000000000341336441772700137660ustar00rootroot00000000000000(library (public_name res)) res-5.0.1/src/nopres_impl.ml000066400000000000000000000250441336441772700160010ustar00rootroot00000000000000(* RES - Automatically Resizing Contiguous Memory for OCaml Copyright (C) 1999- Markus Mottl email: markus.mottl@gmail.com WWW: http://www.ocaml.info This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *) module type Implementation = sig type el type t val name : string val length : t -> int val create : int -> t val make : int -> el -> t val unsafe_get : t -> int -> el val unsafe_set : t -> int -> el -> unit val unsafe_blit : t -> int -> t -> int -> int -> unit end module Make (S : Strat.T) (Impl : Implementation) = struct module Strategy = S type strategy = Strategy.t type el = Impl.el type t = { mutable ar : Impl.t; mutable vlix : int; mutable strategy : strategy } let name = Impl.name let invalid_arg str = invalid_arg (name ^ "." ^ str) let failwith str = failwith (name ^ "." ^ str) let length ra = ra.vlix + 1 let lix ra = ra.vlix let real_length ra = Impl.length ra.ar let real_lix ra = real_length ra - 1 let unsafe_get ra ix = Impl.unsafe_get ra.ar ix let unsafe_set ra ix el = Impl.unsafe_set ra.ar ix el let get ra n = if n > ra.vlix || n < 0 then invalid_arg "get" else unsafe_get ra n let set ra n el = if n > ra.vlix || n < 0 then invalid_arg "set" else unsafe_set ra n el let creator = Impl.create let empty_ar = Impl.create 0 let screate strategy n = let res = { ar = empty_ar; vlix = n - 1; strategy = strategy } in res.ar <- creator (Strategy.grow strategy n); res let smake strategy n x = let res = { ar = empty_ar; vlix = n - 1; strategy = strategy } in res.ar <- Impl.make (Strategy.grow strategy n) x; res let create_fresh n = screate Strategy.default n let create_from ra = { ar = creator (length ra); vlix = ra.vlix; strategy = ra.strategy } let sempty strategy = let res = { ar = empty_ar; vlix = -1; strategy = strategy } in res.ar <- creator (Strategy.grow strategy 0); res let empty () = sempty Strategy.default let create = screate Strategy.default let make = smake Strategy.default let sinit strategy n f = let res = smake strategy n (f 0) in let ar = res.ar in for i = 1 to n - 1 do Impl.unsafe_set ar i (f i) done; res let init n f = sinit Strategy.default n f let get_strategy ra = ra.strategy let resizer some_lix ({ ar = ar} as ra) len = let new_ar = creator len in for i = 0 to some_lix do Impl.unsafe_set new_ar i (Impl.unsafe_get ar i) done; ra.ar <- new_ar let enforce_strategy ra = let real_len = real_length ra in let new_len = length ra in let new_real_len = Strategy.shrink ra.strategy ~real_len ~new_len in if new_real_len <> -1 then resizer ra.vlix ra new_real_len let set_strategy ra strategy = ra.strategy <- strategy; enforce_strategy ra let put_strategy ra strategy = ra.strategy <- strategy let unsafe_blit_on_other ra1 ofs1 ra2 = Impl.unsafe_blit ra1.ar ofs1 ra2.ar let copy ra = let len = length ra in let ar = Impl.create len in Impl.unsafe_blit ra.ar 0 ar 0 len; { ra with ar = ar } let append ra1 ra2 = match ra1.vlix, ra2.vlix with | -1, -1 -> empty () | _, -1 -> copy ra1 | -1, _ -> copy ra2 | _ -> let len1 = length ra1 in let len2 = length ra2 in let res = create_fresh (len1 + len2) in unsafe_blit_on_other ra1 0 res 0 len1; unsafe_blit_on_other ra2 0 res len1 len2; res let rec concat_aux res offset = function | [] -> res | h::t -> if h.vlix < 0 then concat_aux res offset t else let len = length h in unsafe_blit_on_other h 0 res offset len; concat_aux res (offset + len) t let concat l = let len = List.fold_left (fun a el -> a + length el) 0 l in if len = 0 then empty () else concat_aux (create_fresh len) 0 l let unsafe_sub ra ofs len = let res = create_fresh len in unsafe_blit_on_other ra ofs res 0 len; res let sub ra ofs len = if ofs < 0 || len < 0 || ofs + len > length ra then invalid_arg "sub" else unsafe_sub ra ofs len let guarantee_ix ra ix = if real_lix ra < ix then resizer ra.vlix ra (Strategy.grow ra.strategy (ix + 1)) let maybe_grow_ix ra new_lix = guarantee_ix ra new_lix; ra.vlix <- new_lix let add_one ra x = let n = length ra in maybe_grow_ix ra n; unsafe_set ra n x let unsafe_remove_one ra = ra.vlix <- ra.vlix - 1; enforce_strategy ra let remove_one ra = if ra.vlix < 0 then failwith "remove_one" else unsafe_remove_one ra let unsafe_remove_n ra n = ra.vlix <- ra.vlix - n; enforce_strategy ra let remove_n ra n = if n > length ra || n < 0 then invalid_arg "remove_n" else unsafe_remove_n ra n let unsafe_remove_range ra ofs len = let ofs_len = ofs + len in unsafe_blit_on_other ra ofs_len ra ofs (length ra - ofs_len); unsafe_remove_n ra len let remove_range ra ofs len = if ofs < 0 || len < 0 || ofs + len > length ra then invalid_arg "remove_range" else unsafe_remove_range ra ofs len let clear ra = ra.vlix <- -1; enforce_strategy ra let unsafe_swap { ar = ar } n m = let tmp = Impl.unsafe_get ar n in Impl.unsafe_set ar n (Impl.unsafe_get ar m); Impl.unsafe_set ar m tmp let swap ra n m = if n > ra.vlix || m > ra.vlix || n < 0 || m < 0 then invalid_arg "swap" else unsafe_swap ra n m let unsafe_swap_in_last ({ ar = ar } as ra) n = Impl.unsafe_set ar n (Impl.unsafe_get ar ra.vlix); unsafe_remove_one ra let swap_in_last ra n = if n > ra.vlix || n < 0 then invalid_arg "swap_in_last" else unsafe_swap_in_last ra n let unsafe_fill ({ ar = ar } as ra) ofs len x = let last = ofs + len - 1 in maybe_grow_ix ra (max last ra.vlix); for i = ofs to last do Impl.unsafe_set ar i x done let fill ra ofs len x = if ofs < 0 || len < 0 || ofs > length ra then invalid_arg "fill" else unsafe_fill ra ofs len x let unsafe_blit ra1 ofs1 ra2 ofs2 len = guarantee_ix ra2 (ofs2 + len - 1); unsafe_blit_on_other ra1 ofs1 ra2 ofs2 len let blit ra1 ofs1 ra2 ofs2 len = if len < 0 || ofs1 < 0 || ofs2 < 0 || ofs1 + len > length ra1 || ofs2 > length ra2 then invalid_arg "blit" else unsafe_blit ra1 ofs1 ra2 ofs2 len let rec to_list_aux ar i accu = if i < 0 then accu else to_list_aux ar (i - 1) (Impl.unsafe_get ar i :: accu) let to_list ra = to_list_aux ra.ar ra.vlix [] let rec of_list_aux ar i = function | [] -> () | h::t -> Impl.unsafe_set ar i h; of_list_aux ar (i + 1) t let of_list l = let ra = create_fresh (List.length l) in of_list_aux ra.ar 0 l; ra let sof_list strategy l = let ra = screate strategy (List.length l) in of_list_aux ra.ar 0 l; ra let to_array ({ ar = ar } as ra) = Array.init (length ra) (fun i -> Impl.unsafe_get ar i) let sof_array strategy ar = sinit strategy (Array.length ar) (fun i -> Array.unsafe_get ar i) let of_array ar = sof_array Strategy.default ar let iter f ({ ar = ar } as ra) = for i = 0 to ra.vlix do f (Impl.unsafe_get ar i) done let map f ({ ar = ar } as ra) = let res = create_from ra in let res_ar = res.ar in for i = 0 to res.vlix do Impl.unsafe_set res_ar i (f (Impl.unsafe_get ar i)) done; res let iteri f ({ ar = ar } as ra) = for i = 0 to ra.vlix do f i (Impl.unsafe_get ar i) done let mapi f ({ ar = ar } as ra) = let { ar = res_ar } as res = create_from ra in for i = 0 to res.vlix do Impl.unsafe_set res_ar i (f i (Impl.unsafe_get ar i)) done; res let fold_left f accu ({ ar = ar } as ra) = let res = ref accu in for i = 0 to ra.vlix do res := f !res (Impl.unsafe_get ar i) done; !res let fold_right f ({ ar = ar } as ra) accu = let res = ref accu in for i = ra.vlix downto 0 do res := f (Impl.unsafe_get ar i) !res done; !res let rec for_all_aux i p ra = i > ra.vlix || p (unsafe_get ra i) && for_all_aux (i + 1) p ra let for_all p ra = for_all_aux 0 p ra let rec exists_aux i p ra = i <= ra.vlix && (p (unsafe_get ra i) || exists_aux (i + 1) p ra) let exists p ra = exists_aux 0 p ra let rec mem_aux i x ra = i <= ra.vlix && (unsafe_get ra i = x || mem_aux (i + 1) x ra) let mem x ra = mem_aux 0 x ra let rec memq_aux i x ra = i <= ra.vlix && (unsafe_get ra i == x || memq_aux (i + 1) x ra) let memq x ra = memq_aux 0 x ra let rec pos_aux i x ra = if i > ra.vlix then None else if unsafe_get ra i = x then Some i else pos_aux (i + 1) x ra let pos x ra = pos_aux 0 x ra let rec posq_aux i x ra = if i > ra.vlix then None else if unsafe_get ra i == x then Some i else posq_aux (i + 1) x ra let posq x ra = posq_aux 0 x ra let rec find_aux i p ra = if i > ra.vlix then raise Not_found else let el = unsafe_get ra i in if p el then el else find_aux (i + 1) p ra let find p ra = find_aux 0 p ra let rec find_index_aux p ra i = if i > ra.vlix then raise Not_found else if p (unsafe_get ra i) then i else find_index_aux p ra (i + 1) let find_index p ra i = if i < 0 then invalid_arg "find_index" else find_index_aux p ra i let filter p ({ ar = ar } as ra) = let res = sempty ra.strategy in for i = 0 to ra.vlix do let el = Impl.unsafe_get ar i in if p el then add_one res el done; res let find_all = filter let filter_in_place p ({ ar = ar } as ra) = let dest = ref 0 in let pos = ref 0 in while !pos <= ra.vlix do let el = Impl.unsafe_get ar !pos in if p el then begin Impl.unsafe_set ar !dest el; incr dest end; incr pos done; unsafe_remove_n ra (!pos - !dest) let partition p ra = let res1, res2 as res = sempty ra.strategy, sempty ra.strategy in for i = 0 to ra.vlix do let el = unsafe_get ra i in if p el then add_one res1 el else add_one res2 el done; res end res-5.0.1/src/nopres_intf.ml000066400000000000000000000337771336441772700160140ustar00rootroot00000000000000(* RES - Automatically Resizing Contiguous Memory for OCaml Copyright (C) 1999-2002 Markus Mottl email: markus.mottl@gmail.com WWW: http://www.ocaml.info This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *) (** Interfaces to unparameterized resizable arrays and buffers *) (** Interface to unparameterized resizable arrays *) module type T = sig (** {6 Signatures and types} *) (** Module implementing the reallocation strategy *) module Strategy : Strat.T (** Type of reallocation strategy *) type strategy = Strategy.t (** Type of resizable arrays *) type t (** Type of the elements in the resizable array *) type el (** {6 Index and length information} *) val length : t -> int (** [length ra] @return (virtual) length of resizable array [ra] excluding the reserved space. *) val lix : t -> int (** [lix ra] @return (virtual) last index of resizable array [ra] excluding the reserved space. *) val real_length : t -> int (** [real_length ra] @return (real) length of resizable array [ra] including the reserved space. *) val real_lix : t -> int (** [real_lix ra] @return (real) last index of resizable array [ra] including the reserved space. *) (** {6 Getting and setting} *) val get : t -> int -> el (** [get ra n] @return the [n]th element of [ra]. @raise Invalid_argument if index out of bounds. *) val set : t -> int -> el -> unit (** [set ra n] sets the [n]th element of [ra]. @raise Invalid_argument if index out of bounds. *) (** {6 Creation of resizable arrays} *) val sempty : strategy -> t (** [sempty s] @return an empty resizable array using strategy [s]. *) val empty : unit -> t (** [empty ()] same as [sempty] but uses default strategy. *) val screate : strategy -> int -> t (** [screate s n] @return a resizable array with strategy [s] containing [n] arbitrary elements. {e Attention: the contents is {b not} specified!} *) val create : int -> t (** [create n] same as [screate] but uses default strategy. *) val smake : strategy -> int -> el -> t (** [smake s n el] @return a resizable array of length [n] containing element [el] only using strategy [s]. *) val make : int -> el -> t (** [make n el] same as [smake] but uses default strategy. *) val sinit : strategy -> int -> (int -> el) -> t (** [sinit s n f] @return an array of length [n] containing elements that were created by applying function [f] to the index, using strategy [s]. *) val init : int -> (int -> el) -> t (** [init n f] sames as [sinit] but uses default strategy. *) (** {6 Strategy handling} *) val get_strategy : t -> strategy (** [get_strategy ra] @return the reallocation strategy used by resizable array [ra]. *) val set_strategy : t -> strategy -> unit (** [set_strategy ra s] sets the reallocation strategy of resizable array [ra] to [s], possibly causing an immediate reallocation. *) val put_strategy : t -> strategy -> unit (** [put_strategy ra s] sets the reallocation strategy of resizable array [ra] to [s]. Reallocation is only done at later changes in size. *) val enforce_strategy : t -> unit (** [enforce_strategy ra] forces a reallocation if necessary (e.g. after a [put_strategy]). *) (** {6 Copying, blitting and range extraction} *) val copy : t -> t (** [copy ra] @return a copy of resizable array [ra]. The two arrays share the same strategy! *) val sub : t -> int -> int -> t (** [sub ra ofs len] @return a resizable subarray of length [len] from resizable array [ra] starting at offset [ofs] using the default strategy. @raise Invalid_argument if parameters do not denote a correct subarray. *) val fill : t -> int -> int -> el -> unit (** [fill ra ofs len el] fills resizable array [ra] from offset [ofs] with [len] elements [el], possibly adding elements at the end. Raises [Invalid_argument] if offset [ofs] is larger than the length of the array. *) val blit : t -> int -> t -> int -> int -> unit (** [blit ra1 ofs1 ra2 ofs2 len] blits resizable array [ra1] onto [ra2] reading [len] elements from offset [ofs1] and writing them to [ofs2], possibly adding elements at the end of ra2. Raises [Invalid_argument] if [ofs1] and [len] do not designate a valid subarray of [ra1] or if [ofs2] is larger than the length of [ra2]. *) (** {6 Combining resizable arrays} *) val append : t -> t -> t (** [append ra1 ra2] @return a new resizable array using the default strategy and copying [ra1] and [ra2] in this order onto it. *) val concat : t list -> t (** [concat l] @return a new resizable array using the default strategy and copying all resizable arrays in [l] in their respective order onto it. *) (** {6 Adding and removing elements} *) val add_one : t -> el -> unit (** [add_one ra el] adds element [el] to resizable array [ra], possibly causing a reallocation. *) val remove_one : t -> unit (** [remove_one ra] removes the last element of resizable array [ra], possibly causing a reallocation. @raise Failure if the array is empty. *) val remove_n : t -> int -> unit (** [remove_n ra n] removes the last n elements of resizable array [ra], possibly causing a reallocation. @raise Invalid_arg if there are not enough elements or [n < 0]. *) val remove_range : t -> int -> int -> unit (** [remove_range ra ofs len] removes [len] elements from resizable array [ra] starting at [ofs] and possibly causing a reallocation. @raise Invalid_argument if range is invalid. *) val clear : t -> unit (** [clear ra] removes all elements from resizable array [ra], possibly causing a reallocation. *) (** {6 Swapping} *) val swap : t -> int -> int -> unit (** [swap ra n m] swaps elements at indices [n] and [m]. @raise Invalid_argument if any index is out of range. *) val swap_in_last : t -> int -> unit (** [swap_in_last ra n] swaps the last element with the one at position [n]. @raise Invalid_argument if index [n] is out of range. *) (** {6 Array conversions} *) val to_array : t -> el array (** [to_array ra] converts a resizable array to a standard one. *) val sof_array : strategy -> el array -> t (** [sof_array s ar] converts a standard array to a resizable one, using strategy [s]. *) val of_array : el array -> t (** [of_array ar] converts a standard array to a resizable one using the default strategy. *) (** {6 List conversions} *) val to_list : t -> el list (** [to_list ra] converts resizable array [ra] to a list. *) val sof_list : strategy -> el list -> t (** [sof_list s l] creates a resizable array using strategy [s] and the elements in list [l]. *) val of_list : el list -> t (** [of_list l] creates a resizable array using the default strategy and the elements in list [l]. *) (** {6 Iterators} *) val iter : (el -> unit) -> t -> unit (** [iter f ra] applies the unit-function [f] to each element in resizable array [ra]. *) val map : (el -> el) -> t -> t (** [map f ra] @return a resizable array using the strategy of [ra] and mapping each element in [ra] to its corresponding position in the new array using function [f]. *) val iteri : (int -> el -> unit) -> t -> unit (** [iteri f ra] applies the unit-function [f] to each index and element in resizable array [ra]. *) val mapi : (int -> el -> el) -> t -> t (** [mapi f ra] @return a resizable array using the strategy of [ra] and mapping each element in [ra] to its corresponding position in the new array using function [f] and the index position. *) val fold_left : ('a -> el -> 'a) -> 'a -> t -> 'a (** [fold_left f a ra] left-folds values in resizable array [ra] using function [f] and start accumulator [a]. *) val fold_right : (el -> 'a -> 'a) -> t -> 'a -> 'a (** [fold_right f a ra] right-folds values in resizable array [ra] using function [f] and start accumulator [a]. *) (** {6 Scanning of resizable arrays} *) val for_all : (el -> bool) -> t -> bool (** [for_all p ra] @return [true] if all elements in resizable array [ra] satisfy the predicate [p], [false] otherwise. *) val exists : (el -> bool) -> t -> bool (** [exists p ra] @return [true] if at least one element in resizable array [ra] satisfies the predicate [p], [false] otherwise. *) val mem : el -> t -> bool (** [mem el ra] @return [true] if element [el] is logically equal to any element in resizable array [ra], [false] otherwise. *) val memq : el -> t -> bool (** [memq el ra] @return [true] if element [el] is physically equal to any element in resizable array [ra], [false] otherwise. *) val pos : el -> t -> int option (** [pos el ra] @return [Some index] if [el] is logically equal to the element at [index] in [ra], [None] otherwise. [index] is the index of the first element that matches. *) val posq : el -> t -> int option (** [posq el ra] @return [Some index] if [el] is physically equal to the element at [index] in [ra], [None] otherwise. [index] is the index of the first element that matches. *) (** {6 Searching of resizable arrays} *) val find : (el -> bool) -> t -> el (** [find p ra] @return the first element in resizable array [ra] that satisfies predicate [p]. @raise Not_found if there is no such element. *) val find_index : (el -> bool) -> t -> int -> int (** [find_index p ra pos] @return the index of the first element that satisfies predicate [p] in resizable array [ra], starting search at index [pos]. @raise Not_found if there is no such element or if [pos] is larger than the highest index. @raise Invalid_argument if [pos] is negative. *) val filter : (el -> bool) -> t -> t (** [filter p ra] @return a new resizable array by filtering out all elements in [ra] that satisfy predicate [p] using the same strategy as [ra]. *) val find_all : (el -> bool) -> t -> t (** [find_all p ra] is the same as [filter] *) val filter_in_place : (el -> bool) -> t -> unit (** [filter_in_place p ra] as [filter], but filters in place. *) val partition : (el -> bool) -> t -> t * t (** [partition p ra] @return a pair of resizable arrays, the left part containing only elements of [ra] that satisfy predicate [p], the right one only those that do not satisfy it. Both returned arrays are created using the strategy of [ra]. *) (** {6 {b UNSAFE STUFF - USE WITH CAUTION!}} *) val unsafe_get : t -> int -> el val unsafe_set : t -> int -> el -> unit val unsafe_sub : t -> int -> int -> t val unsafe_fill : t -> int -> int -> el -> unit val unsafe_blit : t -> int -> t -> int -> int -> unit val unsafe_remove_one : t -> unit val unsafe_remove_n : t -> int -> unit val unsafe_swap : t -> int -> int -> unit val unsafe_swap_in_last : t -> int -> unit end (** Extended interface to buffers (resizable strings) *) module type Buffer = sig include T (** Includes all functions that exist in non-parameterized arrays. *) (** {6 String conversions} *) val sof_string : strategy -> string -> t (** [sof_string s ar] converts a string to a resizable buffer using strategy [s]. *) val of_string : string -> t (** [of_string ar] converts a string to a resizable buffer using the default strategy. *) (** {6 Functions found in the standard [Buffer]-module} *) (** Note that the function [create n] ignores the parameter [n] and uses the default strategy instead. You can supply a different strategy with [creates s n] as described above. *) val contents : t -> string (** [contents b] @return a copy of the current contents of the buffer [b]. *) val reset : t -> unit (** [reset b] just clears the buffer, possibly resizing it. *) val add_char : t -> char -> unit (** [add_char b c] appends the character [c] at the end of the buffer [b]. *) val add_string : t -> string -> unit (** [add_string b s] appends the string [s] at the end of the buffer [b]. *) val add_substring : t -> string -> int -> int -> unit (** [add_substring b s ofs len] takes [len] characters from offset [ofs] in string [s] and appends them at the end of the buffer [b]. *) val add_buffer : t -> t -> unit (** [add_buffer b1 b2] appends the current contents of buffer [b2] at the end of buffer [b1]. [b2] is not modified. *) val add_channel : t -> in_channel -> int -> unit (** [add_channel b ic n] reads exactly [n] character from the input channel [ic] and stores them at the end of buffer [b]. @raise End_of_file if the channel contains fewer than [n] characters. *) val output_buffer : out_channel -> t -> unit (** [output_buffer oc b] writes the current contents of buffer [b] on the output channel [oc]. *) (** {6 Additional buffer functions} *) val add_full_channel : t -> in_channel -> unit (* [add_full_channel b ic] reads the whole channel [ic] into buffer [b]. *) val add_full_channel_f : t -> in_channel -> int -> (int -> int) -> unit (* [add_full_channel_f b ic n f] reads the whole channel [ic] into buffer [b], starting with read-ahead [n] and using function [f] to calculate the next read-ahead if end-of-file was still not found. *) end res-5.0.1/src/pres_impl.ml000066400000000000000000000271301336441772700154420ustar00rootroot00000000000000(* RES - Automatically Resizing Contiguous Memory for OCaml Copyright (C) 1999- Markus Mottl email: markus.mottl@gmail.com WWW: http://www.ocaml.info This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *) module type Implementation = sig type 'a t val name : string val length : 'a t -> int val make : int -> 'a -> 'a t val unsafe_get : 'a t -> int -> 'a val unsafe_set : 'a t -> int -> 'a -> unit end module Make (S : Strat.T) (Impl : Implementation) = struct module Strategy = S type strategy = Strategy.t type 'a t = { mutable ar : 'a option Impl.t; mutable vlix : int; mutable strategy : strategy } let name = Impl.name let invalid_arg str = invalid_arg (name ^ "." ^ str) let failwith str = failwith (name ^ "." ^ str) let length ra = ra.vlix + 1 let lix ra = ra.vlix let real_length ra = Impl.length ra.ar let real_lix ra = real_length ra - 1 let unsafe_get_ar ar ix = match Impl.unsafe_get ar ix with | None -> failwith "unsafe_get_ar: element undefined - concurrent access?" | Some el -> el let unsafe_get ra ix = unsafe_get_ar ra.ar ix let unsafe_set_ar ar ix el = Impl.unsafe_set ar ix (Some el) let unsafe_set ra ix el = unsafe_set_ar ra.ar ix el let get ra n = if n > ra.vlix || n < 0 then invalid_arg "get" else unsafe_get ra n let set ra n el = if n > ra.vlix || n < 0 then invalid_arg "set" else unsafe_set ra n el let creator n = Impl.make n None let screate_fresh strategy n = let res = { ar = creator 0; vlix = n - 1; strategy = strategy } in res.ar <- creator (Strategy.grow strategy n); res let create_fresh n = screate_fresh Strategy.default n let create_from ra = { ar = creator (length ra); vlix = ra.vlix; strategy = ra.strategy } let sempty strategy = let res = { ar = creator 0; vlix = -1; strategy = strategy } in res.ar <- creator (Strategy.grow strategy 0); res let empty () = sempty Strategy.default let screate strategy n x = let res = screate_fresh strategy n in let res_ar = res.ar in let el = Some x in for i = 0 to n - 1 do Impl.unsafe_set res_ar i el done; res let smake = screate let create n = smake Strategy.default n let make = create let sinit strategy n f = let res = screate_fresh strategy n in let res_ar = res.ar in for i = 0 to n - 1 do unsafe_set_ar res_ar i (f i) done; res let init n f = sinit Strategy.default n f let to_array ({ ar = ar } as ra) = Array.init (length ra) (fun i -> unsafe_get_ar ar i) let sof_array strategy ar = sinit strategy (Array.length ar) (fun i -> Array.unsafe_get ar i) let of_array ar = sof_array Strategy.default ar let get_strategy ra = ra.strategy let resizer some_lix ra len = let ar = creator len in let old_ar = ra.ar in for i = 0 to some_lix do Impl.unsafe_set ar i (Impl.unsafe_get old_ar i) done; ra.ar <- ar let enforce_strategy ra = let real_len = real_length ra in let new_len = length ra in let new_real_len = Strategy.shrink ra.strategy ~real_len ~new_len in if new_real_len <> -1 then resizer ra.vlix ra new_real_len let set_strategy ra strategy = ra.strategy <- strategy; enforce_strategy ra let put_strategy ra strategy = ra.strategy <- strategy let make_matrix sx sy init = let res = create_fresh sx in let res_ar = res.ar in for i = 0 to res.vlix do unsafe_set_ar res_ar i (make sy init) done; res let copy ({ ar = ar } as ra) = let new_ar = Impl.make (real_length ra) (Impl.unsafe_get ar 0) in for i = 1 to real_lix ra do Impl.unsafe_set new_ar i (Impl.unsafe_get ar i) done; { ra with ar = new_ar } let unsafe_blit_on_other { ar = ar1 } ofs1 { ar = ar2 } ofs2 len = let ofs_diff = ofs2 - ofs1 in for i = ofs1 to ofs1 + len - 1 do Impl.unsafe_set ar2 (i + ofs_diff) (Impl.unsafe_get ar1 i) done let append ra1 ra2 = match ra1.vlix, ra2.vlix with | -1, -1 -> empty () | _, -1 -> copy ra1 | -1, _ -> copy ra2 | _ -> let len1 = length ra1 in let len2 = length ra2 in let res = create_fresh (len1 + len2) in unsafe_blit_on_other ra1 0 res 0 len1; unsafe_blit_on_other ra2 0 res len1 len2; res let rec concat_aux res offset = function | [] -> res | h::t -> if h.vlix < 0 then concat_aux res offset t else let len = length h in unsafe_blit_on_other h 0 res offset len; concat_aux res (offset + len) t let concat l = let len = List.fold_left (fun a el -> a + length el) 0 l in if len = 0 then empty () else concat_aux (create_fresh len) 0 l let unsafe_sub ra ofs len = let res = create_fresh len in unsafe_blit_on_other ra ofs res 0 len; res let sub ra ofs len = if ofs < 0 || len < 0 || ofs + len > length ra then invalid_arg "sub" else unsafe_sub ra ofs len let guarantee_ix ra ix = if real_lix ra < ix then resizer ra.vlix ra (Strategy.grow ra.strategy (ix + 1)) let maybe_grow_ix ra new_lix = guarantee_ix ra new_lix; ra.vlix <- new_lix let add_one ra x = let n = length ra in maybe_grow_ix ra n; unsafe_set ra n x let unsafe_remove_one ra = Impl.unsafe_set ra.ar ra.vlix None; ra.vlix <- ra.vlix - 1; enforce_strategy ra let remove_one ra = if ra.vlix < 0 then failwith "remove_one" else unsafe_remove_one ra let unsafe_remove_n ra n = let old_vlix = ra.vlix in let old_ar = ra.ar in ra.vlix <- old_vlix - n; enforce_strategy ra; if old_ar == ra.ar then for i = ra.vlix + 1 to old_vlix do Impl.unsafe_set old_ar i None done let remove_n ra n = if n > length ra || n < 0 then invalid_arg "remove_n" else unsafe_remove_n ra n let unsafe_remove_range ra ofs len = let ofs_len = ofs + len in unsafe_blit_on_other ra ofs_len ra ofs (length ra - ofs_len); unsafe_remove_n ra len let remove_range ra ofs len = if ofs < 0 || len < 0 || ofs + len > length ra then invalid_arg "remove_range" else unsafe_remove_range ra ofs len let clear ra = unsafe_remove_n ra (length ra) let unsafe_swap ra n m = let tmp = unsafe_get ra n in unsafe_set ra n (unsafe_get ra m); unsafe_set ra m tmp let swap ra n m = if n > ra.vlix || m > ra.vlix || n < 0 || m < 0 then invalid_arg "swap" else unsafe_swap ra n m let unsafe_swap_in_last ({ ar = ar } as ra) n = Impl.unsafe_set ar n (Impl.unsafe_get ar ra.vlix); unsafe_remove_one ra let swap_in_last ra n = if n > ra.vlix || n < 0 then invalid_arg "swap_in_last" else unsafe_swap_in_last ra n let unsafe_fill ra ofs len x = let last = ofs + len - 1 in maybe_grow_ix ra (max last ra.vlix); let el = Some x in let ar = ra.ar in for i = ofs to last do Impl.unsafe_set ar i el done let fill ra ofs len x = if ofs < 0 || len < 0 || ofs > length ra then invalid_arg "fill" else unsafe_fill ra ofs len x let unsafe_blit { ar = ar1 } ofs1 ({ ar = ar2 } as ra2) ofs2 len = guarantee_ix ra2 (ofs2 + len - 1); if ofs1 < ofs2 then for i = len - 1 downto 0 do Impl.unsafe_set ar2 (ofs2 + i) (Impl.unsafe_get ar1 (ofs1 + i)) done else for i = 0 to len - 1 do Impl.unsafe_set ar2 (ofs2 + i) (Impl.unsafe_get ar1 (ofs1 + i)) done let blit ra1 ofs1 ra2 ofs2 len = if len < 0 || ofs1 < 0 || ofs2 < 0 || ofs1 + len > length ra1 || ofs2 > length ra2 then invalid_arg "blit" else unsafe_blit ra1 ofs1 ra2 ofs2 len let rec to_list_aux ar i accu = if i < 0 then accu else to_list_aux ar (i - 1) (unsafe_get_ar ar i :: accu) let to_list ra = to_list_aux ra.ar ra.vlix [] let rec of_list_aux res_ar i = function | [] -> () | h::t -> unsafe_set_ar res_ar i h; of_list_aux res_ar (i + 1) t let of_list l = let res = create_fresh (List.length l) in of_list_aux res.ar 0 l; res let sof_list s l = let res = screate_fresh s (List.length l) in of_list_aux res.ar 0 l; res let iter f ({ ar = ar } as ra) = for i = 0 to ra.vlix do f (unsafe_get_ar ar i) done let map f ({ ar = ar } as ra) = let { ar = res_ar } as res = create_from ra in for i = 0 to res.vlix do unsafe_set_ar res_ar i (f (unsafe_get_ar ar i)) done; res let iteri f ({ ar = ar } as ra) = for i = 0 to ra.vlix do f i (unsafe_get_ar ar i) done let mapi f ({ ar = ar } as ra) = let { ar = res_ar } as res = create_from ra in for i = 0 to res.vlix do unsafe_set_ar res_ar i (f i (unsafe_get_ar ar i)) done; res let fold_left f accu ({ ar = ar } as ra) = let res = ref accu in for i = 0 to ra.vlix do res := f !res (unsafe_get_ar ar i) done; !res let fold_right f ({ ar = ar } as ra) accu = let res = ref accu in for i = ra.vlix downto 0 do res := f (unsafe_get_ar ar i) !res done; !res let rec for_all_aux i p ra = i > ra.vlix || p (unsafe_get ra i) && for_all_aux (i + 1) p ra let for_all p ra = for_all_aux 0 p ra let rec exists_aux i p ra = i <= ra.vlix && (p (unsafe_get ra i) || exists_aux (i + 1) p ra) let exists p ra = exists_aux 0 p ra let rec mem_aux i x ra = i <= ra.vlix && (unsafe_get ra i = x || mem_aux (i + 1) x ra) let mem x ra = mem_aux 0 x ra let rec memq_aux i x ra = i <= ra.vlix && (unsafe_get ra i == x || memq_aux (i + 1) x ra) let memq x ra = memq_aux 0 x ra let rec pos_aux i x ra = if i > ra.vlix then None else if unsafe_get ra i = x then Some i else pos_aux (i + 1) x ra let pos x ra = pos_aux 0 x ra let rec posq_aux i x ra = if i > ra.vlix then None else if unsafe_get ra i == x then Some i else posq_aux (i + 1) x ra let posq x ra = posq_aux 0 x ra let rec find_aux i p ra = if i > ra.vlix then raise Not_found else let el = unsafe_get ra i in if p el then el else find_aux (i + 1) p ra let find p ra = find_aux 0 p ra let rec find_index_aux p ra i = if i > ra.vlix then raise Not_found else if p (unsafe_get ra i) then i else find_index_aux p ra (i + 1) let find_index p ra i = if i < 0 then invalid_arg "find_index" else find_index_aux p ra i let filter p ({ ar = ar } as ra) = let res = sempty ra.strategy in for i = 0 to ra.vlix do let el = unsafe_get_ar ar i in if p el then add_one res el done; res let find_all = filter let filter_in_place p ({ ar = ar } as ra) = let dest = ref 0 in let pos = ref 0 in while !pos <= ra.vlix do let el = unsafe_get_ar ar !pos in if p el then begin unsafe_set_ar ar !dest el; incr dest end; incr pos done; unsafe_remove_n ra (!pos - !dest) let partition p ({ ar = ar } as ra) = let res1, res2 as res = sempty ra.strategy, sempty ra.strategy in for i = 0 to ra.vlix do let el = unsafe_get_ar ar i in if p el then add_one res1 el else add_one res2 el done; res end res-5.0.1/src/pres_intf.ml000066400000000000000000000275641336441772700154540ustar00rootroot00000000000000(* RES - Automatically Resizing Contiguous Memory for OCaml Copyright (C) 1999-2002 Markus Mottl email: markus.mottl@gmail.com WWW: http://www.ocaml.info This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *) (** Interface to parameterized resizable arrays *) module type T = sig (** {6 Signatures and types} *) (** Module implementing the reallocation strategy *) module Strategy : Strat.T (** Type of reallocation strategy *) type strategy = Strategy.t (** Type of parameterized resizable arrays *) type 'a t (** {6 Index and length information} *) val length : 'a t -> int (** [length ra] @return (virtual) length of resizable array [ra] excluding the reserved space. *) val lix : 'a t -> int (** [lix ra] @return (virtual) last index of resizable array [ra] excluding the reserved space. *) val real_length : 'a t -> int (** [real_length ra] @return (real) length of resizable array [ra] including the reserved space. *) val real_lix : 'a t -> int (** [real_lix ra] @return (real) last index of resizable array [ra] including the reserved space. *) (** {6 Getting and setting} *) val get : 'a t -> int -> 'a (** [get ra n] @return the [n]th element of [ra]. @raise Invalid_argument if index out of bounds. *) val set : 'a t -> int -> 'a -> unit (** [set ra n] sets the [n]th element of [ra]. @raise Invalid_argument if index out of bounds. *) (** {6 Creation of resizable arrays} *) val sempty : strategy -> 'a t (** [sempty s] @return an empty resizable array using strategy [s]. *) val empty : unit -> 'a t (** [empty ()] same as [sempty] but uses default strategy. *) val screate : strategy -> int -> 'a -> 'a t (** [screate s n el] @return a resizable array of length [n] containing element [el] only using strategy [s]. *) val create : int -> 'a -> 'a t (** [create n el] same as [screate] but uses default strategy. *) val smake : strategy -> int -> 'a -> 'a t (** [smake s n el] same as [screate]. *) val make : int -> 'a -> 'a t (** [make n el] same as [create]. *) val sinit : strategy -> int -> (int -> 'a) -> 'a t (** [sinit s n f] @return an array of length [n] containing elements that were created by applying function [f] to the index, using strategy [s]. *) val init : int -> (int -> 'a) -> 'a t (** [init n f] sames as [sinit] but uses default strategy. *) (** {6 Strategy handling} *) val get_strategy : 'a t -> strategy (** [get_strategy ra] @return the reallocation strategy used by resizable array [ra]. *) val set_strategy : 'a t -> strategy -> unit (** [set_strategy ra s] sets the reallocation strategy of resizable array [ra] to [s], possibly causing an immediate reallocation. *) val put_strategy : 'a t -> strategy -> unit (** [put_strategy ra s] sets the reallocation strategy of resizable array [ra] to [s]. Reallocation is only done at later changes in size. *) val enforce_strategy : 'a t -> unit (** [enforce_strategy ra] forces a reallocation if necessary (e.g. after a [put_strategy]). *) (** {6 Matrix functions} *) val make_matrix : int -> int -> 'a -> 'a t t (** [make_matrix sx sy el] creates a (resizable) matrix of dimensions [sx] and [sy] containing element [el] only. Both dimensions are controlled by the default strategy. *) (** {6 Copying, blitting and range extraction} *) val copy : 'a t -> 'a t (** [copy ra] @return a copy of resizable array [ra]. The two arrays share the same strategy! *) val sub : 'a t -> int -> int -> 'a t (** [sub ra ofs len] @return a resizable subarray of length [len] from resizable array [ra] starting at offset [ofs] using the default strategy. @raise Invalid_argument if parameters do not denote a correct subarray. *) val fill : 'a t -> int -> int -> 'a -> unit (** [fill ra ofs len el] fills resizable array [ra] from offset [ofs] with [len] elements [el], possibly adding elements at the end. Raises [Invalid_argument] if offset [ofs] is larger than the length of the array. *) val blit : 'a t -> int -> 'a t -> int -> int -> unit (** [blit ra1 ofs1 ra2 ofs2 len] blits resizable array [ra1] onto [ra2] reading [len] elements from offset [ofs1] and writing them to [ofs2], possibly adding elements at the end of ra2. Raises [Invalid_argument] if [ofs1] and [len] do not designate a valid subarray of [ra1] or if [ofs2] is larger than the length of [ra2]. *) (** {6 Combining resizable arrays} *) val append : 'a t -> 'a t -> 'a t (** [append ra1 ra2] @return a new resizable array using the default strategy and copying [ra1] and [ra2] in this order onto it. *) val concat : 'a t list -> 'a t (** [concat l] @return a new resizable array using the default strategy and copying all resizable arrays in [l] in their respective order onto it. *) (** {6 Adding and removing elements} *) val add_one : 'a t -> 'a -> unit (** [add_one ra el] adds element [el] to resizable array [ra], possibly causing a reallocation. *) val remove_one : 'a t -> unit (** [remove_one ra] removes the last element of resizable array [ra], possibly causing a reallocation. @raise Failure if the array is empty. *) val remove_n : 'a t -> int -> unit (** [remove_n ra n] removes the last n elements of resizable array [ra], possibly causing a reallocation. @raise Invalid_arg if there are not enough elements or [n < 0]. *) val remove_range : 'a t -> int -> int -> unit (** [remove_range ra ofs len] removes [len] elements from resizable array [ra] starting at [ofs] and possibly causing a reallocation. @raise Invalid_argument if range is invalid. *) val clear : 'a t -> unit (** [clear ra] removes all elements from resizable array [ra], possibly causing a reallocation. *) (** {6 Swapping} *) val swap : 'a t -> int -> int -> unit (** [swap ra n m] swaps elements at indices [n] and [m]. @raise Invalid_argument if any index is out of range. *) val swap_in_last : 'a t -> int -> unit (** [swap_in_last ra n] swaps the last element with the one at position [n]. @raise Invalid_argument if index [n] is out of range. *) (** {6 Array conversions} *) val to_array : 'a t -> 'a array (** [to_array ra] converts a resizable array to a standard one. *) val sof_array : strategy -> 'a array -> 'a t (** [sof_array s ar] converts a standard array to a resizable one, using strategy [s]. *) val of_array : 'a array -> 'a t (** [of_array ar] converts a standard array to a resizable one using the default strategy. *) (** {6 List conversions} *) val to_list : 'a t -> 'a list (** [to_list ra] converts resizable array [ra] to a list. *) val sof_list : strategy -> 'a list -> 'a t (** [sof_list s l] creates a resizable array using strategy [s] and the elements in list [l]. *) val of_list : 'a list -> 'a t (** [of_list l] creates a resizable array using the default strategy and the elements in list [l]. *) (** {6 Iterators} *) val iter : ('a -> unit) -> 'a t -> unit (** [iter f ra] applies the unit-function [f] to each element in resizable array [ra]. *) val map : ('a -> 'b) -> 'a t -> 'b t (** [map f ra] @return a resizable array using the strategy of [ra] and mapping each element in [ra] to its corresponding position in the new array using function [f]. *) val iteri : (int -> 'a -> unit) -> 'a t -> unit (** [iteri f ra] applies the unit-function [f] to each index and element in resizable array [ra]. *) val mapi : (int -> 'a -> 'b) -> 'a t -> 'b t (** [mapi f ra] @return a resizable array using the strategy of [ra] and mapping each element in [ra] to its corresponding position in the new array using function [f] and the index position. *) val fold_left : ('b -> 'a -> 'b) -> 'b -> 'a t -> 'b (** [fold_left f a ra] left-folds values in resizable array [ra] using function [f] and start accumulator [a]. *) val fold_right : ('a -> 'b -> 'b) -> 'a t -> 'b -> 'b (** [fold_right f a ra] right-folds values in resizable array [ra] using function [f] and start accumulator [a]. *) (** {6 Scanning of resizable arrays} *) val for_all : ('a -> bool) -> 'a t -> bool (** [for_all p ra] @return [true] if all elements in resizable array [ra] satisfy the predicate [p], [false] otherwise. *) val exists : ('a -> bool) -> 'a t -> bool (** [exists p ra] @return [true] if at least one element in resizable array [ra] satisfies the predicate [p], [false] otherwise. *) val mem : 'a -> 'a t -> bool (** [mem el ra] @return [true] if element [el] is logically equal to any element in resizable array [ra], [false] otherwise. *) val memq : 'a -> 'a t -> bool (** [memq el ra] @return [true] if element [el] is physically equal to any element in resizable array [ra], [false] otherwise. *) val pos : 'a -> 'a t -> int option (** [pos el ra] @return [Some index] if [el] is logically equal to the element at [index] in [ra], [None] otherwise. [index] is the index of the first element that matches. *) val posq : 'a -> 'a t -> int option (** [posq el ra] @return [Some index] if [el] is physically equal to the element at [index] in [ra], [None] otherwise. [index] is the index of the first element that matches. *) (** {6 Searching of resizable arrays} *) val find : ('a -> bool) -> 'a t -> 'a (** [find p ra] @return the first element in resizable array [ra] that satisfies predicate [p]. @raise Not_found if there is no such element. *) val find_index : ('a -> bool) -> 'a t -> int -> int (** [find_index p ra pos] @return the index of the first element that satisfies predicate [p] in resizable array [ra], starting search at index [pos]. @raise Not_found if there is no such element or if [pos] is larger than the highest index. @raise Invalid_argument if [pos] is negative. *) val filter : ('a -> bool) -> 'a t -> 'a t (** [filter p ra] @return a new resizable array by filtering out all elements in [ra] that satisfy predicate [p] using the same strategy as [ra]. *) val find_all : ('a -> bool) -> 'a t -> 'a t (** [find_all p ra] is the same as [filter] *) val filter_in_place : ('a -> bool) -> 'a t -> unit (** [filter_in_place p ra] as [filter], but filters in place. *) val partition : ('a -> bool) -> 'a t -> 'a t * 'a t (** [partition p ra] @return a pair of resizable arrays, the left part containing only elements of [ra] that satisfy predicate [p], the right one only those that do not satisfy it. Both returned arrays are created using the strategy of [ra]. *) (** {6 {b UNSAFE STUFF - USE WITH CAUTION!}} *) val unsafe_get : 'a t -> int -> 'a val unsafe_set : 'a t -> int -> 'a -> unit val unsafe_sub : 'a t -> int -> int -> 'a t val unsafe_fill : 'a t -> int -> int -> 'a -> unit val unsafe_blit : 'a t -> int -> 'a t -> int -> int -> unit val unsafe_remove_one : 'a t -> unit val unsafe_remove_n : 'a t -> int -> unit val unsafe_swap : 'a t -> int -> int -> unit val unsafe_swap_in_last : 'a t -> int -> unit end res-5.0.1/src/res.ml000066400000000000000000000204321336441772700142370ustar00rootroot00000000000000(* RES - Automatically Resizing Contiguous Memory for OCaml Copyright (C) 1999- Markus Mottl email: markus.mottl@gmail.com WWW: http://www.ocaml.info This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *) module DefStrat = struct type t = float * float * int let default = 1.5, 0.5, 16 let grow (waste, _, min_size) new_len = max (truncate (float new_len *. waste)) min_size let shrink (waste, shrink_trig, min_size) ~real_len ~new_len = if real_len > min_size && truncate (float real_len *. shrink_trig) > new_len then max (truncate (float new_len *. waste)) min_size else -1 end module BitDefStrat = struct include DefStrat let default = 1.5, 0.5, 1024 end module Array_impl = struct type 'a t = 'a array let name = "Res.Array" let length = Array.length let make = Array.make let unsafe_get = Array.get let unsafe_set = Array.set end module Unsafe_float_impl = struct type el = float type t = el array let length = Array.length let create = Array.create_float let make = Array.make let unsafe_get = Array.unsafe_get let unsafe_set = Array.unsafe_set let unsafe_blit (ar1 : t) ofs1 ar2 ofs2 len = if ofs1 < ofs2 then for i = len - 1 downto 0 do unsafe_set ar2 (ofs2 + i) (unsafe_get ar1 (ofs1 + i)) done else for i = 0 to len - 1 do unsafe_set ar2 (ofs2 + i) (unsafe_get ar1 (ofs1 + i)) done end module Float_impl = struct include Unsafe_float_impl let name = "Res.Floats" let unsafe_get = Array.get let unsafe_set = Array.set let unsafe_blit ar1 ofs1 ar2 ofs2 len = if len < 0 || ofs1 < 0 || ofs1 > Array.length ar1 - len || ofs2 < 0 || ofs2 > Array.length ar2 - len then invalid_arg "Res.Floats.blit" else unsafe_blit ar1 ofs1 ar2 ofs2 len end (* TODO: create safe version *) (* Code of the Bit-module due to Jean-Christophe Filliatre *) module Bit_impl = struct type el = bool type t = { length : int; bits : int array } let name = "Res.Bits" let length v = v.length let bpi = Sys.word_size - 2 let bit_j = Array.init bpi (fun j -> 1 lsl j) let bit_not_j = Array.init bpi (fun j -> max_int - bit_j.(j)) let low_mask = Array.make (bpi + 1) 0 let () = for i = 1 to bpi do low_mask.(i) <- low_mask.(i-1) lor bit_j.(i - 1) done let keep_lowest_bits a j = a land low_mask.(j) let high_mask = Array.init (bpi + 1) (fun j -> low_mask.(j) lsl (bpi-j)) let keep_highest_bits a j = a land high_mask.(j) let make n b = let initv = if b then max_int else 0 in let r = n mod bpi in if r = 0 then { length = n; bits = Array.make (n / bpi) initv } else begin let s = n / bpi in let b = Array.make (s + 1) initv in b.(s) <- b.(s) land low_mask.(r); { length = n; bits = b } end let create n = make n false let pos n = let i = n / bpi in let j = n mod bpi in if j < 0 then (i - 1, j + bpi) else (i,j) let unsafe_get v n = let (i,j) = pos n in ((Array.unsafe_get v.bits i) land (Array.unsafe_get bit_j j)) > 0 let unsafe_set v n b = let (i,j) = pos n in if b then Array.unsafe_set v.bits i ((Array.unsafe_get v.bits i) lor (Array.unsafe_get bit_j j)) else Array.unsafe_set v.bits i ((Array.unsafe_get v.bits i) land (Array.unsafe_get bit_not_j j)) let blit_bits a i m v n = let (i',j) = pos n in if j == 0 then Array.unsafe_set v i' ((keep_lowest_bits (a lsr i) m) lor (keep_highest_bits (Array.unsafe_get v i') (bpi - m))) else let d = m + j - bpi in if d > 0 then begin Array.unsafe_set v i' (((keep_lowest_bits (a lsr i) (bpi - j)) lsl j) lor (keep_lowest_bits (Array.unsafe_get v i') j)); Array.unsafe_set v (i' + 1) ((keep_lowest_bits (a lsr (i + bpi - j)) d) lor (keep_highest_bits (Array.unsafe_get v (i' + 1)) (bpi - d))) end else Array.unsafe_set v i' (((keep_lowest_bits (a lsr i) m) lsl j) lor ((Array.unsafe_get v i') land (low_mask.(j) lor high_mask.(-d)))) let blit_int a v n = let (i,j) = pos n in if j == 0 then Array.unsafe_set v i a else begin Array.unsafe_set v i ( (keep_lowest_bits (Array.unsafe_get v i) j) lor ((keep_lowest_bits a (bpi - j)) lsl j)); Array.unsafe_set v (i + 1) ((keep_highest_bits (Array.unsafe_get v (i + 1)) (bpi - j)) lor (a lsr (bpi - j))) end let unsafe_blit v1 ofs1 v2 ofs2 len = let (bi,bj) = pos ofs1 in let (ei,ej) = pos (ofs1 + len - 1) in if bi == ei then blit_bits (Array.unsafe_get v1.bits bi) bj len v2.bits ofs2 else begin blit_bits (Array.unsafe_get v1.bits bi) bj (bpi - bj) v2.bits ofs2; let n = ref (ofs2 + bpi - bj) in for i = bi + 1 to ei - 1 do blit_int (Array.unsafe_get v1.bits i) v2.bits !n; n := !n + bpi done; blit_bits (Array.unsafe_get v1.bits ei) 0 (ej + 1) v2.bits !n end end module Buffer_impl = struct type el = char type t = Bytes.t let length = Bytes.length let create = Bytes.create let make = Bytes.make let name = "Res.Buffer" let unsafe_get = Bytes.unsafe_get let unsafe_set = Bytes.unsafe_set let unsafe_blit = Bytes.unsafe_blit end module MakeArray (S : Strat.T) = Pres_impl.Make (S) (Array_impl) module MakeFloats (S : Strat.T) = Nopres_impl.Make (S) (Float_impl) module MakeBits (S : Strat.T) = Nopres_impl.Make (S) (Bit_impl) module MakeWeak (S : Strat.T) = Weak_impl.Make (S) module MakeBuffer (S : Strat.T) = struct module B = Nopres_impl.Make (S) (Buffer_impl) include B let create _ = empty () let contents buf = Bytes.sub_string buf.ar 0 (length buf) let reset = clear let add_char = add_one let add_string buf str = let old_buf_len = length buf in let len = String.length str in maybe_grow_ix buf (buf.vlix + len); Bytes.blit_string str 0 buf.ar old_buf_len len let add_substring buf str ofs len = if ofs < 0 || len < 0 || ofs + len > String.length str then invalid_arg "add_substring"; let old_buf_len = length buf in maybe_grow_ix buf (buf.vlix + len); Bytes.blit_string str ofs buf.ar old_buf_len len let add_buffer b1 b2 = let len = length b2 in let old_buf_len = length b1 in maybe_grow_ix b1 (b1.vlix + len); Bytes.blit b2.ar 0 b1.ar old_buf_len len let add_channel buf ch len = let old_buf_len = length buf in maybe_grow_ix buf (buf.vlix + len); try really_input ch buf.ar old_buf_len len with | End_of_file -> buf.vlix <- old_buf_len - 1; enforce_strategy buf let rec add_full_channel_f_aux buf ch len adjust = if len > 0 then begin let old_buf_len = length buf in maybe_grow_ix buf (buf.vlix + len); let r = input ch buf.ar old_buf_len len in if r > 0 then begin let diff = len - r in if diff > 0 then begin buf.vlix <- buf.vlix - diff; add_full_channel_f_aux buf ch len adjust end else add_full_channel_f_aux buf ch (adjust len) adjust end else buf.vlix <- buf.vlix - len end let add_full_channel_f buf ch len adjust = add_full_channel_f_aux buf ch len adjust; enforce_strategy buf let add_full_channel buf ch = add_full_channel_f buf ch 4096 (fun n -> n) let output_buffer ch buf = output ch buf.ar 0 (length buf) let sof_string strategy str = sinit strategy (String.length str) (fun i -> String.unsafe_get str i) let of_string = sof_string Strategy.default end module Array = MakeArray (DefStrat) module Floats = MakeFloats (DefStrat) module Bits = MakeBits (BitDefStrat) module Weak = MakeWeak (DefStrat) module Buffer = MakeBuffer (DefStrat) res-5.0.1/src/res.mli000066400000000000000000000066301336441772700144140ustar00rootroot00000000000000(* RES - Automatically Resizing Contiguous Memory for OCaml Copyright (C) 1999- Markus Mottl email: markus.mottl@gmail.com WWW: http://www.ocaml.info This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *) (** Global module for resizable datastructures and default implementations *) (** {6 Default strategies} *) (** Default strategy for resizable datastructures *) module DefStrat : (Strat.T with type t = float * float * int) (** [type t] is a triple [(waste, shrink_trig, min_size)], where [waste] (default: 1.5) indicates how much the array should grow in excess when reallocation is triggered, [shrink_trig] (default: 0.5) at which percentage of excess elements it should be shrunk and [min_size] (default: 16 elements) is the minimum size of the resizable array. *) module BitDefStrat : (Strat.T with type t = float * float * int) (** Same as [DefStrat], but the minimum size is 1024 elements (bits). *) (** {6 Default instantiation of standard resizable datastructures} *) (** Resizable parameterized array using the default reallocation strategy. *) module Array : (Pres_intf.T with module Strategy = DefStrat) (** Resizable float array using the default reallocation strategy. *) module Floats : (Nopres_intf.T with module Strategy = DefStrat and type el = float) (** Resizable bit vector using the default reallocation strategy. *) module Bits : (Nopres_intf.T with module Strategy = BitDefStrat and type el = bool) (** Resizable weak array using the default reallocation strategy. *) module Weak : (Weak_intf.T with module Strategy = DefStrat) (** Resizable buffer using the default reallocation strategy. *) module Buffer : (Nopres_intf.Buffer with module Strategy = DefStrat and type el = char) (** {6 Functors for creating standard resizable datastructures from strategies} *) (** Functor that creates resizable parameterized arrays from reallocation strategies. *) module MakeArray : functor (S : Strat.T) -> (Pres_intf.T with module Strategy = S) (** Functor that creates resizable float arrays from reallocation strategies. *) module MakeFloats : functor (S : Strat.T) -> (Nopres_intf.T with module Strategy = S and type el = float) (** Functor that creates resizable bit vectors from reallocation strategies. *) module MakeBits : functor (S : Strat.T) -> (Nopres_intf.T with module Strategy = S and type el = bool) (** Functor that creates resizable weak arrays from reallocation strategies. *) module MakeWeak : functor (S : Strat.T) -> (Weak_intf.T with module Strategy = S) (** Functor that creates resizable buffers (=string arrays) from reallocation strategies. *) module MakeBuffer : functor (S : Strat.T) -> (Nopres_intf.Buffer with module Strategy = S and type el = char) res-5.0.1/src/strat.ml000066400000000000000000000040221336441772700146000ustar00rootroot00000000000000(* RES - Automatically Resizing Contiguous Memory for OCaml Copyright (C) 1999- Markus Mottl email: markus.mottl@gmail.com WWW: http://www.ocaml.info This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *) (** Interface to strategies *) module type T = sig type t (** The abstract type of strategies. *) val default : t (** Default strategy of this strategy implementation. *) val grow : t -> int -> int (** [grow strat new_len] @return the new real length of some contiguous datastructure using strategy [strat] given new virtual length [new_len]. The user should then use this new real length to resize the datastructure. Be careful, the new (real) length {b must} be larger than the new virtual length, otherwise your program will crash! *) val shrink : t -> real_len : int -> new_len : int -> int (** [shrink strat ~real_len ~new_len] @return the new real length of a resizable datastructure given its current real length [real_len] and its required new virtual length [new_len] wrt. strategy [strat]. The user should then use this new real length to resize the datastructure. If [-1] is returned, it is not necessary to resize. Be careful, the new (real) length {b must} be larger than the new virtual length [new_len], otherwise your program may crash! *) end res-5.0.1/src/weak_impl.ml000066400000000000000000000237601336441772700154250ustar00rootroot00000000000000(* RES - Automatically Resizing Contiguous Memory for OCaml Copyright (C) 1999- Markus Mottl email: markus.mottl@gmail.com WWW: http://www.ocaml.info This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *) (* TODO: make safe and improve *) module Make (S : Strat.T) = struct module Strategy = S type strategy = Strategy.t type 'a t = { mutable ar : 'a Weak.t; mutable vlix : int; mutable strategy : strategy } let name = "Res.Weak" let invalid_arg str = invalid_arg (name ^ "." ^ str) let failwith str = failwith (name ^ "." ^ str) let length ra = ra.vlix + 1 let lix ra = ra.vlix let real_length ra = Weak.length ra.ar let real_lix ra = real_length ra - 1 let unsafe_get ra ix = Weak.get ra.ar ix let unsafe_set ra ix el = Weak.set ra.ar ix el let check ra ix = Weak.check ra.ar ix let get ra n = if n > ra.vlix || n < 0 then invalid_arg "get" else unsafe_get ra n let get_copy ra n = if n > ra.vlix || n < 0 then invalid_arg "get_copy" else Weak.get_copy ra.ar n let set ra n = if n > ra.vlix || n < 0 then invalid_arg "set" else unsafe_set ra n let creator = Weak.create let screate_fresh strategy n = let res = {ar = creator 0; vlix = n - 1; strategy = strategy} in res.ar <- creator (Strategy.grow strategy n); res let create_fresh n = screate_fresh Strategy.default n let create_from ra = {ar = creator (length ra); vlix = ra.vlix; strategy = ra.strategy} let sempty strategy = let res = {ar = creator 0; vlix = -1; strategy = strategy} in res.ar <- creator (Strategy.grow strategy 0); res let empty () = sempty Strategy.default let smake strategy n x = let res = screate_fresh strategy n in for i = 0 to n - 1 do unsafe_set res i x done; res let make n = smake Strategy.default n let create n = make n None let screate strategy n = smake strategy n None let sinit strategy n f = let res = screate_fresh strategy n in for i = 0 to n - 1 do unsafe_set res i (f i) done; res let init n f = sinit Strategy.default n f let get_strategy ra = ra.strategy let resizer some_lix ra len = let ar = creator len in for i = 0 to some_lix do Weak.set ar i (unsafe_get ra i) done; ra.ar <- ar let enforce_strategy ra = let real_len = real_length ra in let new_len = length ra in let new_real_len = Strategy.shrink ra.strategy ~real_len ~new_len in if new_real_len <> -1 then resizer ra.vlix ra new_real_len let set_strategy ra strategy = ra.strategy <- strategy; enforce_strategy ra let put_strategy ra strategy = ra.strategy <- strategy let copy ra = let ar = Weak.create (real_length ra) in for i = 0 to real_lix ra do Weak.set ar i (unsafe_get ra i) done; {ra with ar = ar} let unsafe_blit_on_other ra1 ofs1 ra2 ofs2 len = let ofs_diff = ofs2 - ofs1 in for i = ofs1 to ofs1 + len - 1 do unsafe_set ra2 (i + ofs_diff) (unsafe_get ra1 i) done let append ra1 ra2 = match ra1.vlix, ra2.vlix with | -1, -1 -> empty () | _, -1 -> copy ra1 | -1, _ -> copy ra2 | _ -> let len1 = length ra1 in let len2 = length ra2 in let res = create_fresh (len1 + len2) in unsafe_blit_on_other ra1 0 res 0 len1; unsafe_blit_on_other ra2 0 res len1 len2; res let rec concat_aux res offset = function | [] -> res | h::t -> if h.vlix < 0 then concat_aux res offset t else let len = length h in unsafe_blit_on_other h 0 res offset len; concat_aux res (offset + len) t let concat l = let len = List.fold_left (fun a el -> a + length el) 0 l in if len = 0 then empty () else concat_aux (create_fresh len) 0 l let unsafe_sub ra ofs len = let res = create_fresh len in unsafe_blit_on_other ra ofs res 0 len; res let sub ra ofs len = if ofs < 0 || len < 0 || ofs + len > length ra then invalid_arg "sub" else unsafe_sub ra ofs len let guarantee_ix ra ix = if real_lix ra < ix then resizer ra.vlix ra (Strategy.grow ra.strategy (ix + 1)) let maybe_grow_ix ra new_lix = guarantee_ix ra new_lix; ra.vlix <- new_lix let add_one ra x = let n = length ra in maybe_grow_ix ra n; unsafe_set ra n x let unsafe_remove_one ra = unsafe_set ra ra.vlix None; ra.vlix <- ra.vlix - 1; enforce_strategy ra let remove_one ra = if ra.vlix < 0 then failwith "remove_one" else unsafe_remove_one ra let unsafe_remove_n ra n = let old_vlix = ra.vlix in let old_ar = ra.ar in ra.vlix <- old_vlix - n; enforce_strategy ra; if old_ar == ra.ar then for i = ra.vlix + 1 to old_vlix do unsafe_set ra i None done let remove_n ra n = if n > length ra || n < 0 then invalid_arg "remove_n" else unsafe_remove_n ra n let unsafe_remove_range ra ofs len = unsafe_blit_on_other ra (ofs + len) ra ofs (length ra - len); unsafe_remove_n ra len let remove_range ra ofs len = if ofs < 0 || len < 0 || ofs + len > length ra then invalid_arg "remove_range" else unsafe_remove_range ra ofs len let clear ra = unsafe_remove_n ra (length ra) let unsafe_swap ra n m = let tmp = unsafe_get ra n in unsafe_set ra n (unsafe_get ra m); unsafe_set ra m tmp let swap ra n m = if n > ra.vlix || m > ra.vlix || n < 0 || m < 0 then invalid_arg "swap" else unsafe_swap ra n m let unsafe_swap_in_last ra n = unsafe_set ra n (unsafe_get ra ra.vlix); unsafe_remove_one ra let swap_in_last ra n = if n > ra.vlix || n < 0 then invalid_arg "swap_in_last" else unsafe_swap_in_last ra n let unsafe_fill ra ofs len x = let last = ofs + len - 1 in maybe_grow_ix ra (max last ra.vlix); for i = ofs to last do unsafe_set ra i x done let fill ra ofs len x = if ofs < 0 || len < 0 || ofs > length ra then invalid_arg "fill" else unsafe_fill ra ofs len x let unsafe_blit ra1 ofs1 ra2 ofs2 len = guarantee_ix ra2 (ofs2 + len - 1); if ofs1 < ofs2 then for i = len - 1 downto 0 do unsafe_set ra2 (ofs2 + i) (unsafe_get ra1 (ofs1 + i)) done else for i = 0 to len - 1 do unsafe_set ra2 (ofs2 + i) (unsafe_get ra1 (ofs1 + i)) done let blit ra1 ofs1 ra2 ofs2 len = if len < 0 || ofs1 < 0 || ofs2 < 0 || ofs1 + len > length ra1 || ofs2 > length ra2 then invalid_arg "blit" else unsafe_blit ra1 ofs1 ra2 ofs2 len let to_std ra = let wa = Weak.create (length ra) in for i = 0 to ra.vlix do Weak.set wa i (unsafe_get ra i) done; wa let sof_std strategy ar = sinit strategy (Weak.length ar) (Weak.get ar) let of_std ar = sof_std Strategy.default ar let rec to_list_aux ra i accu = if i < 0 then accu else to_list_aux ra (i - 1) (unsafe_get ra i :: accu) let to_list ra = to_list_aux ra ra.vlix [] let rec of_list_aux res i = function | [] -> res | h::t -> unsafe_set res i h; of_list_aux res (i + 1) t let of_list l = of_list_aux (create_fresh (List.length l)) 0 l let iter f ra = for i = 0 to ra.vlix do f (unsafe_get ra i) done let iteri f ra = for i = 0 to ra.vlix do f i (unsafe_get ra i) done let fold_left f accu ra = let res = ref accu in for i = 0 to ra.vlix do res := f !res (unsafe_get ra i) done; !res let fold_right f ra accu = let res = ref accu in for i = ra.vlix downto 0 do res := f (unsafe_get ra i) !res done; !res let rec for_all_aux i p ra = if i > ra.vlix then true else if p (unsafe_get ra i) then for_all_aux (i + 1) p ra else false let for_all p ra = for_all_aux 0 p ra let rec exists_aux i p ra = if i > ra.vlix then false else if p (unsafe_get ra i) then true else exists_aux (i + 1) p ra let exists p ra = exists_aux 0 p ra let rec mem_aux i x ra = if i > ra.vlix then false else if unsafe_get ra i = x then true else mem_aux (i + 1) x ra let mem x ra = mem_aux 0 x ra let rec memq_aux i x ra = if i > ra.vlix then false else if unsafe_get ra i == x then true else memq_aux (i + 1) x ra let memq x ra = memq_aux 0 x ra let rec pos_aux i x ra = if i > ra.vlix then None else if unsafe_get ra i = x then Some i else pos_aux (i + 1) x ra let pos x ra = pos_aux 0 x ra let rec posq_aux i x ra = if i > ra.vlix then None else if unsafe_get ra i == x then Some i else posq_aux (i + 1) x ra let posq x ra = posq_aux 0 x ra let rec find_aux i p ra = if i > ra.vlix then raise Not_found else let el = unsafe_get ra i in if p el then el else find_aux (i + 1) p ra let find p ra = find_aux 0 p ra let rec find_index_aux p ra i = if i > ra.vlix then raise Not_found else if p (unsafe_get ra i) then i else find_index_aux p ra (i + 1) let find_index p ra i = if i < 0 then invalid_arg "find_index" else find_index_aux p ra i let filter p ra = let res = sempty ra.strategy in for i = 0 to ra.vlix do let el = unsafe_get ra i in if p el then add_one res el done; res let find_all = filter let filter_in_place p ra = let dest = ref 0 in let pos = ref 0 in while !pos <= ra.vlix do let el = unsafe_get ra !pos in if p el then begin unsafe_set ra !dest el; incr dest end; incr pos done; unsafe_remove_n ra (!pos - !dest) let partition p ra = let res1, res2 as res = sempty ra.strategy, sempty ra.strategy in for i = 0 to ra.vlix do let el = unsafe_get ra i in if p el then add_one res1 el else add_one res2 el done; res end res-5.0.1/src/weak_intf.ml000066400000000000000000000265451336441772700154300ustar00rootroot00000000000000(* RES - Automatically Resizing Contiguous Memory for OCaml Copyright (C) 1999-2002 Markus Mottl email: markus.mottl@gmail.com WWW: http://www.ocaml.info This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *) (** Interface to weak resizable arrays *) module type T = sig (** {6 Signatures and types} *) (** Module implementing the reallocation strategy *) module Strategy : Strat.T (** Type of reallocation strategy *) type strategy = Strategy.t (** Type of parameterized resizable arrays *) type 'a t (** {6 Index and length information} *) val length : 'a t -> int (** [length ra] @return (virtual) length of resizable array [ra] excluding the reserved space. *) val lix : 'a t -> int (** [lix ra] @return (virtual) last index of resizable array [ra] excluding the reserved space. *) val real_length : 'a t -> int (** [real_length ra] @return (real) length of resizable array [ra] including the reserved space. *) val real_lix : 'a t -> int (** [real_lix ra] @return (real) last index of resizable array [ra] including the reserved space. *) (** {6 Getting, setting and checking} *) val get : 'a t -> int -> 'a option (** [get ra n] @return the [n]th element of [ra]. @raise Invalid_argument if index out of bounds. *) val get_copy : 'a t -> int -> 'a option (** [get_copy ra n] see documentation of module [Weak] in the standard distribution. *) val check : 'a t -> int -> bool (** [check ra n] @return [true] if the [n]th cell of [ra] is full, [false] if it is empty. Note that even if [check ar n] returns [true], a subsequent {!get}[ ar n] can return [None]. *) val set : 'a t -> int -> 'a option -> unit (** [set ra n] sets the [n]th element of [ra]. @raise Invalid_argument if index out of bounds. *) (** {6 Creation of resizable arrays} *) val sempty : strategy -> 'a t (** [sempty s] @return an empty resizable array using strategy [s]. *) val empty : unit -> 'a t (** [empty ()] same as [sempty] but uses default strategy. *) val screate : strategy -> int -> 'a t (** [screate s n el] @return a resizable array of length [n] using strategy [s]. *) val create : int -> 'a t (** [create n] same as [screate] but uses default strategy. *) val sinit : strategy -> int -> (int -> 'a option) -> 'a t (** [sinit s n f] @return an array of length [n] containing elements that were created by applying function [f] to the index, using strategy [s]. *) val init : int -> (int -> 'a option) -> 'a t (** [init n f] sames as [sinit] but uses default strategy. *) (** {6 Strategy handling} *) val get_strategy : 'a t -> strategy (** [get_strategy ra] @return the reallocation strategy used by resizable array [ra]. *) val set_strategy : 'a t -> strategy -> unit (** [set_strategy ra s] sets the reallocation strategy of resizable array [ra] to [s], possibly causing an immediate reallocation. *) val put_strategy : 'a t -> strategy -> unit (** [put_strategy ra s] sets the reallocation strategy of resizable array [ra] to [s]. Reallocation is only done at later changes in size. *) val enforce_strategy : 'a t -> unit (** [enforce_strategy ra] forces a reallocation if necessary (e.g. after a [put_strategy]). *) (** {6 Copying, blitting and range extraction} *) val copy : 'a t -> 'a t (** [copy ra] @return a copy of resizable array [ra]. The two arrays share the same strategy! *) val sub : 'a t -> int -> int -> 'a t (** [sub ra ofs len] @return a resizable subarray of length [len] from resizable array [ra] starting at offset [ofs] using the default strategy. @raise Invalid_argument if parameters do not denote a correct subarray. *) val fill : 'a t -> int -> int -> 'a option -> unit (** [fill ra ofs len el] fills resizable array [ra] from offset [ofs] with [len] elements [el], possibly adding elements at the end. Raises [Invalid_argument] if offset [ofs] is larger than the length of the array. *) val blit : 'a t -> int -> 'a t -> int -> int -> unit (** [blit ra1 ofs1 ra2 ofs2 len] blits resizable array [ra1] onto [ra2] reading [len] elements from offset [ofs1] and writing them to [ofs2], possibly adding elements at the end of ra2. Raises [Invalid_argument] if [ofs1] and [len] do not designate a valid subarray of [ra1] or if [ofs2] is larger than the length of [ra2]. *) (** {6 Combining resizable arrays} *) val append : 'a t -> 'a t -> 'a t (** [append ra1 ra2] @return a new resizable array using the default strategy and copying [ra1] and [ra2] in this order onto it. *) val concat : 'a t list -> 'a t (** [concat l] @return a new resizable array using the default strategy and copying all resizable arrays in [l] in their respective order onto it. *) (** {6 Adding and removing elements} *) val add_one : 'a t -> 'a option -> unit (** [add_one ra el] adds element [el] to resizable array [ra], possibly causing a reallocation. *) val remove_one : 'a t -> unit (** [remove_one ra] removes the last element of resizable array [ra], possibly causing a reallocation. @raise Failure if the array is empty. *) val remove_n : 'a t -> int -> unit (** [remove_n ra n] removes the last n elements of resizable array [ra], possibly causing a reallocation. @raise Invalid_arg if there are not enough elements or [n < 0]. *) val remove_range : 'a t -> int -> int -> unit (** [remove_range ra ofs len] removes [len] elements from resizable array [ra] starting at [ofs] and possibly causing a reallocation. @raise Invalid_argument if range is invalid. *) val clear : 'a t -> unit (** [clear ra] removes all elements from resizable array [ra], possibly causing a reallocation. *) (** {6 Swapping} *) val swap : 'a t -> int -> int -> unit (** [swap ra n m] swaps elements at indices [n] and [m]. @raise Invalid_argument if any index is out of range. *) val swap_in_last : 'a t -> int -> unit (** [swap_in_last ra n] swaps the last element with the one at position [n]. @raise Invalid_argument if index [n] is out of range. *) (** {6 Standard conversions} *) val to_std : 'a t -> 'a Weak.t (** [to_std ra] converts a resizable weak array to a standard one. *) val sof_std : strategy -> 'a Weak.t -> 'a t (** [sof_std s ar] converts a standard weak array to a resizable one, using strategy [s]. *) val of_std : 'a Weak.t -> 'a t (** [of_std ar] converts a standard weak array to a resizable one using the default strategy. *) (** {6 List conversions} *) val to_list : 'a t -> 'a option list (** [to_list ra] converts resizable array [ra] to a list. *) val of_list : 'a option list -> 'a t (** [of_list l] creates a resizable array using the default strategy and the elements in list [l]. *) (** {6 Iterators} *) val iter : ('a option -> unit) -> 'a t -> unit (** [iter f ra] applies the unit-function [f] to each element in resizable array [ra]. *) val iteri : (int -> 'a option -> unit) -> 'a t -> unit (** [iteri f ra] applies the unit-function [f] to each index and element in resizable array [ra]. *) val fold_left : ('b -> 'a option -> 'b) -> 'b -> 'a t -> 'b (** [fold_left f a ra] left-folds values in resizable array [ra] using function [f] and start accumulator [a]. *) val fold_right : ('a option -> 'b -> 'b) -> 'a t -> 'b -> 'b (** [fold_right f a ra] right-folds values in resizable array [ra] using function [f] and start accumulator [a]. *) (** {6 Scanning of resizable arrays} *) val for_all : ('a option -> bool) -> 'a t -> bool (** [for_all p ra] @return [true] if all elements in resizable array [ra] satisfy the predicate [p], [false] otherwise. *) val exists : ('a option -> bool) -> 'a t -> bool (** [exists p ra] @return [true] if at least one element in resizable array [ra] satisfies the predicate [p], [false] otherwise. *) val mem : 'a option -> 'a t -> bool (** [mem el ra] @return [true] if element [el] is logically equal to any element in resizable array [ra], [false] otherwise. *) val memq : 'a option -> 'a t -> bool (** [memq el ra] @return [true] if element [el] is physically equal to any element in resizable array [ra], [false] otherwise. *) val pos : 'a option -> 'a t -> int option (** [pos el ra] @return [Some index] if [el] is logically equal to the element at [index] in [ra], [None] otherwise. [index] is the index of the first element that matches. *) val posq : 'a option -> 'a t -> int option (** [posq el ra] @return [Some index] if [el] is physically equal to the element at [index] in [ra], [None] otherwise. [index] is the index of the first element that matches. *) (** {6 Searching of resizable arrays} *) val find : ('a option -> bool) -> 'a t -> 'a option (** [find p ra] @return the first element in resizable array [ra] that satisfies predicate [p]. @raise Not_found if there is no such element. *) val find_index : ('a option -> bool) -> 'a t -> int -> int (** [find_index p ra pos] @return the index of the first element that satisfies predicate [p] in resizable array [ra], starting search at index [pos]. @raise Not_found if there is no such element or if [pos] is larger than the highest index. @raise Invalid_argument if [pos] is negative. *) val filter : ('a option -> bool) -> 'a t -> 'a t (** [filter p ra] @return a new resizable array by filtering out all elements in [ra] that satisfy predicate [p] using the same strategy as [ra]. *) val find_all : ('a option -> bool) -> 'a t -> 'a t (** [find_all p ra] is the same as [filter] *) val filter_in_place : ('a option -> bool) -> 'a t -> unit (** [filter_in_place p ra] as [filter], but filters in place. *) val partition : ('a option -> bool) -> 'a t -> 'a t * 'a t (** [partition p ra] @return a pair of resizable arrays, the left part containing only elements of [ra] that satisfy predicate [p], the right one only those that do not satisfy it. Both returned arrays are created using the strategy of [ra]. *) (** {6 {b UNSAFE STUFF - USE WITH CAUTION!}} *) val unsafe_get : 'a t -> int -> 'a option val unsafe_set : 'a t -> int -> 'a option -> unit val unsafe_sub : 'a t -> int -> int -> 'a t val unsafe_fill : 'a t -> int -> int -> 'a option -> unit val unsafe_blit : 'a t -> int -> 'a t -> int -> int -> unit val unsafe_remove_one : 'a t -> unit val unsafe_remove_n : 'a t -> int -> unit val unsafe_swap : 'a t -> int -> int -> unit val unsafe_swap_in_last : 'a t -> int -> unit end