transpose-0.2.2/.cargo_vcs_info.json0000644000000001360000000000100130530ustar { "git": { "sha1": "e70dd159f1881d86aa50ee01586d04e7a83d8dbe" }, "path_in_vcs": "" }transpose-0.2.2/.gitignore000064400000000000000000000000410072674642500136560ustar 00000000000000/target **/*.rs.bk Cargo.lock transpose-0.2.2/Cargo.toml0000644000000021500000000000100110470ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] name = "transpose" version = "0.2.2" authors = ["Elliott Mahler "] description = "Utility for transposing multi-dimensional data" documentation = "http://docs.rs/transpose" readme = "README.md" keywords = [ "array", "transpose", "2d", ] categories = [ "algorithms", "data structures", "no-std", ] license = "MIT OR Apache-2.0" repository = "http://github.com/ejmahler/transpose" [[bench]] name = "transpose_benchmarks" harness = false [dependencies.num-integer] version = "0.1" default-features = false [dependencies.strength_reduce] version = "^0.2.1" [dev-dependencies.criterion] version = "0.3" transpose-0.2.2/Cargo.toml.orig000064400000000000000000000012060072674642500145610ustar 00000000000000[package] name = "transpose" version = "0.2.2" authors = ["Elliott Mahler "] description = "Utility for transposing multi-dimensional data" license = "MIT OR Apache-2.0" repository = "http://github.com/ejmahler/transpose" documentation = "http://docs.rs/transpose" keywords = ["array", "transpose", "2d"] categories = ["algorithms", "data structures", "no-std"] readme = "README.md" [dependencies] strength_reduce = "^0.2.1" [dependencies.num-integer] version = "0.1" default-features = false [dev-dependencies] criterion = "0.3" [[bench]] name = "transpose_benchmarks" harness = false transpose-0.2.2/LICENSE-APACHE000064400000000000000000000254450072674642500136310ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2022 The transpose developers Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. transpose-0.2.2/LICENSE-MIT000064400000000000000000000021050072674642500133250ustar 00000000000000Copyright (c) 2022 The transpose Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. transpose-0.2.2/README.md000064400000000000000000000033030072674642500131510ustar 00000000000000# transpose [![crate](https://img.shields.io/crates/v/transpose.svg)](https://crates.io/crates/transpose) [![license](https://img.shields.io/crates/l/transpose.svg)](https://crates.io/crates/transpose) [![documentation](https://docs.rs/transpose/badge.svg)](https://docs.rs/transpose/) ![minimum rustc 1.26](https://img.shields.io/badge/rustc-1.26+-red.svg) Utility for transposing multi-dimensional data See the [API Documentation](https://docs.rs/transpose/) for more details. `transpose` is `#![no_std]` ## Example ```rust // Create a 2D array in row-major order: the rows of our 2D array are contiguous, // and the columns are strided let input_array = vec![ 1, 2, 3, 4, 5, 6]; // Treat our 6-element array as a 2D 3x2 array, and transpose it to a 2x3 array let mut output_array = vec![0; 6]; transpose::transpose(&input_array, &mut output_array, 3, 2); // The rows have become the columns, and the columns have become the rows let expected_array = vec![ 1, 4, 2, 5, 3, 6]; assert_eq!(output_array, expected_array); ``` ## Compatibility The `transpose` crate requires rustc 1.26 or greater. ## License Licensed under either of * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. transpose-0.2.2/RELEASES.md000064400000000000000000000011000072674642500134100ustar 00000000000000# Release 0.2.2 (2022-11-07) ## Fixes - Added missing license files - Upgraded `criterion` dependency from 0.2 to 0.3 # Release 0.2.1 (2020-03-30) ## Improvements - Significantly improved the performance of the out-of-place transpose - Removed depenendence on `std` in the `num_integer` dependency. # Release 0.2.0 (2019-01-04) ## Features - Implemented an in-place transpose. ### Breaking Changes - Documented minimum rust version to be 1.26 # Release 0.1.0 (2019-01-01) - Initial release. Support for an out-of-place transpose. transpose-0.2.2/benches/transpose_benchmarks.rs000064400000000000000000000042550072674642500200710ustar 00000000000000#[macro_use] extern crate criterion; extern crate transpose; use criterion::{Criterion, ParameterizedBenchmark, Throughput}; use std::mem; use std::time::Duration; fn bench_oop_transpose(c: &mut Criterion, tyname: &str) { let ref sizes = [(4, 4), (8, 8), (16, 16), (64, 64), (256, 256), (1024, 1024), (2048, 2048), (4096, 4096)]; let bench = ParameterizedBenchmark::new(tyname, |b, &&(width, height)| { let mut buffer = vec![T::default(); width * height]; let mut scratch = vec![T::default(); width * height]; b.iter(|| { transpose::transpose(&mut buffer, &mut scratch, width, height); }); }, sizes) .throughput(|&&(width, height)| Throughput::Bytes((width * height * mem::size_of::()) as u32)) .warm_up_time(Duration::from_secs(1)); c.bench("square transposes out-of-place", bench); } fn bench_oop_u32(c: &mut Criterion) { bench_oop_transpose::(c, "u32") } fn bench_oop_u64(c: &mut Criterion) { bench_oop_transpose::(c, "u64") } criterion_group!(out_of_place_benches, bench_oop_u32, bench_oop_u64); fn bench_inplace_transpose(c: &mut Criterion, tyname: &str) { let ref sizes = [(4, 4), (8, 8), (16, 16), (64, 64), (256, 256), (1024, 1024)]; let bench = ParameterizedBenchmark::new(tyname, |b, &&(width, height)| { let mut buffer = vec![T::default(); width * height]; let mut scratch = vec![T::default(); std::cmp::max(width, height)]; b.iter(|| { transpose::transpose_inplace(&mut buffer, &mut scratch, width, height); }); }, sizes) .throughput(|&&(width, height)| Throughput::Bytes((width * height * mem::size_of::()) as u32)) .warm_up_time(Duration::from_secs(1)); c.bench("square transposes inplace", bench); } fn bench_inplace_u32(c: &mut Criterion) { bench_inplace_transpose::(c, "u32") } fn bench_inplace_u64(c: &mut Criterion) { bench_inplace_transpose::(c, "u64") } criterion_group!(inplace_benches, bench_inplace_u32, bench_inplace_u64); criterion_main!(out_of_place_benches, inplace_benches); transpose-0.2.2/src/in_place.rs000064400000000000000000000112260072674642500146040ustar 00000000000000 use strength_reduce::StrengthReducedUsize; use num_integer; fn multiplicative_inverse(a: usize, n: usize) -> usize { // we're going to use a modified version extended euclidean algorithm // we only need half the output let mut t = 0; let mut t_new = 1; let mut r = n; let mut r_new = a; while r_new > 0 { let quotient = r / r_new; r = r - quotient * r_new; core::mem::swap(&mut r, &mut r_new); // t might go negative here, so we have to do a checked subtract // if it underflows, wrap it around to the other end of the modulo // IE, 3 - 4 mod 5 = -1 mod 5 = 4 let t_subtract = quotient * t_new; t = if t_subtract < t { t - t_subtract } else { n - (t_subtract - t) % n }; core::mem::swap(&mut t, &mut t_new); } t } /// Transpose the input array in-place. /// /// Given an input array of size input_width * input_height, representing flattened 2D data stored in row-major order, /// transpose the rows and columns of that input array, in-place. /// /// Despite being in-place, this algorithm requires max(width * height) in scratch space. /// /// ``` /// // row-major order: the rows of our 2D array are contiguous, /// // and the columns are strided /// let original_array = vec![ 1, 2, 3, /// 4, 5, 6]; /// let mut input_array = original_array.clone(); /// /// // Treat our 6-element array as a 2D 3x2 array, and transpose it to a 2x3 array /// // transpose_inplace requires max(width, height) scratch space, which is in this case 3 /// let mut scratch = vec![0; 3]; /// transpose::transpose_inplace(&mut input_array, &mut scratch, 3, 2); /// /// // The rows have become the columns, and the columns have become the rows /// let expected_array = vec![ 1, 4, /// 2, 5, /// 3, 6]; /// assert_eq!(input_array, expected_array); /// /// // If we transpose it again, we should get our original data back. /// transpose::transpose_inplace(&mut input_array, &mut scratch, 2, 3); /// assert_eq!(original_array, input_array); /// ``` /// /// # Panics /// /// Panics if `input.len() != input_width * input_height` or if `output.len() != input_width * input_height` pub fn transpose_inplace(buffer: &mut [T], scratch: &mut [T], width: usize, height: usize) { assert_eq!(width*height, buffer.len()); assert_eq!(core::cmp::max(width, height), scratch.len()); let gcd = StrengthReducedUsize::new(num_integer::gcd(width, height)); let a = StrengthReducedUsize::new(height / gcd); let b = StrengthReducedUsize::new(width / gcd); let a_inverse = multiplicative_inverse(a.get(), b.get()); let strength_reduced_height = StrengthReducedUsize::new(height); let index_fn = |x, y| x + y * width; if gcd.get() > 1 { for x in 0..width { let column_offset = (x / b) % strength_reduced_height; let wrapping_point = height - column_offset; // wrapped rotation -- do the "right half" of the array, then the "left half" for y in 0..wrapping_point { scratch[y] = buffer[index_fn(x, y + column_offset)]; } for y in wrapping_point..height { scratch[y] = buffer[index_fn(x, y + column_offset - height)]; } // copy the data back into the column for y in 0..height { buffer[index_fn(x, y)] = scratch[y]; } } } // Permute the rows { let row_scratch = &mut scratch[0..width]; for (y, row) in buffer.chunks_exact_mut(width).enumerate() { for x in 0..width { let helper_val = if y <= height + x%gcd - gcd.get() { x + y*(width-1) } else { x + y*(width-1) + height }; let (helper_div, helper_mod) = StrengthReducedUsize::div_rem(helper_val, gcd); let gather_x = (a_inverse * helper_div)%b + b.get()*helper_mod; row_scratch[x] = row[gather_x]; } row.copy_from_slice(row_scratch); } } // Permute the columns for x in 0..width { let column_offset = x % strength_reduced_height; let wrapping_point = height - column_offset; // wrapped rotation -- do the "right half" of the array, then the "left half" for y in 0..wrapping_point { scratch[y] = buffer[index_fn(x, y + column_offset)]; } for y in wrapping_point..height { scratch[y] = buffer[index_fn(x, y + column_offset - height)]; } // Copy the data back to the buffer, but shuffle it as we do so for y in 0..height { let shuffled_y = (y * width - (y / a)) % strength_reduced_height; buffer[index_fn(x, y)] = scratch[shuffled_y]; } } } transpose-0.2.2/src/lib.rs000064400000000000000000000037240072674642500136040ustar 00000000000000//! Utility for transposing multi-dimensional data stored as a flat slice //! //! This library treats Rust slices as flattened row-major 2D arrays, and provides functions to transpose these 2D arrays, so that the row data becomes the column data, and vice versa. //! ``` //! // Create a 2D array in row-major order: the rows of our 2D array are contiguous, //! // and the columns are strided //! let input_array = vec![ 1, 2, 3, //! 4, 5, 6]; //! //! // Treat our 6-element array as a 2D 3x2 array, and transpose it to a 2x3 array //! let mut output_array = vec![0; 6]; //! transpose::transpose(&input_array, &mut output_array, 3, 2); //! //! // The rows have become the columns, and the columns have become the rows //! let expected_array = vec![ 1, 4, //! 2, 5, //! 3, 6]; //! assert_eq!(output_array, expected_array); //! //! // If we transpose our data again, we should get our original data back. //! let mut final_array = vec![0; 6]; //! transpose::transpose(&output_array, &mut final_array, 2, 3); //! assert_eq!(final_array, input_array); //! ``` //! //! This library supports both in-place and out-of-place transposes. The out-of-place //! transpose is much, much faster than the in-place transpose -- the in-place transpose should //! only be used in situations where the system doesn't have enough memory to do an out-of-place transpose. //! //! The out-of-place transpose uses one out of three different algorithms depending on the length of the input array. //! //! - Small: simple iteration over the array. //! - Medium: divide the array into tiles of fixed size, and process each tile separately. //! - Large: recursively split the array into smaller parts until each part is of a good size for the tiling algorithm, and then transpose each part. #![no_std] extern crate num_integer; extern crate strength_reduce; mod in_place; mod out_of_place; pub use in_place::transpose_inplace; pub use out_of_place::transpose; transpose-0.2.2/src/out_of_place.rs000064400000000000000000000254350072674642500155000ustar 00000000000000// Block size used by the tiling algoritms const BLOCK_SIZE: usize = 16; // Number of segments used by the segmented block transpose function const NBR_SEGMENTS: usize = 4; // recursively split data until the number of rows and columns is below this number const RECURSIVE_LIMIT: usize = 128; // Largest size for for using the direct approach const SMALL_LEN: usize = 255; // Largest size for using the tiled approach const MEDIUM_LEN: usize = 1024*1024; /// Given an array of size width * height, representing a flattened 2D array, /// transpose the rows and columns of that 2D array into the output. /// Benchmarking shows that loop tiling isn't effective for small arrays. unsafe fn transpose_small(input: &[T], output: &mut [T], width: usize, height: usize) { for x in 0..width { for y in 0..height { let input_index = x + y * width; let output_index = y + x * height; *output.get_unchecked_mut(output_index) = *input.get_unchecked(input_index); } } } // Transpose a subset of the array, from the input into the output. The idea is that by transposing one block at a time, we can be more cache-friendly // SAFETY: Width * height must equal input.len() and output.len(), start_x + block_width must be <= width, start_y + block height must be <= height unsafe fn transpose_block(input: &[T], output: &mut [T], width: usize, height: usize, start_x: usize, start_y: usize, block_width: usize, block_height: usize) { for inner_x in 0..block_width { for inner_y in 0..block_height { let x = start_x + inner_x; let y = start_y + inner_y; let input_index = x + y * width; let output_index = y + x * height; *output.get_unchecked_mut(output_index) = *input.get_unchecked(input_index); } } } // Transpose a subset of the array, from the input into the output. The idea is that by transposing one block at a time, we can be more cache-friendly // SAFETY: Width * height must equal input.len() and output.len(), start_x + block_width must be <= width, start_y + block height must be <= height // This function works as `transpose_block`, but also divides the loop into a number of segments. This makes it more cache fiendly for large sizes. unsafe fn transpose_block_segmented(input: &[T], output: &mut [T], width: usize, height: usize, start_x: usize, start_y: usize, block_width: usize, block_height: usize) { let height_per_div = block_height/NBR_SEGMENTS; for subblock in 0..NBR_SEGMENTS { for inner_x in 0..block_width { for inner_y in 0..height_per_div { let x = start_x + inner_x; let y = start_y + inner_y + subblock*height_per_div; let input_index = x + y * width; let output_index = y + x * height; *output.get_unchecked_mut(output_index) = *input.get_unchecked(input_index); } } } } /// Given an array of size width * height, representing a flattened 2D array, /// transpose the rows and columns of that 2D array into the output. /// This algorithm divides the input into tiles of size BLOCK_SIZE*BLOCK_SIZE, /// in order to reduce cache misses. This works well for medium sizes, when the /// data for each tile fits in the caches. fn transpose_tiled(input: &[T], output: &mut [T], input_width: usize, input_height: usize) { let x_block_count = input_width / BLOCK_SIZE; let y_block_count = input_height / BLOCK_SIZE; let remainder_x = input_width - x_block_count * BLOCK_SIZE; let remainder_y = input_height - y_block_count * BLOCK_SIZE; for y_block in 0..y_block_count { for x_block in 0..x_block_count { unsafe { transpose_block( input, output, input_width, input_height, x_block * BLOCK_SIZE, y_block * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE, ); } } //if the input_width is not cleanly divisible by block_size, there are still a few columns that haven't been transposed if remainder_x > 0 { unsafe { transpose_block( input, output, input_width, input_height, input_width - remainder_x, y_block * BLOCK_SIZE, remainder_x, BLOCK_SIZE); } } } //if the input_height is not cleanly divisible by BLOCK_SIZE, there are still a few rows that haven't been transposed if remainder_y > 0 { for x_block in 0..x_block_count { unsafe { transpose_block( input, output, input_width, input_height, x_block * BLOCK_SIZE, input_height - remainder_y, BLOCK_SIZE, remainder_y, ); } } //if the input_width is not cleanly divisible by block_size, there are still a few rows+columns that haven't been transposed if remainder_x > 0 { unsafe { transpose_block( input, output, input_width, input_height, input_width - remainder_x, input_height - remainder_y, remainder_x, remainder_y); } } } } /// Given an array of size width * height, representing a flattened 2D array, /// transpose the rows and columns of that 2D array into the output. /// This is a recursive algorithm that divides the array into smaller pieces, until they are small enough to /// transpose directly without worrying about cache misses. /// Once they are small enough, they are transposed using a tiling algorithm. fn transpose_recursive(input: &[T], output: &mut [T], row_start: usize, row_end: usize, col_start: usize, col_end: usize, total_columns: usize, total_rows: usize) { let nbr_rows = row_end - row_start; let nbr_cols = col_end - col_start; if (nbr_rows <= RECURSIVE_LIMIT && nbr_cols <= RECURSIVE_LIMIT) || nbr_rows<=2 || nbr_cols<=2 { let x_block_count = nbr_cols / BLOCK_SIZE; let y_block_count = nbr_rows / BLOCK_SIZE; let remainder_x = nbr_cols - x_block_count * BLOCK_SIZE; let remainder_y = nbr_rows - y_block_count * BLOCK_SIZE; for y_block in 0..y_block_count { for x_block in 0..x_block_count { unsafe { transpose_block_segmented( input, output, total_columns, total_rows, col_start + x_block * BLOCK_SIZE, row_start + y_block * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE, ); } } //if the input_width is not cleanly divisible by block_size, there are still a few columns that haven't been transposed if remainder_x > 0 { unsafe { transpose_block( input, output, total_columns, total_rows, col_start + x_block_count * BLOCK_SIZE, row_start + y_block * BLOCK_SIZE, remainder_x, BLOCK_SIZE); } } } //if the input_height is not cleanly divisible by BLOCK_SIZE, there are still a few rows that haven't been transposed if remainder_y > 0 { for x_block in 0..x_block_count { unsafe { transpose_block( input, output, total_columns, total_rows, col_start + x_block * BLOCK_SIZE, row_start + y_block_count * BLOCK_SIZE, BLOCK_SIZE, remainder_y, ); } } //if the input_width is not cleanly divisible by block_size, there are still a few rows+columns that haven't been transposed if remainder_x > 0 { unsafe { transpose_block( input, output, total_columns, total_rows, col_start + x_block_count * BLOCK_SIZE, row_start + y_block_count * BLOCK_SIZE, remainder_x, remainder_y); } } } } else if nbr_rows >= nbr_cols { transpose_recursive(input, output, row_start, row_start + (nbr_rows / 2), col_start, col_end, total_columns, total_rows); transpose_recursive(input, output, row_start + (nbr_rows / 2), row_end, col_start, col_end, total_columns, total_rows); } else { transpose_recursive(input, output, row_start, row_end, col_start, col_start + (nbr_cols / 2), total_columns, total_rows); transpose_recursive(input, output, row_start, row_end, col_start + (nbr_cols / 2), col_end, total_columns, total_rows); } } /// Transpose the input array into the output array. /// /// Given an input array of size input_width * input_height, representing flattened 2D data stored in row-major order, /// transpose the rows and columns of that input array into the output array /// ``` /// // row-major order: the rows of our 2D array are contiguous, /// // and the columns are strided /// let input_array = vec![ 1, 2, 3, /// 4, 5, 6]; /// /// // Treat our 6-element array as a 2D 3x2 array, and transpose it to a 2x3 array /// let mut output_array = vec![0; 6]; /// transpose::transpose(&input_array, &mut output_array, 3, 2); /// /// // The rows have become the columns, and the columns have become the rows /// let expected_array = vec![ 1, 4, /// 2, 5, /// 3, 6]; /// assert_eq!(output_array, expected_array); /// /// // If we transpose it again, we should get our original data back. /// let mut final_array = vec![0; 6]; /// transpose::transpose(&output_array, &mut final_array, 2, 3); /// assert_eq!(final_array, input_array); /// ``` /// /// # Panics /// /// Panics if `input.len() != input_width * input_height` or if `output.len() != input_width * input_height` pub fn transpose(input: &[T], output: &mut [T], input_width: usize, input_height: usize) { assert_eq!(input_width*input_height, input.len()); assert_eq!(input_width*input_height, output.len()); if input.len() <= SMALL_LEN { unsafe { transpose_small(input, output, input_width, input_height) }; } else if input.len() <= MEDIUM_LEN { transpose_tiled(input, output, input_width, input_height); } else { transpose_recursive(input, output, 0, input_height, 0, input_width, input_width, input_height); } } transpose-0.2.2/tests/test_transpose.rs000064400000000000000000000026210072674642500164610ustar 00000000000000extern crate transpose; fn gen_data(width: usize, height: usize) -> Vec { (0..width*height).collect() } const BLOCK_SIZE: usize = 16; #[test] fn test_out_of_place_transpose() { let sizes = [ 0, 1, 2, BLOCK_SIZE - 1, BLOCK_SIZE, BLOCK_SIZE + 1, BLOCK_SIZE * 4 - 1, BLOCK_SIZE * 5, BLOCK_SIZE * 4 + 1 ]; for &width in &sizes { for &height in &sizes { let input = gen_data(width, height); let mut output = vec![0; width * height]; transpose::transpose(&input, &mut output, width, height); for x in 0..width { for y in 0..height { assert_eq!(input[x + y * width], output[y + x * height], "x = {}, y = {}", x, y); } } } } } #[test] fn test_transpose_inplace() { for width in 1..10 { for height in 1..10 { let input = gen_data(width, height); let mut output = input.clone(); let mut scratch = vec![usize::default(); std::cmp::max(width, height)]; transpose::transpose_inplace(&mut output, &mut scratch, width, height); for x in 0..width { for y in 0..height { assert_eq!(input[x + y * width], output[y + x * height], "x = {}, y = {}", x, y); } } } } }