rust-samp-sdk 3.4.0

Low-level FFI bindings for the SA-MP AMX virtual machine and open.mp native component ABI. Used internally by `rust-samp`; depend on it directly only if you need raw access without the higher-level macros and lifecycle.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
//! Safe API for a live AMX VM instance.
//!
//! Wraps the `*mut AMX` received from the server + the `amx_Exports` table.
//! Each method here resolves the corresponding `amx_*` function on demand (via
//! [`crate::exports`]) and invokes it with idiomatic Rust error handling.

use crate::cell::{AmxCell, AmxPrimitive, AmxString, Buffer, Ref};
use crate::consts::{AmxExecIdx, AmxFlags};
use crate::error::{AmxError, AmxResult};
// Intentional wildcard: brings in the 40+ marker types of the exported AMX
// functions (`Register`, `Allot`, `Exec`, ...). Listing each one would be
// noisy and fragile when a new function is added to the table.
#[allow(clippy::wildcard_imports)]
use crate::exports::*;
use crate::raw::functions::AmxNative;
use crate::raw::types::{AMX, AMX_HEADER, AMX_NATIVE_INFO};

#[cfg(feature = "encoding")]
use crate::encoding;

use std::borrow::Cow;
use std::ffi::CString;
use std::ptr::NonNull;

macro_rules! amx_try {
    ($call:expr) => {
        let result = $call;

        if result > 0 {
            return Err(result.into());
        }
    };
}

/// Reads a field of the `#[repr(C, packed)]` `AMX` via `read_unaligned` (taking
/// a reference to a packed field is unsound). `None` when the pointer is null.
macro_rules! read_reg {
    ($self:ident . $field:ident) => {
        NonNull::new($self.ptr)
            .map(|amx| unsafe { std::ptr::addr_of!((*amx.as_ptr()).$field).read_unaligned() })
    };
}

/// Wrapper over the raw `*mut AMX` and the exported function table.
#[derive(Debug)]
pub struct Amx {
    ptr: *mut AMX,
    fn_table: usize,
}

impl Amx {
    /// Builds the wrapper.
    ///
    /// `ptr` is the pointer received in callbacks such as `AmxLoad`; `fn_table`
    /// is the address resolved during plugin initialization (typically stored
    /// in a global [`AtomicUsize`] read in `Load()` from
    /// [`crate::consts::ServerData::AmxExports`]).
    ///
    /// [`AtomicUsize`]: std::sync::atomic::AtomicUsize
    pub fn new(ptr: *mut AMX, fn_table: usize) -> Amx {
        Amx { ptr, fn_table }
    }

    /// Wraps a VM for **data-side access only**, with no function table.
    ///
    /// The register accessors and `read_cell`/`write_cell`/`read_cells`/
    /// `read_bytes`/`read_code` resolve addresses straight from the `AMX`
    /// struct, so they need no exported function table. Anything that calls
    /// into the VM (`register`, `exec`, `get_ref`, `allot`…) does, and will
    /// fail on an `Amx` built here.
    ///
    /// Meant for a debug hook or a paused VM, where a plugin holds the pointer
    /// but has no native call context — it states that intent instead of
    /// passing a bare `0` as the function table.
    #[must_use]
    pub fn data_only(ptr: *mut AMX) -> Amx {
        Amx { ptr, fn_table: 0 }
    }

    /// Registers plugin natives in the VM via `amx_Register`.
    ///
    /// Generally called in `AmxLoad` — the `#[native]` macro + `initialize_plugin!`
    /// build the list automatically; only call manually from `raw` code.
    ///
    /// # Errors
    /// Propagates any [`AmxError`] returned by `amx_Register` — typically
    /// `AmxError::NotFound` if a listed native is not declared in the script,
    /// or VM state errors if called outside the load cycle.
    pub fn register(&self, natives: &[AMX_NATIVE_INFO]) -> AmxResult<()> {
        let register = Register::from_table(self.fn_table);
        // `usize` -> `i32`: the `amx_Register` ABI takes the count as `int`.
        // Practical truncation would require >2 billion natives — impossible.
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let len = natives.len() as i32;
        let ptr = natives.as_ptr();

        amx_try!(register(self.ptr, ptr, len));

        Ok(())
    }

    pub(crate) fn allot<T: Sized + AmxPrimitive>(&self, cells: usize) -> AmxResult<Ref<'_, T>> {
        if cells > i32::MAX as usize {
            return Err(AmxError::Memory);
        }

        let allot = Allot::from_table(self.fn_table);

        let mut amx_addr = 0;
        let mut phys_addr = 0;

        // `cells` was validated above as `<= i32::MAX`; cast is safe.
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let cells_i32 = cells as i32;
        amx_try!(allot(
            self.ptr,
            cells_i32,
            &raw mut amx_addr,
            &raw mut phys_addr
        ));

        if phys_addr == 0 {
            return Err(AmxError::Memory);
        }

