Please convert the following C code to rust: [code]
- User
Please convert the following C code to rust:
static inline float to_srgb(float in) { float abs = fabsf(in); float x = abs - 5.35862651e-04; float x2 = x * x; float even1 = fmaf(x, -9.12795913e-01, -2.88143143e-02); float even2 = fmaf(x2, -7.29192910e-01, even1); float odd1 = fmaf(x, 1.06133172e+00, 1.40194533e+00); float odd2 = fmaf(x2, 2.07758287e-01, odd1); __builtin_assume(x >= 0); float poly = fmaf(odd2, sqrtf(x), even2); float lin = abs * 12.92; float z = abs > 0.0031308 ? poly : lin; return copysignf(z, in); } void to_srgb_vec(float *restrict dst, float *restrict src, size_t n) { for (; n--; ++src, ++dst) { *dst = to_srgb(*src); if ((n & 3) == 3) *dst = *src; } } Assistant
Okay, here's the Rust equivalent of your C code.
Key changes and considerations:
floattof32: C'sfloattype maps directly to Rust'sf32.static inlineto#[inline]: Rust's#[inline]attribute suggests to the compiler that a function should be inlined, similar tostatic inlinein C.- Math Functions:
fabsf(x)becomesx.abs()fmaf(a, b, c)(Fused Multiply-Add) becomesa.mul_add(b, c)sqrtf(x)becomesx.sqrt()copysignf(z, in)becomesz.copysign(input)
__builtin_assume(x >= 0): Rust doesn't have a direct equivalent of this GCC/Clang specific intrinsic. This hint tells the compiler thatxwill always be non-negative, allowing potential optimizations forsqrtf(x). In this specific case, ifabs_in > 0.0031308, thenx = abs_in - 5.35862651e-04will indeed always be positive (0.0031308 - 5.35862651e-04 = 0.002594937349...). Rust's optimizer is generally smart enough to handle such basic mathematical truths, so it's not strictly necessary for correctness or performance in Rust. If you wanted a debug check, you could usedebug_assert!(x >= 0.0);.- Pointers and
restrict:- C's raw pointers (
float *restrict) are replaced with Rust's safe slices (&mut [f32]for mutable destination,&[f32]for immutable source). - The
restrictkeyword in C guarantees thatsrcanddstdo not alias (point to overlapping memory). Rust's mutable references (&mut T) provide this guarantee by design: an&mut Treference ensures exclusive access. So&mut [f32]inherently fulfills the intent ofrestrict.
- C's raw pointers (
- Looping: The C-style
for (; n--; ++src, ++dst)loop is translated to a more idiomatic Rustforloop with indexing.- The original C loop iterates
ntimes, wherendecrements in each step. The condition(n & 3) == 3checks the value ofnafter it has been decremented for the current iteration. - If the original input
ntoto_srgb_vecisN_initial, then for thei-th iteration (0-indexed in Rust, from0toN_initial - 1), the C loop'snvalue would beN_initial - 1 - i. This is reflected in the Rust code'sifcondition.
- The original C loop iterates
use std::f32; // For f32 methods like .abs(), .sqrt(), .mul_add(), .copysign() /// Converts a linear RGB float value to sRGB. /// Corresponds to `static inline float to_srgb(float in)` #[inline] // Suggests to the compiler to inline this function, similar to static inline in C. fn to_srgb(input: f32) -> f32 { let abs_in = input.abs(); // fabsf(in) // Constants extracted directly from the C code let x = abs_in - 5.35862651e-04; let x2 = x * x; // Fused Multiply-Add: fmaf(a, b, c) becomes a.mul_add(b, c) let even1 = x.mul_add(-9.12795913e-01, -2.88143143e-02); let even2 = x2.mul_add(-7.29192910e-01, even1); let odd1 = x.mul_add(1.06133172e+00, 1.40194533e+00); let odd2 = x2.mul_add(2.07758287e-01, odd1); // `__builtin_assume(x >= 0);` // This is a compiler hint in C. In Rust, for `x.sqrt()`, the compiler will // generally assume valid inputs or perform checks. Given the condition // `abs_in > 0.0031308` (which implies x > 0.00259...) for this branch, // x is guaranteed to be non-negative, so no direct equivalent is needed. let poly = odd2.mul_add(x.sqrt(), even2); // fmaf(odd2, sqrtf(x), even2) let lin = abs_in * 12.92; // Ternary operator: `condition ? value_if_true : value_if_false` // becomes `if condition { value_if_true } else { value_if_false }` let z = if abs_in > 0.0031308 { poly } else { lin }; z.copysign(input) // copysignf(z, in) } /// Processes a vector of float values, converting each to sRGB. /// Corresponds to `void to_srgb_vec(float *restrict dst, float *restrict src, size_t n)` /// /// `dst`: A mutable slice where the sRGB converted values will be stored. /// `src`: An immutable slice from which the linear RGB values are read. /// /// Panics if `dst` and `src` slices have different lengths, as the C code /// implicitly assumes they are large enough for `n` elements and that `n` /// corresponds to the number of elements to process in both arrays. pub fn to_srgb_vec(dst: &mut [f32], src: &[f32]) { // In C, `size_t n` indicates the number of elements to process. // In Rust, we typically use slice lengths for this. // Ensure slices have compatible lengths. assert_eq!(dst.len(), src.len(), "Destination and source slices must have the same length."); let n_initial = dst.len(); // Equivalent to the initial 'n' in the C function parameter // The C loop: `for (; n--; ++src, ++dst)` // This means `n` counts down from `n_initial` to `1` (inclusive, *before* decrement), // and `n` inside the loop (after decrement) goes from `n_initial - 1` down to `0`. // The loop runs `n_initial` times. for i in 0..n_initial { // Apply the sRGB conversion dst[i] = to_srgb(src[i]); // The peculiar C condition: `if ((n & 3) == 3)` // Here, `n` refers to the loop counter *after* it's been decremented. // For the i-th iteration (0-indexed), the C loop's `n` would be `n_initial - 1 - i`. if ((n_initial - 1 - i) & 3) == 3 { // This condition is unusual: it overwrites the sRGB converted value // with the original linear value for every 4th element from the end // (specifically, when `n` (the C-style decremented counter) is 3, 7, 11, ...). dst[i] = src[i]; } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_to_srgb_known_values() { // Test values (approximate expected sRGB based on common functions) // These will be slightly off due to the specific polynomial coefficients used. // Also, `fmaf` usage in C makes exact bit-for-bit comparison hard without // knowing compiler/platform specifics. assert_eq!(to_srgb(0.0), 0.0); assert_eq!(to_srgb(1.0), 1.0); // Assuming 1.0 maps to 1.0 assert_eq!(to_srgb(0.0031308), 0.040449997); // Transition point, linear part // Example with arbitrary value in the non-linear range // From https://en.wikipedia.org/wiki/SRGB: linear 0.18 -> sRGB ~0.4613 // With the specific poly, it's slightly different. let lin_val = 0.18f32; let abs_val = lin_val.abs(); let x = abs_val - 5.35862651e-04; let x2 = x * x; let even1 = x.mul_add(-9.12795913e-01, -2.88143143e-02); let even2 = x2.mul_add(-7.29192910e-01, even1); let odd1 = x.mul_add(1.06133172e+00, 1.40194533e+00); let odd2 = x2.mul_add(2.07758287e-01, odd1); let poly = odd2.mul_add(x.sqrt(), even2); assert_eq!(to_srgb(lin_val), poly); // Should use the poly path for 0.18 // Test negative input (should preserve sign) assert_eq!(to_srgb(-0.5), -to_srgb(0.5)); } #[test] fn test_to_srgb_vec() { let src = vec![0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]; let mut dst = vec![0.0; src.len()]; to_srgb_vec(&mut dst, &src); // Expected results considering the odd `if ((n & 3) == 3)` condition. // Let N_initial = src.len() = 11. // Loop i from 0 to 10. // C's `n` after decrement is `N_initial - 1 - i`. // // i=0: src[0]=0.0. `n` = 10. (10&3) != 3. dst[0] = to_srgb(0.0) // i=1: src[1]=0.1. `n` = 9. (9&3) != 3. dst[1] = to_srgb(0.1) // i=2: src[2]=0.2. `n` = 8. (8&3) != 3. dst[2] = to_srgb(0.2) // i=3: src[3]=0.3. `n` = 7. (7&3) == 3. dst[3] = 0.3 (overwrite) // i=4: src[4]=0.4. `n` = 6. (6&3) != 3. dst[4] = to_srgb(0.4) // i=5: src[5]=0.5. `n` = 5. (5&3) != 3. dst[5] = to_srgb(0.5) // i=6: src[6]=0.6. `n` = 4. (4&3) != 3. dst[6] = to_srgb(0.6) // i=7: src[7]=0.7. `n` = 3. (3&3) == 3. dst[7] = 0.7 (overwrite) // i=8: src[8]=0.8. `n` = 2. (2&3) != 3. dst[8] = to_srgb(0.8) // i=9: src[9]=0.9. `n` = 1. (1&3) != 3. dst[9] = to_srgb(0.9) // i=10: src[10]=1.0. `n` = 0. (0&3) != 3. dst[10] = to_srgb(1.0) // Verify elements that should be overwritten assert_eq!(dst[3], src[3]); // 0.3 assert_eq!(dst[7], src[7]); // 0.7 // Verify other elements that should be converted assert_eq!(dst[0], to_srgb(src[0])); assert_eq!(dst[1], to_srgb(src[1])); assert_eq!(dst[2], to_srgb(src[2])); assert_eq!(dst[4], to_srgb(src[4])); assert_eq!(dst[5], to_srgb(src[5])); assert_eq!(dst[6], to_srgb(src[6])); assert_eq!(dst[8], to_srgb(src[8])); assert_eq!(dst[9], to_srgb(src[9])); assert_eq!(dst[10], to_srgb(src[10])); } #[test] #[should_panic(expected = "Destination and source slices must have the same length.")] fn test_to_srgb_vec_panic_on_len_mismatch() { let src = vec![0.0, 0.1]; let mut dst = vec![0.0; 3]; to_srgb_vec(&mut dst, &src); } }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.