【学Rust写CAD】20 平铺模式结构体(spread.rs)

这个 Spread。rs文件定义了渐变超出定义区域时的扩展方式,通常用于处理渐变在边界之外的行为。

源码

rust 复制代码
//color/spread.rs
#[derive(Debug, Clone, Copy)]
pub struct Pad;  // 空结构体,表示 Pad 模式

#[derive(Debug, Clone, Copy)]
pub struct Reflect;  // 空结构体,表示 Reflect 模式

#[derive(Debug, Clone, Copy)]
pub struct Repeat;  // 空结构体,表示 Repeat 模式

trait Spread {
    fn apply(&self, x: i32) -> i32;
}

impl Spread for Pad {
    fn apply(&self, x: i32) -> i32 {
        if x > 255 {
            255
        } else if x < 0 {
            0
        } else {
            x
        }
    }
}

impl Spread for Repeat {
    fn apply(&self, x: i32) -> i32 {
        x & 255
    }
}

impl Spread for Reflect {
    fn apply(&self, x: i32) -> i32 {
        let sign = (x << 23) >> 31;
        (x ^ sign) & 255
    }
}

代码分析

这段代码定义了几种不同的颜色值处理模式,用于处理超出标准RGB范围(0-255)的数值。

主要组成部分

  1. 模式定义
    定义了三个空结构体,分别表示不同的处理模式:
rust 复制代码
pub struct Pad;     // Pad模式
pub struct Reflect; // Reflect模式
pub struct Repeat;  // Repeat模式

这些结构体都是空结构体(零大小类型),仅用作标记类型(tag types)来实现不同的行为。

  1. Spread trait
    定义了一个trait Spread,它有一个方法apply,接受一个i32参数并返回处理后的i32值:
rust 复制代码
trait Spread {
    fn apply(&self, x: i32) -> i32;
}
  1. 不同模式的实现
Pad模式
rust 复制代码
impl Spread for Pad {
    fn apply(&self, x: i32) -> i32 {
        if x > 255 {
            255
        } else if x < 0 {
            0
        } else {
            x
        }
    }
}
  • 将超出范围的值截断到边界

  • x > 255 → 返回255

  • x < 0 → 返回0

  • 否则返回原值

Repeat模式
rust 复制代码
impl Spread for Repeat {
    fn apply(&self, x: i32) -> i32 {
        x & 255
    }
}
  • 使用位运算实现模256的效果

  • 相当于x % 256,但效率更高

  • 例如:256 → 0, 257 → 1, -1 → 255

Reflect模式
rust 复制代码
impl Spread for Reflect {
    fn apply(&self, x: i32) -> i32 {
        let sign = (x << 23) >> 31;
        (x ^ sign) & 255
    }
}
  • 实现类似"反射"边界的效果

  • 当x超出范围时,会像镜子一样反射回来

  • 例如:256 → 255, 257 → 254, -1 → 0, -2 → 1

  • 使用位运算技巧高效实现:

    • sign计算x的符号位(0表示正,-1表示负)

    • x ^ sign相当于x取反(当x为负时)

    • 最后& 255确保在0-255范围内

使用场景

这段代码可能用于图像处理中,当颜色值计算超出标准范围时,提供不同的处理策略:

  • Pad: 简单截断,保持颜色在有效范围内

  • Repeat: 循环处理,适合某些纹理或模式重复的场景

  • Reflect: 镜像反射处理,可以创建更平滑的过渡效果

这些模式的选择会影响图像处理边缘效果或颜色溢出的处理方式。

相关推荐
superman超哥20 小时前
Serde 性能优化的终极武器
开发语言·rust·编程语言·rust serde·serde性能优化·rust开发工具
sayang_shao1 天前
Rust多线程编程学习笔记
笔记·学习·rust
鸿乃江边鸟1 天前
Spark Datafusion Comet 向量化Rust Native--读数据
rust·spark·native·arrow
硬汉嵌入式1 天前
基于Rust构建的单片机Ariel RTOS,支持Cortex-M、RISC-V 和 Xtensa
单片机·rust·risc-v
低调滴开发2 天前
Tauri开发桌面端服务,配置指定防火墙端口
rust·tauri·桌面端·windows防火墙规则
咚为2 天前
Rust Cell使用与原理
开发语言·网络·rust
咸甜适中3 天前
rust的docx-rs库,自定义docx模版批量生成docx文档(逐行注释)
开发语言·rust·docx·docx-rs
FAFU_kyp3 天前
RISC0_ZERO项目在macOs上生成链上证明避坑
开发语言·后端·学习·macos·rust
古城小栈3 天前
开发常用 宏
算法·rust
咸甜适中3 天前
rust的docx-rs库读取docx文件中的文本内容(逐行注释)
开发语言·rust·docx·docx-rs