        unsafe { Ok(Ref::new(amx_addr, phys_addr as *mut T)) }
    }

    /// Executes the public function identified by `index` in the VM.
    ///
    /// Returns the Pawn return value (`i32`). Arguments must have been pushed
    /// via [`push`] (in reverse order) and [`Allocator`] (for strings/arrays)
    /// before this call.
    ///
    /// [`push`]: Amx::push
    ///
    /// # Errors
    /// Propagates any [`AmxError`] from script execution — notably
    /// `Exit`/`Assert` (Pawn aborted), `StackError`/`StackLow`/`HeapLow`
    /// (stack or heap overflow), `Divide`, `Native` (a called native
    /// returned an error) or `Index` if `index` does not match a valid function.
    pub fn exec(&self, index: AmxExecIdx) -> AmxResult<i32> {
        let exec = Exec::from_table(self.fn_table);
        let mut retval = 0;

        amx_try!(exec(self.ptr, &raw mut retval, index.into()));

        Ok(retval)
    }

    /// Calls a public inside a managed [`Allocator`] scope — the escape hatch for
    /// callbacks with **output arrays**, which the input-only [`exec_public!`]
    /// macro cannot express.
    ///
    /// Resolves `name` to its public index and opens an [`Allocator`], then hands
    /// both to `body`. Inside, allocate input/output buffers, [`push`] the
    /// arguments (in reverse order), call [`exec`], and read any output buffers
    /// back — all before the scope closes and frees the heap. The scope also
    /// rewinds the VM stack, so a mid-sequence `push` failure cannot unbalance it.
    ///
    /// [`exec_public!`]: crate::exec_public
    /// [`push`]: Amx::push
    /// [`exec`]: Amx::exec
    ///
    /// # Errors
    /// `AmxError::NotFound` if the public does not exist; otherwise whatever
    /// `body` returns (typically propagated from `push`/`exec`).
    ///
    /// # Example
    /// ```rust,no_run
    /// # use samp_sdk::amx::Amx;
    /// # use samp_sdk::error::AmxResult;
    /// # fn demo(amx: &Amx) -> AmxResult<Vec<i32>> {
    /// // Pawn: forward FillSquares(out[], size);
    /// let squares = amx.exec_public_scope("FillSquares", |alloc, idx| {
    ///     let buf = alloc.allot_buffer(8)?; // output array
    ///     amx.push(8)?;                      // size   (pushed first = last arg)
    ///     amx.push(&buf)?;                   // out[]  (pushed last  = first arg)
    ///     amx.exec(idx)?;
    ///     Ok(buf.as_slice().to_vec())        // read the array back before it frees
    /// })?;
    /// # Ok(squares)
    /// # }
    /// ```
    pub fn exec_public_scope<F, R>(&self, name: &str, body: F) -> AmxResult<R>
    where
        F: FnOnce(&Allocator<'_>, AmxExecIdx) -> AmxResult<R>,
    {
        let index = self.find_public(name)?;
        let allocator = self.allocator();
        body(&allocator, index)
    }

    /// Index of a native by name (resolved via `amx_FindNative`).
    ///
    /// # Errors
    /// `AmxError::NotFound` if `name` contains an interior NUL byte or if the
    /// native is not registered in the VM.
    pub fn find_native(&self, name: &str) -> AmxResult<i32> {
        let find_native = FindNative::from_table(self.fn_table);
        let c_str = CString::new(name).map_err(|_| AmxError::NotFound)?;
        let mut index = -1;

        amx_try!(find_native(self.ptr, c_str.as_ptr(), &raw mut index));

        Ok(index)
    }

    /// Calls a native registered by **another plugin** in the same AMX.
    ///
    /// SA-MP plugins inject their natives into every loaded AMX via
    /// `amx_Register`, which writes a host function pointer into the
    /// native's entry inside the `AMX_HEADER` natives table. This helper
    /// resolves the name through `amx_FindNative`, reads that function
    /// pointer back, builds the `params` block in the AMX convention
    /// (first cell = `argc * sizeof(cell)`, then the arguments), and
    /// invokes the native.
    ///
    /// Integer arguments are passed as their `i32` value. Floats are
    /// passed bit-cast to `i32` (use [`f32::to_bits`] then
    /// [`i32::from_ne_bytes`] on `to_ne_bytes`, or `f32::to_bits() as i32`).
    /// String and array arguments are AMX cell addresses returned by
    /// [`Allocator::allot_string`]/[`Allocator::allot_buffer`] — same
    /// marshalling as for [`exec_public`](crate::exec_public).
    ///
    /// # Example
    /// ```rust,ignore
    /// // Calling Streamer_CreateDynamicObject from a Rust plugin
    /// fn on_amx_load(&mut self, amx: &Amx) -> AmxResult<()> {
    ///     let model_id: i32 = 1337;
    ///     #[allow(clippy::cast_possible_wrap)]
    ///     let x = 100.0_f32.to_bits() as i32;
    ///     let y = 200.0_f32.to_bits() as i32;
    ///     let z =  10.0_f32.to_bits() as i32;
    ///     let object_id = amx.call_native(
    ///         "Streamer_CreateDynamicObject",
    ///         &[model_id, x, y, z, 0, 0, 0],
    ///     )?;
    ///     log::info!("created dynamic object id={object_id}");
    ///     Ok(())
    /// }
    /// ```
    ///
    /// # Errors
    /// - [`AmxError::NotFound`] if `name` contains an interior NUL byte,
    ///   the native is not registered, or its address is still zero
    ///   (registered name but no host pointer attached).
    /// - [`AmxError::MemoryAccess`] if the AMX header cannot be read.
    /// - [`AmxError::Index`] if the resolved index is out of range for
    ///   the natives table reported by the AMX header.
    /// - Any [`AmxError`] propagated from the called native via
    ///   `amx.error` (re-raised by the caller through `amx_try!`).
    pub fn call_native(&self, name: &str, params: &[i32]) -> AmxResult<i32> {
        let index = self.find_native(name)?;
        if index < 0 {
            return Err(AmxError::NotFound);
        }

        let header_ptr = self.header().ok_or(AmxError::MemoryAccess)?;
        // SAFETY: `header()` returned NonNull, and the AMX is alive for
        // the duration of `&self`.
        let (natives_off, libraries_off, defsize) = unsafe {
            let h = header_ptr.as_ptr();
            (
                std::ptr::read_unaligned(&raw const (*h).natives),
                std::ptr::read_unaligned(&raw const (*h).libraries),
                std::ptr::read_unaligned(&raw const (*h).defsize),
            )
        };

        if defsize <= 0 || libraries_off < natives_off {
            return Err(AmxError::MemoryAccess);
        }
        let defsize_i32 = i32::from(defsize);
        let table_bytes = libraries_off - natives_off;
        let num_natives = table_bytes / defsize_i32;
        if index >= num_natives {
            return Err(AmxError::Index);
        }

        let amx_ptr = self.amx().ok_or(AmxError::MemoryAccess)?;
        // SAFETY: `amx_ptr` is NonNull and points to the live AMX.
        let base = unsafe { (*amx_ptr.as_ptr()).base };
        if base.is_null() {
            return Err(AmxError::MemoryAccess);
        }

        let entry_off = natives_off + index * defsize_i32;
        // SAFETY: `entry_off` is within the natives table bounded by
        // (libraries - natives), which the header advertises as part of
        // the AMX-mapped region pointed to by `base`.
        let entry_ptr = unsafe { base.offset(entry_off as isize) };

        // First 4 bytes of each entry — both `AMX_FUNCSTUB` and
        // `ANX_FUNCSTUBNT` start with `u32 address`, the host function
        // pointer written by `amx_Register`.
        let address = unsafe { std::ptr::read_unaligned(entry_ptr.cast::<u32>()) };
        if address == 0 {
            return Err(AmxError::NotFound);
        }

        // SAFETY: SA-MP / open.mp are 32-bit; the AMX cell width and host
        // function pointer width are both 4 bytes. `address` came from
        // `amx_Register`, which writes a valid `AmxNative` pointer.
        let native: AmxNative = unsafe { std::mem::transmute(address as usize) };

        // Build the params block: `[argc * sizeof(cell), arg0, arg1, ...]`.
        // Bytes, not cells — matches the convention every AMX native
        // implementation reads (`params[0] / sizeof(cell)` to recover argc).
        let mut buf: Vec<i32> = Vec::with_capacity(params.len() + 1);
        // `params.len()` bounded by `i32::MAX` in practice; the AMX
        // would have failed long before reaching 2 billion args.
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let argc_bytes = (params.len() as i32) * 4;
        buf.push(argc_bytes);
        buf.extend_from_slice(params);

        let retval = native(self.ptr, buf.as_mut_ptr());
        // Surface VM-side errors set by the native into `amx.error`.
        // SAFETY: `amx_ptr` already validated above.
        let err = unsafe { (*amx_ptr.as_ptr()).error };
        if err > 0 {
            return Err(err.into());
        }
        Ok(retval)
    }

    /// Index of a public function by name — pass the result to [`exec`].
    ///
    /// ```
    /// use samp_sdk::amx::Amx;
    /// use samp_sdk::error::AmxResult;
    /// fn has_on_player_connect(amx: &Amx) -> AmxResult<bool> {
    ///     let idx = amx.find_public("OnPlayerConnect")?;
    ///     Ok(i32::from(idx) >= 0)
    /// }
    /// ```
    ///
    /// [`exec`]: Amx::exec
    ///
    /// # Errors
    /// `AmxError::NotFound` if `name` contains an interior NUL byte or if the
    /// public function is not declared in the Pawn script.
    pub fn find_public(&self, name: &str) -> AmxResult<AmxExecIdx> {
        let find_public = FindPublic::from_table(self.fn_table);
        let c_str = CString::new(name).map_err(|_| AmxError::NotFound)?;
        let mut index = -1;

        amx_try!(find_public(self.ptr, c_str.as_ptr(), &raw mut index));

        Ok(AmxExecIdx::from(index))
    }

    /// `Ref<T>` pointing to a public variable declared in the Pawn script.
    ///
    /// ```rust,no_run
    /// # use samp_sdk::amx::Amx;
    /// # use samp_sdk::error::AmxResult;
    /// # fn check(amx: &Amx) -> AmxResult<()> {
    /// let version = amx.find_pubvar::<f32>("my_plugin_version")?;
    /// // outdated
    /// if *version < 1.0 { }
    /// # Ok(()) }
    /// ```
    ///
    /// # Errors
    /// `AmxError::NotFound` if `name` contains an interior NUL byte or if the
    /// pubvar is not declared. `AmxError::MemoryAccess` if the address returned
    /// by the VM is invalid.
    pub fn find_pubvar<T: Sized + AmxPrimitive>(&self, name: &str) -> AmxResult<Ref<'_, T>> {
        let find_pubvar = FindPubVar::from_table(self.fn_table);
        let c_str = CString::new(name).map_err(|_| AmxError::NotFound)?;
        let mut cell_ptr = 0;

        amx_try!(find_pubvar(self.ptr, c_str.as_ptr(), &raw mut cell_ptr));

        self.get_ref(cell_ptr)
    }

    /// Flags of the loaded `.amx`.
    ///
    /// # Errors
    /// Propagates any [`AmxError`] returned by `amx_Flags` — in practice, it
    /// only fails if the internal `AMX*` is corrupted or null.
    pub fn flags(&self) -> AmxResult<AmxFlags> {
        let flags = Flags::from_table(self.fn_table);
        let mut value: u16 = 0;

        amx_try!(flags(self.ptr, &raw mut value));

        Ok(AmxFlags::from_bits_truncate(value))
    }

    /// Returns the VM's opcode dispatch table (`amx_opcodelist`): `count` raw
    /// label addresses, one per opcode, in opcode order.
    ///
    /// On a server built with computed-goto threading (GCC/Clang, the SA-MP and
    /// open.mp builds), the loader rewrites each opcode in the code segment to the
    /// *address* of its handler label, so a byte read with [`read_code`] yields a
    /// pointer, not the opcode number. Inverting this table (address → opcode)
    /// lets a debugger recover the real opcode at `cip`. The table is fetched the
    /// way the loader itself does it — set the `BROWSE` flag and call `amx_Exec`
    /// with index `0`, which returns `&amx_opcodelist` instead of running code.
    ///
    /// `count` is the number of opcodes the caller expects (`OP_NUM_OPCODES`);
    /// the SDK does not hardcode the VM's opcode count. Returns `None` only when
    /// the table cannot be obtained (null VM/table).
    ///
    /// The `AMX_FLAG_RELOC` header bit is intentionally **not** consulted: it is
    /// set by the loader in the file header and may not yet be visible at
    /// `AmxLoad` time, even though the dispatch table is already available. A
    /// non-computed-goto VM would return a table whose addresses simply never
    /// match a real opcode, so inverting it is harmless (the consumer finds no
    /// match and treats the code value as a raw opcode).
    ///
    /// [`read_code`]: Self::read_code
    pub fn opcode_table(&self, count: usize) -> Option<Vec<usize>> {
        let amx = NonNull::new(self.ptr)?.as_ptr();

        // Toggle the BROWSE flag so `amx_Exec(.., 0)` returns the label table
        // instead of executing. Restore the previous flags afterwards.
        let saved = unsafe { std::ptr::addr_of!((*amx).flags).read_unaligned() };
        unsafe {
            std::ptr::addr_of_mut!((*amx).flags)
                .write_unaligned(saved | i32::from(AmxFlags::BROWSE.bits()));
        }
        let exec = Exec::from_table(self.fn_table);
        // `retval` receives `(cell)amx_opcodelist` — a pointer to the table. On the
        // 32-bit SA-MP/open.mp VMs `cell` and `void*` are both 32-bit (the VM
        // asserts `sizeof(cell)==sizeof(void*)`), so it round-trips through i32.
        let mut retval: i32 = 0;
        let _ = exec(self.ptr, &raw mut retval, 0);
        unsafe {
            std::ptr::addr_of_mut!((*amx).flags).write_unaligned(saved);
        }

        let table = usize::try_from(retval.cast_unsigned()).ok()? as *const usize;
        if table.is_null() {
            return None;
        }
        // Read `count` pointer-sized entries from the table.
        let mut out = Vec::with_capacity(count);
        for i in 0..count {
            out.push(unsafe { table.add(i).read_unaligned() });
        }
        Some(out)
    }

    /// Resolves an AMX cell (relative address) to a typed [`Ref<T>`].
    ///
    /// # Errors
    /// `AmxError::MemoryAccess` if `address` does not correspond to a valid
    /// cell in the Pawn script address space.
    pub fn get_ref<T: Sized + AmxPrimitive>(&self, address: i32) -> AmxResult<Ref<'_, T>> {
        let get_addr = GetAddr::from_table(self.fn_table);
        let mut dest = 0;
        let mut dest_addr = std::ptr::addr_of_mut!(dest);

        amx_try!(get_addr(self.ptr, address, &raw mut dest_addr));

        if dest_addr.is_null() {
            return Err(AmxError::MemoryAccess);
        }

        unsafe { Ok(Ref::new(address, dest_addr.cast::<T>())) }
    }

    /// Rewinds the VM heap and stack to the values captured when an
    /// [`Allocator`] scope opened, freeing everything it allocated **and**
    /// pushed in one shot.
    ///
    /// - `hea`: restores the heap top (frees `allot*` buffers).
    /// - `stk`: restores the stack top. The stack grows downward, so this only
    ///   rewinds when the current `stk` sits *below* the captured value (i.e.
    ///   something was pushed and not yet consumed) — the corrective path for a
    ///   `push` sequence that failed part-way through `exec_public!`. A balanced
    ///   `exec` leaves `stk` back at the captured value, making this a no-op.
    #[inline]
    pub(crate) fn release_scope(&self, hea: i32, stk: i32) {
        if let Some(mut amx) = self.amx() {
            let amx = unsafe { amx.as_mut() };
            if hea >= 0 && amx.hea > hea {
                amx.hea = hea;
            }
            if stk >= 0 && stk <= amx.stp && amx.stk < stk {
                amx.stk = stk;
            }
        }
    }

    /// Pushes an `AmxCell` value onto the VM stack. Use **in reverse order**
    /// of the public function's arguments before calling [`exec`].
    ///
    /// [`exec`]: Amx::exec
    ///
    /// # Errors
    /// Propagates any [`AmxError`] from `amx_Push` — typically
    /// `AmxError::StackError`/`StackLow` if the stack is full.
    pub fn push<'a, T: AmxCell<'a>>(&'a self, value: T) -> AmxResult<()> {
        let push = Push::from_table(self.fn_table);

        amx_try!(push(self.ptr, value.as_cell()));

        Ok(())
    }

    /// Length in characters of an AMX string at address `value`.
    ///
    /// # Errors
    /// `AmxError::MemoryAccess` if `value` does not point to valid memory in
    /// the script space. Other [`AmxError`] are propagated from `amx_StrLen`.
    pub fn strlen(&self, value: *const i32) -> AmxResult<usize> {
        let strlen = StrLen::from_table(self.fn_table);
        let mut len = 0;
        amx_try!(strlen(value, &raw mut len));
        // `len` returned by `amx_StrLen` is always >= 0 (a negative value
        // would become an error via `amx_try!`).
        #[allow(clippy::cast_sign_loss)]
        Ok(len as usize)
    }

    /// Creates an [`Allocator`] bound to this `Amx`.
    ///
    /// All memory allocated via [`Allocator::allot`]/[`Allocator::allot_buffer`]/
    /// [`Allocator::allot_string`] is released automatically when the
    /// `Allocator` goes out of scope (`Drop`). Keep it alive while using the
    /// returned references.
    #[must_use]
    pub fn allocator(&self) -> Allocator<'_> {
        Allocator::new(self)
    }

    /// Raw pointer to the `AMX` (non-null) or `None` if constructed with null.
    #[must_use]
    pub fn amx(&self) -> Option<NonNull<AMX>> {
        NonNull::new(self.ptr)
    }

    /// Raw pointer to the `AMX_HEADER` of the loaded `.amx`.
    #[must_use]
    pub fn header(&self) -> Option<NonNull<AMX_HEADER>> {
        let amx = NonNull::new(self.ptr)?;
        NonNull::new(unsafe { (*amx.as_ptr()).base.cast::<AMX_HEADER>() })
    }

    // ---- VM register accessors (all `None` when the pointer is null) ----

    /// Current instruction pointer (`cip`) — a code-segment offset in a debug
    /// hook. Read as `u32`.
    #[must_use]
    pub fn cip(&self) -> Option<u32> {
        read_reg!(self.cip).map(i32::cast_unsigned)
    }

    /// Current frame pointer (`frm`); local/argument symbols are addressed
    /// relative to it.
    #[must_use]
    pub fn frame(&self) -> Option<i32> {
        read_reg!(self.frm)
    }

    /// Current stack pointer (`stk`).
    #[must_use]
    pub fn stack(&self) -> Option<i32> {
        read_reg!(self.stk)
    }

    /// Current heap pointer (`hea`).
    #[must_use]
    pub fn heap(&self) -> Option<i32> {
        read_reg!(self.hea)
    }

    /// Top of the stack (`stp`) — the upper bound of the data address space.
    #[must_use]
    pub fn stp(&self) -> Option<i32> {
        read_reg!(self.stp)
    }

    /// Heap low-water mark (`hlw`) — the bottom of the heap segment. The heap
    /// grows upward from here; releasing it below `hlw` is what the VM reports as
    /// `AMX_ERR_HEAPLOW`. A debugger reads it in a debug hook to detect a heap
    /// underflow before the VM aborts.
    #[must_use]
    pub fn hlw(&self) -> Option<i32> {
        read_reg!(self.hlw)
    }

    /// Primary register (`pri`) — the VM's main accumulator. In a debug hook it
    /// holds the operand the next instruction will act on; e.g. for `OP_BOUNDS`
    /// it is the index being range-checked.
    #[must_use]
    pub fn pri(&self) -> Option<i32> {
        read_reg!(self.pri)
    }

    /// Alternate register (`alt`) — the VM's secondary accumulator. For the
    /// division opcodes (`OP_DIV`/`OP_SDIV`) it holds the divisor, so reading it
    /// in a debug hook lets a debugger detect a divide-by-zero before it aborts.
    #[must_use]
    pub fn alt(&self) -> Option<i32> {
        read_reg!(self.alt)
    }

    /// Reads a 32-bit cell from the **code** segment at `offset` (a code-segment
    /// offset, like `cip`). Returns `None` when the VM pointer is null or the
    /// offset is outside the code segment `[0, header.dat - header.cod)`.
    ///
    /// The code segment is read-only and laid out as `base + header.cod`; this is
    /// the counterpart of [`read_cell`](Self::read_cell) for instructions. A
    /// debugger uses it to decode the opcode at `cip` inside a debug hook (e.g. to
    /// catch a runtime error before the VM aborts). Reads byte-wise (no alignment
    /// assumption), since the `AMX_HEADER` is packed.
    #[must_use]
    pub fn read_code(&self, offset: u32) -> Option<i32> {
        let amx = NonNull::new(self.ptr)?.as_ptr();
        let base = unsafe { std::ptr::addr_of!((*amx).base).read_unaligned() };
        if base.is_null() {
            return None;
        }
        let hdr = base.cast::<AMX_HEADER>();
        let cod = unsafe { std::ptr::addr_of!((*hdr).cod).read_unaligned() };
        let dat = unsafe { std::ptr::addr_of!((*hdr).dat).read_unaligned() };
        // Code segment spans `[cod, dat)`; the offset is relative to `cod`.
        let size = u32::try_from(dat - cod).ok()?;
        if offset >= size {
            return None;
        }
        let cod = usize::try_from(cod).ok()?;
        let off = usize::try_from(offset).ok()?;
        let ptr = unsafe { base.add(cod + off) };
        let mut buf = [0u8; 4];
        unsafe { std::ptr::copy_nonoverlapping(ptr, buf.as_mut_ptr(), 4) };
        Some(i32::from_ne_bytes(buf))
    }

    /// Resolves a data-segment address to a raw pointer with the same bounds
    /// checking as `amx_GetAddr`, without going through the exported function
    /// table. Returns `None` when the address falls in the free region between
    /// heap and stack, is negative, or is past the top of the stack.
    ///
    /// Unlike [`get_ref`](Self::get_ref), this works inside a debug hook, where
    /// no native call context is available. It is the building block for
    /// [`read_cell`](Self::read_cell)/[`write_cell`](Self::write_cell).
    fn data_ptr(&self, addr: i32) -> Option<*mut u8> {
        let amx = NonNull::new(self.ptr)?.as_ptr();
        let base = unsafe { std::ptr::addr_of!((*amx).base).read_unaligned() };
        if base.is_null() {
            return None;
        }
        let data_field = unsafe { std::ptr::addr_of!((*amx).data).read_unaligned() };
        let hea = unsafe { std::ptr::addr_of!((*amx).hea).read_unaligned() };
        let stk = unsafe { std::ptr::addr_of!((*amx).stk).read_unaligned() };
        let stp = unsafe { std::ptr::addr_of!((*amx).stp).read_unaligned() };

        // `data` is `amx->data` when set, otherwise `amx->base + header->dat`.
        let data = if data_field.is_null() {
            let hdr = base.cast::<AMX_HEADER>();
            let dat = unsafe { std::ptr::addr_of!((*hdr).dat).read_unaligned() };
            unsafe { base.add(usize::try_from(dat).ok()?) }
        } else {
            data_field
        };

        // Same valid region as `amx_GetAddr`: reject the active heap/stack gap
        // and anything outside `[0, stp)`.
        if (addr >= hea && addr < stk) || addr < 0 || addr >= stp {
            return None;
        }
        Some(unsafe { data.add(usize::try_from(addr).ok()?) })
    }

    /// Reads a 32-bit cell from the data segment at `addr`, validating bounds
    /// like `amx_GetAddr`. Returns `None` if the address is inaccessible.
    ///
    /// Reads byte-wise (no alignment assumption). Usable from a debug hook.
    #[must_use]
    pub fn read_cell(&self, addr: i32) -> Option<i32> {
        let ptr = self.data_ptr(addr)?;
        let mut buf = [0u8; 4];
        unsafe { std::ptr::copy_nonoverlapping(ptr, buf.as_mut_ptr(), 4) };
        Some(i32::from_ne_bytes(buf))
    }

    /// Reads up to `count` consecutive cells starting at `addr`, validating
    /// each one like [`read_cell`](Self::read_cell).
    ///
    /// Stops early and returns what it read when an address becomes
    /// inaccessible — the natural case at the end of the data segment. `None`
    /// only when `addr` itself is inaccessible.
    ///
    /// Unlike [`get_ref`](Self::get_ref)-based access (`Buffer`, `AmxString`),
    /// this needs no function table, so it works inside a debug hook.
    #[must_use]
    pub fn read_cells(&self, addr: i32, count: usize) -> Option<Vec<i32>> {
        let first = self.read_cell(addr)?;
        let mut out = Vec::with_capacity(count);
        out.push(first);
        for i in 1..count {
            let offset = i32::try_from(i.checked_mul(4)?).ok()?;
            let Some(cell) = self.read_cell(addr.checked_add(offset)?) else {
                break;
            };
            out.push(cell);
        }
        Some(out)
    }

    /// Reads up to `len` raw bytes of the data segment starting at `addr`, in
    /// the VM's native byte order — the backing read for a hex view.
    ///
    /// `addr` needs no alignment: the read starts at the enclosing cell and the
    /// leading bytes are trimmed. Like [`read_cells`](Self::read_cells), it
    /// stops early at the first inaccessible address, so the result may be
    /// shorter than `len`; `None` only when `addr` itself is inaccessible.
    #[must_use]
    pub fn read_bytes(&self, addr: i32, len: usize) -> Option<Vec<u8>> {
        let aligned = addr & !3;
        let skip = usize::try_from(addr - aligned).ok()?;
        let cells = skip.checked_add(len)?.div_ceil(4);
        let read = self.read_cells(aligned, cells)?;

        let mut bytes = Vec::with_capacity(read.len() * 4);
        for cell in read {
            bytes.extend_from_slice(&cell.to_ne_bytes());
        }
        let end = skip.checked_add(len)?.min(bytes.len());
        Some(bytes.get(skip..end).unwrap_or(&[]).to_vec())
    }

    /// Writes a 32-bit cell to the data segment at `addr`, validating bounds
    /// like `amx_GetAddr`. Returns `false` if the address is inaccessible.
    ///
    /// Writes byte-wise (no alignment assumption). Usable from a debug hook to
    /// edit a variable while the VM is paused.
    pub fn write_cell(&self, addr: i32, value: i32) -> bool {
        let Some(ptr) = self.data_ptr(addr) else {
            return false;
        };
        let buf = value.to_ne_bytes();
        unsafe { std::ptr::copy_nonoverlapping(buf.as_ptr(), ptr, 4) };
        true
    }

    /// Installs a debug hook callback into this VM (`amx->debug = cb`), the
    /// equivalent of `amx_SetDebugHook`. The VM then calls `cb` on every line,
    /// provided the `.amx` was compiled with `-d2`/`-d3`.
    ///
    /// The callback runs on the VM thread and crosses the FFI boundary, so it
    /// must never unwind (no panics).
    pub fn install_debug_hook(&self, cb: crate::raw::functions::AmxDebug) {
        if let Some(amx) = NonNull::new(self.ptr) {
            unsafe { std::ptr::addr_of_mut!((*amx.as_ptr()).debug).write_unaligned(cb) };
        }
    }

    /// Builds this VM's [`OpcodeMap`](crate::debug::OpcodeMap), to decode the
    /// raw values [`read_code`](Self::read_code) returns on a computed-goto
    /// build. Build it once per VM (typically in `on_amx_load`).
    ///
    /// A VM whose dispatch table cannot be fetched yields an identity map,
    /// which treats code values as plain opcode numbers.
    #[cfg(feature = "debug")]
    #[must_use]
    pub fn opcode_map(&self) -> crate::debug::OpcodeMap {
        crate::debug::OpcodeMap::new(self.opcode_table(crate::debug::OP_NUM_OPCODES))
    }

    /// Walks the call stack from `top_cip`, returning the `(cip, frm)` of every
    /// frame — index 0 is the top, where the VM currently is.
    ///
    /// Inside a debug hook, `top_cip` is the address of the line's `OP_BREAK`,
    /// i.e. [`cip`](Self::cip) minus one cell, since the hook is entered with
    /// the instruction pointer already past the break.
    ///
    /// See [`debug::stack::walk`](crate::debug::stack::walk) for the frame
    /// layout and the conditions that end the walk. Returns an empty vector
    /// only when the VM's registers cannot be read.
    #[cfg(feature = "debug")]
    #[must_use]
    pub fn call_stack(&self, top_cip: u32) -> Vec<(u32, i32)> {
        let (Some(frm), Some(stp)) = (self.frame(), self.stp()) else {
            return Vec::new();
        };
        crate::debug::stack::walk(top_cip, frm, stp, |addr| self.read_cell(addr))
    }

    /// Removes a previously installed debug hook, restoring `amx->debug` to a
    /// no-op callback that returns `AMX_ERR_NONE`.
    pub fn remove_debug_hook(&self) {
        extern "C" fn noop(_amx: *mut AMX) -> i32 {
            0
        }
        self.install_debug_hook(noop);
    }
}

