pub trait ZigZag {
type UInt;
// Required methods
fn zigzag_encode(value: Self) -> Self::UInt;
fn zigzag_decode(value: Self::UInt) -> Self;
// Provided methods
fn zigzag_encode_slice(values: &[Self], out: &mut [Self::UInt])
where Self: Sized + Copy { ... }
fn zigzag_decode_slice(values: &[Self::UInt], out: &mut [Self])
where Self: Sized + Copy,
Self::UInt: Copy { ... }
fn try_zigzag_encode_slice(
values: &[Self],
out: &mut [Self::UInt],
) -> Result<(), ZigZagError>
where Self: Sized + Copy { ... }
fn try_zigzag_decode_slice(
values: &[Self::UInt],
out: &mut [Self],
) -> Result<(), ZigZagError>
where Self: Sized + Copy,
Self::UInt: Copy { ... }
}Expand description
Trait for ZigZag encoding, used to convert signed integers to unsigned integers
Required Associated Types§
Required Methods§
Sourcefn zigzag_encode(value: Self) -> Self::UInt
fn zigzag_encode(value: Self) -> Self::UInt
Encode a signed integer to an unsigned integer
Sourcefn zigzag_decode(value: Self::UInt) -> Self
fn zigzag_decode(value: Self::UInt) -> Self
Decode an unsigned integer back to a signed integer
Provided Methods§
Sourcefn zigzag_encode_slice(values: &[Self], out: &mut [Self::UInt])
fn zigzag_encode_slice(values: &[Self], out: &mut [Self::UInt])
Encode a slice of signed integers to unsigned integers
§Arguments
values- Slice of signed integers to encodeout- Output slice to store encoded unsigned integers
§Panics
Panics if out is smaller than values
Examples found in repository?
3fn main() {
4 println!("ZigZag Encoding Examples:");
5
6 // Encode different integer types (single values)
7 println!("Single Value Encoding:");
8 println!("i8: -1 encoded as: {} (u8)", i8::zigzag_encode(-1));
9 println!("i16: 10 encoded as: {} (u16)", i16::zigzag_encode(10));
10 println!("i32: -100 encoded as: {} (u32)", i32::zigzag_encode(-100));
11 println!("i64: 1000 encoded as: {} (u64)", i64::zigzag_encode(1000));
12
13 println!("\nZigZag Decoding Examples:");
14
15 // Decode different integer types (single values)
16 println!("Single Value Decoding:");
17 println!("u8: 1 decoded as: {} (i8)", i8::zigzag_decode(1u8));
18 println!("u16: 20 decoded as: {} (i16)", i16::zigzag_decode(20u16));
19 println!("u32: 200 decoded as: {} (i32)", i32::zigzag_decode(200u32));
20 println!("u64: 2000 decoded as: {} (i64)", i64::zigzag_decode(2000u64));
21
22 // Demonstrate round-trip conversion (single value)
23 let original = -42i32;
24 let encoded = i32::zigzag_encode(original);
25 let decoded = i32::zigzag_decode(encoded);
26
27 println!("\nRound-trip Conversion Example (Single Value):");
28 println!("Original value: {}", original);
29 println!("Encoded as: {}", encoded);
30 println!("Decoded back: {}", decoded);
31 println!("Conversion successful: {}", original == decoded);
32
33 // Demonstrate batch processing
34 println!("\nBatch Processing Example:");
35 let values = [-100i32, -10, -1, 0, 1, 10, 100];
36 let mut encoded = [0u32; 7];
37 let mut decoded = [0i32; 7];
38
39 // Encode array
40 i32::zigzag_encode_slice(&values, &mut encoded);
41
42 println!("Original values: {:?}", values);
43 println!("Encoded values: {:?}", encoded);
44
45 // Decode array
46 i32::zigzag_decode_slice(&encoded, &mut decoded);
47 println!("Decoded values: {:?}", decoded);
48 println!("Batch round-trip successful: {}", values == decoded);
49}More examples
4fn main() {
5 const ITERATIONS: usize = 10_000_000;
6 const BATCH_SIZE: usize = 1000;
7
8 println!("Running ZigZag encoding/decoding performance test");
9
10 // Test single value i32 encoding
11 let start = std::time::Instant::now();
12 let mut sum = 0u32;
13 for i in 0..ITERATIONS {
14 let val = (i % 1000) as i32 - 500; // Cycle between -500 and 499
15 sum = sum.wrapping_add(i32::zigzag_encode(val));
16 }
17 let duration = start.elapsed();
18 println!("i32 single value encoding: {:?} for {} operations (checksum: {})",
19 duration, ITERATIONS, sum);
20
21 // Test single value i32 decoding
22 let start = std::time::Instant::now();
23 let mut sum = 0i32;
24 for i in 0..ITERATIONS {
25 let val = (i % 1000) as u32;
26 sum = sum.wrapping_add(i32::zigzag_decode(val));
27 }
28 let duration = start.elapsed();
29 println!("i32 single value decoding: {:?} for {} operations (checksum: {})",
30 duration, ITERATIONS, sum);
31
32 // Test batch i32 encoding
33 let mut values = [0i32; BATCH_SIZE];
34 let mut encoded = [0u32; BATCH_SIZE];
35
36 // Initialize test data
37 for i in 0..BATCH_SIZE {
38 values[i] = (i as i32) - (BATCH_SIZE as i32 / 2);
39 }
40
41 // Measure batch encoding performance
42 let batch_iterations = ITERATIONS / BATCH_SIZE;
43 let start = std::time::Instant::now();
44 for _ in 0..batch_iterations {
45 i32::zigzag_encode_slice(&values, &mut encoded);
46 }
47 let duration = start.elapsed();
48 println!("i32 batch encoding: {:?} for {} batches of {} values (total: {} operations)",
49 duration, batch_iterations, BATCH_SIZE, batch_iterations * BATCH_SIZE);
50
51 // Measure batch decoding performance
52 let start = std::time::Instant::now();
53 for _ in 0..batch_iterations {
54 i32::zigzag_decode_slice(&encoded, &mut values);
55 }
56 let duration = start.elapsed();
57 println!("i32 batch decoding: {:?} for {} batches of {} values (total: {} operations)",
58 duration, batch_iterations, BATCH_SIZE, batch_iterations * BATCH_SIZE);
59
60 // Check if expected values after round-trip are preserved
61 let mut original = [0i32; BATCH_SIZE];
62 for i in 0..BATCH_SIZE {
63 original[i] = (i as i32) - (BATCH_SIZE as i32 / 2);
64 }
65 assert_eq!(values, original, "Batch round-trip values should be preserved");
66
67 println!("\nComparing single value vs batch processing efficiency:");
68 println!("This comparison shows if batch processing provides any optimization beyond \
69 just calling single operations in sequence.");
70}3fn main() {
4 println!("ZigZag Iterator-based API Examples");
5 println!("================================\n");
6
7 // Source data
8 let values = [-100, -10, -1, 0, 1, 10, 100];
9 println!("Original values: {:?}", values);
10
11 // Basic encode iterator example
12 println!("\n1. Basic encoding with iterator");
13 println!("----------------------------");
14 let encoded_iter = zigzag_encode_iter::<i32, _>(values.iter());
15
16 // We can display the values as they are generated
17 println!("Encoded values: ");
18 for encoded in encoded_iter {
19 print!("{} ", encoded);
20 }
21 println!();
22
23 // Demonstrate conversion without allocating a buffer
24 println!("\n2. Pairing original and encoded values");
25 println!("----------------------------------");
26 let encoded_iter = zigzag_encode_iter::<i32, _>(values.iter());
27 for (original, encoded) in values.iter().zip(encoded_iter) {
28 println!("{:5} encodes to {:5}", original, encoded);
29 }
30
31 // Decoding example
32 println!("\n3. Iterator-based decoding");
33 println!("------------------------");
34 let encoded = [199u32, 19, 1, 0, 2, 20, 200];
35 println!("Encoded values: {:?}", encoded);
36
37 println!("Decoded values: ");
38 let decoded_iter = zigzag_decode_iter::<i32, _>(encoded.iter());
39 for decoded in decoded_iter {
40 print!("{} ", decoded);
41 }
42 println!();
43
44 // Filtering example
45 println!("\n4. Combining with other iterator operations");
46 println!("---------------------------------------");
47 let values = [-100, -50, -10, -5, -1, 0, 1, 5, 10, 50, 100];
48
49 // Create an iterator that only processes positive values
50 println!("Original values: {:?}", values);
51 println!("Processing only positive values:");
52
53 let filtered_encoded: Vec<u32> = values.iter()
54 .filter(|&&x| x > 0) // Only positive values
55 .map(|&x| i32::zigzag_encode(x)) // Encode them
56 .collect(); // Collect results
57
58 println!("Filtered and encoded: {:?}", filtered_encoded);
59
60 // Memory efficiency example
61 println!("\n5. Memory efficiency comparison");
62 println!("----------------------------");
63
64 // Traditional approach with intermediate allocations
65 let large_range: Vec<i32> = (-1000..1000).collect();
66 println!("Processing {} values", large_range.len());
67
68 println!("Traditional approach (with buffer allocation):");
69 let start = std::time::Instant::now();
70 let mut encoded_buffer = vec![0u32; large_range.len()];
71 i32::zigzag_encode_slice(&large_range, &mut encoded_buffer);
72
73 let mut decoded_buffer = vec![0i32; encoded_buffer.len()];
74 i32::zigzag_decode_slice(&encoded_buffer, &mut decoded_buffer);
75 let duration = start.elapsed();
76 println!("Time with buffers: {:?}", duration);
77
78 // Iterator-based approach
79 println!("Iterator-based approach:");
80 let start = std::time::Instant::now();
81
82 // Process without intermediate allocations
83 let sum: i32 = zigzag_decode_iter::<i32, _>(
84 zigzag_encode_iter::<i32, _>(large_range.iter()).collect::<Vec<_>>().iter()
85 ).sum();
86
87 let duration = start.elapsed();
88 println!("Time with iterators: {:?}", duration);
89 println!("Sum of processed values: {}", sum);
90}Sourcefn zigzag_decode_slice(values: &[Self::UInt], out: &mut [Self])
fn zigzag_decode_slice(values: &[Self::UInt], out: &mut [Self])
Decode a slice of unsigned integers back to signed integers
§Arguments
values- Slice of unsigned integers to decodeout- Output slice to store decoded signed integers
§Panics
Panics if out is smaller than values
Examples found in repository?
3fn main() {
4 println!("ZigZag Encoding Examples:");
5
6 // Encode different integer types (single values)
7 println!("Single Value Encoding:");
8 println!("i8: -1 encoded as: {} (u8)", i8::zigzag_encode(-1));
9 println!("i16: 10 encoded as: {} (u16)", i16::zigzag_encode(10));
10 println!("i32: -100 encoded as: {} (u32)", i32::zigzag_encode(-100));
11 println!("i64: 1000 encoded as: {} (u64)", i64::zigzag_encode(1000));
12
13 println!("\nZigZag Decoding Examples:");
14
15 // Decode different integer types (single values)
16 println!("Single Value Decoding:");
17 println!("u8: 1 decoded as: {} (i8)", i8::zigzag_decode(1u8));
18 println!("u16: 20 decoded as: {} (i16)", i16::zigzag_decode(20u16));
19 println!("u32: 200 decoded as: {} (i32)", i32::zigzag_decode(200u32));
20 println!("u64: 2000 decoded as: {} (i64)", i64::zigzag_decode(2000u64));
21
22 // Demonstrate round-trip conversion (single value)
23 let original = -42i32;
24 let encoded = i32::zigzag_encode(original);
25 let decoded = i32::zigzag_decode(encoded);
26
27 println!("\nRound-trip Conversion Example (Single Value):");
28 println!("Original value: {}", original);
29 println!("Encoded as: {}", encoded);
30 println!("Decoded back: {}", decoded);
31 println!("Conversion successful: {}", original == decoded);
32
33 // Demonstrate batch processing
34 println!("\nBatch Processing Example:");
35 let values = [-100i32, -10, -1, 0, 1, 10, 100];
36 let mut encoded = [0u32; 7];
37 let mut decoded = [0i32; 7];
38
39 // Encode array
40 i32::zigzag_encode_slice(&values, &mut encoded);
41
42 println!("Original values: {:?}", values);
43 println!("Encoded values: {:?}", encoded);
44
45 // Decode array
46 i32::zigzag_decode_slice(&encoded, &mut decoded);
47 println!("Decoded values: {:?}", decoded);
48 println!("Batch round-trip successful: {}", values == decoded);
49}More examples
4fn main() {
5 const ITERATIONS: usize = 10_000_000;
6 const BATCH_SIZE: usize = 1000;
7
8 println!("Running ZigZag encoding/decoding performance test");
9
10 // Test single value i32 encoding
11 let start = std::time::Instant::now();
12 let mut sum = 0u32;
13 for i in 0..ITERATIONS {
14 let val = (i % 1000) as i32 - 500; // Cycle between -500 and 499
15 sum = sum.wrapping_add(i32::zigzag_encode(val));
16 }
17 let duration = start.elapsed();
18 println!("i32 single value encoding: {:?} for {} operations (checksum: {})",
19 duration, ITERATIONS, sum);
20
21 // Test single value i32 decoding
22 let start = std::time::Instant::now();
23 let mut sum = 0i32;
24 for i in 0..ITERATIONS {
25 let val = (i % 1000) as u32;
26 sum = sum.wrapping_add(i32::zigzag_decode(val));
27 }
28 let duration = start.elapsed();
29 println!("i32 single value decoding: {:?} for {} operations (checksum: {})",
30 duration, ITERATIONS, sum);
31
32 // Test batch i32 encoding
33 let mut values = [0i32; BATCH_SIZE];
34 let mut encoded = [0u32; BATCH_SIZE];
35
36 // Initialize test data
37 for i in 0..BATCH_SIZE {
38 values[i] = (i as i32) - (BATCH_SIZE as i32 / 2);
39 }
40
41 // Measure batch encoding performance
42 let batch_iterations = ITERATIONS / BATCH_SIZE;
43 let start = std::time::Instant::now();
44 for _ in 0..batch_iterations {
45 i32::zigzag_encode_slice(&values, &mut encoded);
46 }
47 let duration = start.elapsed();
48 println!("i32 batch encoding: {:?} for {} batches of {} values (total: {} operations)",
49 duration, batch_iterations, BATCH_SIZE, batch_iterations * BATCH_SIZE);
50
51 // Measure batch decoding performance
52 let start = std::time::Instant::now();
53 for _ in 0..batch_iterations {
54 i32::zigzag_decode_slice(&encoded, &mut values);
55 }
56 let duration = start.elapsed();
57 println!("i32 batch decoding: {:?} for {} batches of {} values (total: {} operations)",
58 duration, batch_iterations, BATCH_SIZE, batch_iterations * BATCH_SIZE);
59
60 // Check if expected values after round-trip are preserved
61 let mut original = [0i32; BATCH_SIZE];
62 for i in 0..BATCH_SIZE {
63 original[i] = (i as i32) - (BATCH_SIZE as i32 / 2);
64 }
65 assert_eq!(values, original, "Batch round-trip values should be preserved");
66
67 println!("\nComparing single value vs batch processing efficiency:");
68 println!("This comparison shows if batch processing provides any optimization beyond \
69 just calling single operations in sequence.");
70}3fn main() {
4 println!("ZigZag Iterator-based API Examples");
5 println!("================================\n");
6
7 // Source data
8 let values = [-100, -10, -1, 0, 1, 10, 100];
9 println!("Original values: {:?}", values);
10
11 // Basic encode iterator example
12 println!("\n1. Basic encoding with iterator");
13 println!("----------------------------");
14 let encoded_iter = zigzag_encode_iter::<i32, _>(values.iter());
15
16 // We can display the values as they are generated
17 println!("Encoded values: ");
18 for encoded in encoded_iter {
19 print!("{} ", encoded);
20 }
21 println!();
22
23 // Demonstrate conversion without allocating a buffer
24 println!("\n2. Pairing original and encoded values");
25 println!("----------------------------------");
26 let encoded_iter = zigzag_encode_iter::<i32, _>(values.iter());
27 for (original, encoded) in values.iter().zip(encoded_iter) {
28 println!("{:5} encodes to {:5}", original, encoded);
29 }
30
31 // Decoding example
32 println!("\n3. Iterator-based decoding");
33 println!("------------------------");
34 let encoded = [199u32, 19, 1, 0, 2, 20, 200];
35 println!("Encoded values: {:?}", encoded);
36
37 println!("Decoded values: ");
38 let decoded_iter = zigzag_decode_iter::<i32, _>(encoded.iter());
39 for decoded in decoded_iter {
40 print!("{} ", decoded);
41 }
42 println!();
43
44 // Filtering example
45 println!("\n4. Combining with other iterator operations");
46 println!("---------------------------------------");
47 let values = [-100, -50, -10, -5, -1, 0, 1, 5, 10, 50, 100];
48
49 // Create an iterator that only processes positive values
50 println!("Original values: {:?}", values);
51 println!("Processing only positive values:");
52
53 let filtered_encoded: Vec<u32> = values.iter()
54 .filter(|&&x| x > 0) // Only positive values
55 .map(|&x| i32::zigzag_encode(x)) // Encode them
56 .collect(); // Collect results
57
58 println!("Filtered and encoded: {:?}", filtered_encoded);
59
60 // Memory efficiency example
61 println!("\n5. Memory efficiency comparison");
62 println!("----------------------------");
63
64 // Traditional approach with intermediate allocations
65 let large_range: Vec<i32> = (-1000..1000).collect();
66 println!("Processing {} values", large_range.len());
67
68 println!("Traditional approach (with buffer allocation):");
69 let start = std::time::Instant::now();
70 let mut encoded_buffer = vec![0u32; large_range.len()];
71 i32::zigzag_encode_slice(&large_range, &mut encoded_buffer);
72
73 let mut decoded_buffer = vec![0i32; encoded_buffer.len()];
74 i32::zigzag_decode_slice(&encoded_buffer, &mut decoded_buffer);
75 let duration = start.elapsed();
76 println!("Time with buffers: {:?}", duration);
77
78 // Iterator-based approach
79 println!("Iterator-based approach:");
80 let start = std::time::Instant::now();
81
82 // Process without intermediate allocations
83 let sum: i32 = zigzag_decode_iter::<i32, _>(
84 zigzag_encode_iter::<i32, _>(large_range.iter()).collect::<Vec<_>>().iter()
85 ).sum();
86
87 let duration = start.elapsed();
88 println!("Time with iterators: {:?}", duration);
89 println!("Sum of processed values: {}", sum);
90}Sourcefn try_zigzag_encode_slice(
values: &[Self],
out: &mut [Self::UInt],
) -> Result<(), ZigZagError>
fn try_zigzag_encode_slice( values: &[Self], out: &mut [Self::UInt], ) -> Result<(), ZigZagError>
Try to encode a slice of signed integers to unsigned integers, returning a Result instead of panicking if the output buffer is too small
§Arguments
values- Slice of signed integers to encodeout- Output slice to store encoded unsigned integers
§Returns
Ok(())if all values were encoded successfullyErr(ZigZagError::BufferTooSmall)if output buffer is too small
Sourcefn try_zigzag_decode_slice(
values: &[Self::UInt],
out: &mut [Self],
) -> Result<(), ZigZagError>
fn try_zigzag_decode_slice( values: &[Self::UInt], out: &mut [Self], ) -> Result<(), ZigZagError>
Try to decode a slice of unsigned integers back to signed integers, returning a Result instead of panicking if the output buffer is too small
§Arguments
values- Slice of unsigned integers to decodeout- Output slice to store decoded signed integers
§Returns
Ok(())if all values were decoded successfullyErr(ZigZagError::BufferTooSmall)if output buffer is too small
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.