Skip to main content

kasl_ir/value/
offset.rs

1//
2//  Copyright 2025-2026 Shuntaro Kasatani
3//
4//  Licensed under the Apache License, Version 2.0 (the "License");
5//  you may not use this file except in compliance with the License.
6//  You may obtain a copy of the License at
7//
8//      http://www.apache.org/licenses/LICENSE-2.0
9//
10//  Unless required by applicable law or agreed to in writing, software
11//  distributed under the License is distributed on an "AS IS" BASIS,
12//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13//  See the License for the specific language governing permissions and
14//  limitations under the License.
15//
16
17use std::fmt::Display;
18
19/// An offset used in memory access instructions.
20#[derive(Clone, PartialEq, Eq, Hash)]
21pub enum Offset {
22    /// Physical byte count.
23    Immediate(u32),
24    /// Pointer size, mutiplied by the given factor.
25    PointerScaled(u32),
26}
27
28impl Offset {
29    /// Returns a new offset with the immediate value of zero.
30    pub fn zero() -> Self {
31        Offset::Immediate(0)
32    }
33}
34
35/// A trait to resolve an `Offset` to an actual byte offset, given the pointer size of the target architecture.
36pub trait ResolveOffset {
37    fn resolve(&self, ptr_size: u32) -> u32;
38}
39
40impl ResolveOffset for Offset {
41    fn resolve(&self, ptr_size: u32) -> u32 {
42        match self {
43            Offset::Immediate(n) => *n,
44            Offset::PointerScaled(n) => *n * ptr_size,
45        }
46    }
47}
48
49impl Display for Offset {
50    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51        match self {
52            Offset::Immediate(offset) => write!(f, "{}", offset),
53            Offset::PointerScaled(scale) => write!(f, "ptr*{}", scale),
54        }
55    }
56}