/// AMX heap allocator with automatic release (RAII).
///
/// Captures the value of `amx.hea` at creation time and restores it on `Drop`,
/// freeing everything allocated by the `Allocator` in a single operation.
/// Do not use multiple nested `Allocator`s — each one restores to a different
/// heap point.
pub struct Allocator<'amx> {
    amx: &'amx Amx,
    release_hea: i32,
    release_stk: i32,
}

impl<'amx> Allocator<'amx> {
    pub(crate) fn new(amx: &'amx Amx) -> Allocator<'amx> {
        // Capture the heap and stack tops to restore on drop. A null VM (only
        // reachable from tests) yields `(0, 0)` and every `allot*` then fails
        // gracefully via `amx_Allot` — no panic at construction.
        let (release_hea, release_stk) = amx.amx().map_or((0, 0), |ptr| {
            let ptr = ptr.as_ptr();
            unsafe { ((*ptr).hea, (*ptr).stk) }
        });

        Allocator {
            amx,
            release_hea,
            release_stk,
        }
    }

    /// Allocates a single cell on the heap and initializes it with `init_value`.
    ///
    /// # Errors
    /// `AmxError::Memory` if the VM heap is exhausted.
    pub fn allot<T: Sized + AmxPrimitive>(&self, init_value: T) -> AmxResult<Ref<'_, T>> {
        let mut cell = self.amx.allot(1)?;
        *cell = init_value;

        Ok(cell)
    }

    /// Allocates `size` cells on the heap and returns a [`Buffer`] covering that region.
    ///
    /// # Errors
    /// `AmxError::Memory` if the VM heap is exhausted or if `size` exceeds
    /// `i32::MAX`.
    pub fn allot_buffer(&self, size: usize) -> AmxResult<Buffer<'_>> {
        let buffer = self.amx.allot(size)?;

        Ok(Buffer::new(buffer, size))
    }

    /// Allocates space for `array.len()` cells and copies the content (`AmxCell::as_cell`).
    ///
    /// # Errors
    /// `AmxError::Memory` if the VM heap is exhausted.
    pub fn allot_array<T>(&self, array: &[T]) -> AmxResult<Buffer<'_>>
    where
        T: AmxCell<'amx> + AmxPrimitive,
    {
        let mut buffer = self.allot_buffer(array.len())?;

        let slice = buffer.as_mut_slice();

        for (idx, item) in array.iter().enumerate() {
            slice[idx] = item.as_cell();
        }

        Ok(buffer)
    }

    /// Allocates space for a string and copies `string` (configured encoding),
    /// adding the `0` terminator at the end.
    ///
    /// # Errors
    /// `AmxError::Memory` if the VM heap is exhausted.
    pub fn allot_string(&self, string: &str) -> AmxResult<AmxString<'_>> {
        let bytes = Allocator::string_bytes(string);
        let buffer = self.allot_buffer(bytes.len() + 1)?;

        Ok(unsafe { AmxString::new(buffer, bytes.as_ref()) })
    }

    fn string_bytes(string: &str) -> Cow<'_, [u8]> {
        #[cfg(feature = "encoding")]
        return encoding::get().encode(string).0;

        #[cfg(not(feature = "encoding"))]
        return Cow::from(string.as_bytes());
    }
}

impl Drop for Allocator<'_> {
    fn drop(&mut self) {
        // Rewinds heap + stack to the captured scope. Never fails; on a balanced
        // `exec_public!` the stack rewind is a no-op, on a failed push sequence
        // it restores the leftover cells so the VM stack stays balanced.
        self.amx.release_scope(self.release_hea, self.release_stk);
    }
}

#[cfg(test)]
mod vm_tests {
    use super::Amx;
    use crate::raw::types::{AMX, AMX_HEADER};
    use std::mem::MaybeUninit;

    /// Builds a synthetic `AMX` over `data` and runs `f` with an `Amx` wrapping
    /// it. Only the fields the VM accessors read are initialized (`base`/`data`/
    /// register fields); `data` non-null means `data_ptr` uses it directly,
    /// without needing a real `AMX_HEADER`.
    ///
    /// Region layout: valid data is `[0, stp)` minus the active heap/stack gap
    /// `[hea, stk)` — mirroring `amx_GetAddr`. Here `stp = data.len()`.
    fn with_amx(data: &mut [u8], cip: i32, frm: i32, hea: i32, stk: i32, f: impl FnOnce(&Amx)) {
        let stp = i32::try_from(data.len()).unwrap();
        let mut raw = MaybeUninit::<AMX>::uninit();
        let p = raw.as_mut_ptr();
        unsafe {
            let base = data.as_mut_ptr();
            std::ptr::addr_of_mut!((*p).base).write_unaligned(base);
            std::ptr::addr_of_mut!((*p).data).write_unaligned(base);
            std::ptr::addr_of_mut!((*p).cip).write_unaligned(cip);
            std::ptr::addr_of_mut!((*p).frm).write_unaligned(frm);
            std::ptr::addr_of_mut!((*p).hea).write_unaligned(hea);
            std::ptr::addr_of_mut!((*p).stk).write_unaligned(stk);
            std::ptr::addr_of_mut!((*p).stp).write_unaligned(stp);
            // pri/alt seeded deterministically so the register test can read them.
            std::ptr::addr_of_mut!((*p).pri).write_unaligned(11);
            std::ptr::addr_of_mut!((*p).alt).write_unaligned(0);
        }
        let amx = Amx::new(p, 0);
        f(&amx);
    }

    #[test]
    fn registers_read_back() {
        let mut data = vec![0u8; 256];
        with_amx(&mut data, 40, 100, 64, 192, |amx| {
            assert_eq!(amx.cip(), Some(40));
            assert_eq!(amx.frame(), Some(100));
            assert_eq!(amx.heap(), Some(64));
            assert_eq!(amx.stack(), Some(192));
            assert_eq!(amx.stp(), Some(256));
            // pri/alt as seeded by `with_amx` (alt = 0 models a divide-by-zero).
            assert_eq!(amx.pri(), Some(11));
            assert_eq!(amx.alt(), Some(0));
        });
    }

    #[test]
    fn read_code_reads_instructions_and_bounds() {
        // Build a minimal blob: AMX_HEADER followed by the code segment. Only the
        // `cod`/`dat` fields matter here — `cod` marks where the code starts and
        // `dat` its end (the data segment would follow). The `base` pointer is the
        // blob itself, mirroring how the loader lays the `.amx` out in memory.
        let hdr_size = std::mem::size_of::<AMX_HEADER>();
        let cod = i32::try_from(hdr_size).unwrap();
        // Two 4-byte cells of code: 0xAABBCCDD then 0x00000011.
        let mut blob = vec![0u8; hdr_size + 8];
        blob[hdr_size..hdr_size + 4].copy_from_slice(&0xAABB_CCDDu32.to_ne_bytes());
        blob[hdr_size + 4..hdr_size + 8].copy_from_slice(&0x11i32.to_ne_bytes());
        let dat = i32::try_from(hdr_size + 8).unwrap();

        let mut raw = MaybeUninit::<AMX>::uninit();
        let p = raw.as_mut_ptr();
        unsafe {
            let base = blob.as_mut_ptr();
            std::ptr::addr_of_mut!((*p).base).write_unaligned(base);
            let hdr = base.cast::<AMX_HEADER>();
            std::ptr::addr_of_mut!((*hdr).cod).write_unaligned(cod);
            std::ptr::addr_of_mut!((*hdr).dat).write_unaligned(dat);
        }
        let amx = Amx::new(p, 0);
        // Offset 0 and 4 are the two seeded cells.
        assert_eq!(amx.read_code(0), Some(0xAABB_CCDDu32.cast_signed()));
        assert_eq!(amx.read_code(4), Some(0x11));
        // Past the end of the code segment (size = 8): rejected.
        assert_eq!(amx.read_code(8), None);
        assert_eq!(amx.read_code(100), None);
    }

    #[test]
    fn read_write_cell_roundtrip_and_bounds() {
        let mut data = vec![0u8; 256];
        // Seed a global at addr 0 (below the heap/stack gap [64,192)).
        data[0..4].copy_from_slice(&7i32.to_ne_bytes());
        with_amx(&mut data, 40, 100, 64, 192, |amx| {
            // Valid below the gap.
            assert_eq!(amx.read_cell(0), Some(7));
            // Valid above the stack pointer (addr 200 in [192,256)).
            assert!(amx.write_cell(200, 0x1234_5678));
            assert_eq!(amx.read_cell(200), Some(0x1234_5678));
            // Inside the active heap/stack gap: rejected like amx_GetAddr.
            assert_eq!(amx.read_cell(100), None);
            assert!(!amx.write_cell(100, 1));
            // Negative and past the top of the stack: rejected.
            assert_eq!(amx.read_cell(-4), None);
            assert_eq!(amx.read_cell(256), None);
            assert_eq!(amx.read_cell(260), None);
        });
    }

    #[test]
    fn read_cells_reads_a_run_and_stops_at_the_gap() {
        let mut data = vec![0u8; 256];
        for (i, cell) in [10i32, 20, 30, 40].iter().enumerate() {
            data[i * 4..i * 4 + 4].copy_from_slice(&cell.to_ne_bytes());
        }
        // Heap/stack gap at [64, 192): cells 0..16 are readable.
        with_amx(&mut data, 40, 100, 64, 192, |amx| {
            assert_eq!(amx.read_cells(0, 4), Some(vec![10, 20, 30, 40]));
            // Starting mid-run.
            assert_eq!(amx.read_cells(8, 2), Some(vec![30, 40]));
            // Runs into the gap at 64: returns only what was readable.
            assert_eq!(amx.read_cells(56, 8).map(|v| v.len()), Some(2));
            // The start itself is inside the gap.
            assert_eq!(amx.read_cells(100, 2), None);
        });
    }

    #[test]
    fn read_bytes_handles_unaligned_start() {
        let mut data = vec![0u8; 256];
        // Bytes 0..8 = 0,1,2,3,4,5,6,7 (native order within each cell).
        for (i, b) in (0u8..8).enumerate() {
            data[i] = b;
        }
        with_amx(&mut data, 40, 100, 64, 192, |amx| {
            assert_eq!(amx.read_bytes(0, 4), Some(vec![0, 1, 2, 3]));
            // Unaligned start: begins at the enclosing cell and trims.
            assert_eq!(amx.read_bytes(2, 4), Some(vec![2, 3, 4, 5]));
            assert_eq!(amx.read_bytes(3, 2), Some(vec![3, 4]));
            // Truncated at the heap/stack gap instead of failing.
            let near_gap = amx.read_bytes(56, 32).expect("start is readable");
            assert_eq!(near_gap.len(), 8);
            // Unreadable start.
            assert_eq!(amx.read_bytes(100, 4), None);
        });
    }

    #[test]
    fn data_only_reads_without_a_function_table() {
        let mut data = vec![0u8; 256];
        data[..4].copy_from_slice(&7i32.to_ne_bytes());
        with_amx(&mut data, 40, 100, 64, 192, |amx| {
            let ptr = amx.amx().expect("non-null").as_ptr();
            let view = Amx::data_only(ptr);
            assert_eq!(view.read_cell(0), Some(7));
            assert_eq!(view.cip(), Some(40));
            assert!(view.write_cell(0, 9));
            assert_eq!(view.read_cell(0), Some(9));
        });
    }

    #[test]
    fn null_amx_is_safe() {
        let amx = Amx::new(std::ptr::null_mut(), 0);
        assert_eq!(amx.cip(), None);
        assert_eq!(amx.frame(), None);
        assert_eq!(amx.stp(), None);
        assert_eq!(amx.pri(), None);
        assert_eq!(amx.alt(), None);
        assert_eq!(amx.read_cell(0), None);
        assert_eq!(amx.read_cells(0, 4), None);
        assert_eq!(amx.read_bytes(0, 4), None);
        assert_eq!(amx.read_code(0), None);
        assert_eq!(amx.opcode_table(256), None);
        assert!(!amx.write_cell(0, 1));
        // Installing/removing a hook on a null AMX must not crash.
        amx.remove_debug_hook();
    }
}