rust-apk 1.0.0

Build, align, sign, verify, and inspect Android APKs in pure Rust
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
//! `Res_value`: typed values stored in resource tables and binary XML.

use std::fmt;
use std::str::FromStr;

use binrw::binrw;

use super::id::{ResourceId, ResourceRef};

/// The raw, 8-byte `Res_value` record.
#[binrw]
#[brw(little)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct RawValue {
    #[br(temp)]
    #[bw(calc = 8)]
    _size: u16,
    #[br(temp)]
    #[bw(calc = 0)]
    _reserved: u8,
    pub data_type: u8,
    pub data: u32,
}

impl RawValue {
    pub const SIZE: usize = 8;

    pub const fn new(data_type: u8, data: u32) -> Self {
        Self { data_type, data }
    }

    /// Reads a record from the start of `bytes`.
    pub fn read(bytes: &[u8]) -> Option<Self> {
        let bytes = bytes.get(..Self::SIZE)?;
        Some(Self::new(bytes[3], u32::from_le_bytes(bytes[4..8].try_into().ok()?)))
    }
}

/// `Res_value::dataType` codes.
pub(crate) mod data_type {
    pub const NULL: u8 = 0x00;
    pub const REFERENCE: u8 = 0x01;
    pub const ATTRIBUTE: u8 = 0x02;
    pub const STRING: u8 = 0x03;
    pub const FLOAT: u8 = 0x04;
    pub const DIMENSION: u8 = 0x05;
    pub const FRACTION: u8 = 0x06;
    pub const INT_DEC: u8 = 0x10;
    pub const INT_HEX: u8 = 0x11;
    pub const INT_BOOLEAN: u8 = 0x12;
    pub const INT_COLOR_ARGB8: u8 = 0x1c;
    pub const INT_COLOR_RGB8: u8 = 0x1d;
    pub const INT_COLOR_ARGB4: u8 = 0x1e;
    pub const INT_COLOR_RGB4: u8 = 0x1f;

    /// `TYPE_NULL` data marking an explicitly empty value (`@empty`).
    pub const DATA_NULL_EMPTY: u32 = 1;
}

/// A resource or attribute value.
///
/// References may be symbolic ([`ResourceRef::Named`]) while building; they
/// are resolved to IDs when encoded. Decoded values always carry IDs.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum Value {
    String(String),
    Bool(bool),
    /// A decimal integer (`TYPE_INT_DEC`); also used for enum attributes.
    Int(i32),
    /// A hexadecimal integer (`TYPE_INT_HEX`); also used for flag attributes.
    Hex(u32),
    Float(f32),
    Dimension(Dimension),
    Fraction(Fraction),
    Color(Color),
    /// `@type/name`: the value of another resource.
    Reference(ResourceRef),
    /// `?type/name`: the value of a theme attribute.
    Attribute(ResourceRef),
    /// `@null`: no resource, which clears an attribute (a reference to ID 0).
    Null,
    /// `@empty`: an explicitly empty value.
    Empty,
    /// A value type this crate does not interpret, kept verbatim.
    Raw {
        data_type: u8,
        data: u32,
    },
}

impl Value {
    /// Decodes a raw value; `string` looks up string values by pool index.
    pub(crate) fn from_raw<E>(raw: RawValue, string: impl FnOnce(u32) -> Result<String, E>) -> Result<Self, E> {
        use data_type::*;
        let data = raw.data;
        Ok(match raw.data_type {
            NULL if data == DATA_NULL_EMPTY => Self::Empty,
            REFERENCE if data == 0 => Self::Null,
            REFERENCE => Self::Reference(ResourceRef::Id(ResourceId(data))),
            ATTRIBUTE => Self::Attribute(ResourceRef::Id(ResourceId(data))),
            STRING => Self::String(string(data)?),
            FLOAT => Self::Float(f32::from_bits(data)),
            DIMENSION => Self::Dimension(Dimension(data)),
            FRACTION => Self::Fraction(Fraction(data)),
            INT_DEC => Self::Int(data as i32),
            INT_HEX => Self::Hex(data),
            INT_BOOLEAN => Self::Bool(data != 0),
            INT_COLOR_ARGB8 => Self::Color(Color { argb: data, format: ColorFormat::Argb8 }),
            INT_COLOR_RGB8 => Self::Color(Color { argb: data, format: ColorFormat::Rgb8 }),
            INT_COLOR_ARGB4 => Self::Color(Color { argb: data, format: ColorFormat::Argb4 }),
            INT_COLOR_RGB4 => Self::Color(Color { argb: data, format: ColorFormat::Rgb4 }),
            data_type => Self::Raw { data_type, data },
        })
    }

    /// Encodes this value. `string` interns a string; `resolve` maps a
    /// symbolic reference to its ID.
    pub(crate) fn to_raw<'v, E>(
        &'v self,
        string: impl FnOnce(&'v str) -> u32,
        resolve: impl FnOnce(&ResourceRef) -> Result<ResourceId, E>,
    ) -> Result<RawValue, E> {
        use data_type::*;
        Ok(match self {
            Self::String(s) => RawValue::new(STRING, string(s)),
            Self::Bool(b) => RawValue::new(INT_BOOLEAN, if *b { u32::MAX } else { 0 }),
            Self::Int(i) => RawValue::new(INT_DEC, *i as u32),
            Self::Hex(h) => RawValue::new(INT_HEX, *h),
            Self::Float(f) => RawValue::new(FLOAT, f.to_bits()),
            Self::Dimension(d) => RawValue::new(DIMENSION, d.0),
            Self::Fraction(f) => RawValue::new(FRACTION, f.0),
            Self::Color(c) => RawValue::new(c.format.data_type(), c.argb),
            Self::Reference(r) => RawValue::new(REFERENCE, resolve(r)?.0),
            Self::Attribute(r) => RawValue::new(ATTRIBUTE, resolve(r)?.0),
            // As aapt2 compiles it; `TYPE_NULL` would leave the attribute
            // undefined, so a style's value would apply instead.
            Self::Null => RawValue::new(REFERENCE, 0),
            Self::Empty => RawValue::new(NULL, DATA_NULL_EMPTY),
            Self::Raw { data_type, data } => RawValue::new(*data_type, *data),
        })
    }

    pub fn as_str(&self) -> Option<&str> {
        match self {
            Self::String(s) => Some(s),
            _ => None,
        }
    }

    /// The integer content of `Int`, `Hex`, or `Bool` values.
    pub fn as_int(&self) -> Option<i64> {
        match *self {
            Self::Int(i) => Some(i.into()),
            Self::Hex(h) => Some(h.into()),
            Self::Bool(b) => Some(b.into()),
            _ => None,
        }
    }

    pub fn as_bool(&self) -> Option<bool> {
        match *self {
            Self::Bool(b) => Some(b),
            _ => None,
        }
    }
}

impl From<&str> for Value {
    fn from(s: &str) -> Self {
        Self::String(s.to_owned())
    }
}

impl From<String> for Value {
    fn from(s: String) -> Self {
        Self::String(s)
    }
}

impl From<bool> for Value {
    fn from(b: bool) -> Self {
        Self::Bool(b)
    }
}

impl From<i32> for Value {
    fn from(i: i32) -> Self {
        Self::Int(i)
    }
}

impl From<ResourceRef> for Value {
    fn from(r: ResourceRef) -> Self {
        Self::Reference(r)
    }
}

impl From<Color> for Value {
    fn from(c: Color) -> Self {
        Self::Color(c)
    }
}

impl From<Dimension> for Value {
    fn from(d: Dimension) -> Self {
        Self::Dimension(d)
    }
}

impl From<Fraction> for Value {
    fn from(f: Fraction) -> Self {
        Self::Fraction(f)
    }
}

impl fmt::Display for Value {
    /// Formats the value using Android XML notation.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::String(s) => f.write_str(s),
            Self::Bool(b) => write!(f, "{b}"),
            Self::Int(i) => write!(f, "{i}"),
            Self::Hex(h) => write!(f, "0x{h:08x}"),
            Self::Float(x) => write!(f, "{x:?}"),
            Self::Dimension(d) => write!(f, "{d}"),
            Self::Fraction(x) => write!(f, "{x}"),
            Self::Color(c) => write!(f, "{c}"),
            Self::Reference(r) => write!(f, "{r}"),
            Self::Attribute(r) => write!(f, "?{}", r.to_string().trim_start_matches('@')),
            Self::Null => f.write_str("@null"),
            Self::Empty => f.write_str("@empty"),
            Self::Raw { data_type, data } => write!(f, "(type 0x{data_type:02x})0x{data:08x}"),
        }
    }
}

/// A malformed color, dimension, or fraction literal.
#[derive(Clone, Debug, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum LiteralError {
    #[error("{text:?} is not a color (#RGB, #ARGB, #RRGGBB, or #AARRGGBB)")]
    Color { text: String },
    #[error("{text:?} is not a dimension such as `16dp`")]
    Dimension { text: String },
    #[error("{text:?} is not a fraction such as `50%` or `50%p`")]
    Fraction { text: String },
    #[error("{value} is not finite with a magnitude below 2^23, so it has no complex encoding")]
    OutOfRange { value: f32 },
}

/// How a color literal was written, which selects its `Res_value` type.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub enum ColorFormat {
    /// `#AARRGGBB`
    #[default]
    Argb8,
    /// `#RRGGBB`
    Rgb8,
    /// `#ARGB`
    Argb4,
    /// `#RGB`
    Rgb4,
}

impl ColorFormat {
    const fn data_type(self) -> u8 {
        match self {
            Self::Argb8 => data_type::INT_COLOR_ARGB8,
            Self::Rgb8 => data_type::INT_COLOR_RGB8,
            Self::Argb4 => data_type::INT_COLOR_ARGB4,
            Self::Rgb4 => data_type::INT_COLOR_RGB4,
        }
    }
}

/// A color, stored as 32-bit ARGB regardless of its literal form.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct Color {
    pub argb: u32,
    pub format: ColorFormat,
}

impl Color {
    pub const fn argb(argb: u32) -> Self {
        Self { argb, format: ColorFormat::Argb8 }
    }

    pub const fn rgb(rgb: u32) -> Self {
        Self { argb: 0xff00_0000 | (rgb & 0x00ff_ffff), format: ColorFormat::Rgb8 }
    }
}

impl FromStr for Color {
    type Err = LiteralError;

    /// Parses `#RGB`, `#ARGB`, `#RRGGBB`, or `#AARRGGBB`.
    fn from_str(text: &str) -> Result<Self, LiteralError> {
        let invalid = || LiteralError::Color { text: text.to_owned() };
        let hex =
            text.strip_prefix('#').filter(|hex| hex.bytes().all(|b| b.is_ascii_hexdigit())).ok_or_else(invalid)?;
        let value = u32::from_str_radix(hex, 16).map_err(|_| invalid())?;
        // Each 4-bit digit of a short form stands for a repeated 8-bit pair.
        let widen = |v: u32| (0..4).rev().fold(0, |acc, i| (acc << 8) | (((v >> (i * 4)) & 0xf) * 0x11));
        Ok(match hex.len() {
            3 => Self { argb: 0xff00_0000 | widen(value), format: ColorFormat::Rgb4 },
            4 => Self { argb: widen(value), format: ColorFormat::Argb4 },
            6 => Self { argb: 0xff00_0000 | value, format: ColorFormat::Rgb8 },
            8 => Self { argb: value, format: ColorFormat::Argb8 },
            _ => return Err(invalid()),
        })
    }
}

impl fmt::Display for Color {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let opaque = self.argb >> 24 == 0xff;
        let short = (self.argb & 0x0f0f_0f0f) == ((self.argb >> 4) & 0x0f0f_0f0f);
        match self.format {
            ColorFormat::Rgb8 if opaque => write!(f, "#{:06x}", self.argb & 0x00ff_ffff),
            ColorFormat::Argb4 | ColorFormat::Rgb4 if short && (self.format == ColorFormat::Argb4 || opaque) => {
                let short = (0..4).rev().fold(0, |value, i| (value << 4) | ((self.argb >> (i * 8 + 4)) & 0xf));
                match self.format {
                    ColorFormat::Argb4 => write!(f, "#{short:04x}"),
                    _ => write!(f, "#{:03x}", short & 0xfff),
                }
            }
            _ => write!(f, "#{:08x}", self.argb),
        }
    }
}

/// The unit of a [`Dimension`].
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum DimensionUnit {
    Px,
    Dp,
    Sp,
    Pt,
    In,
    Mm,
}

impl DimensionUnit {
    const ALL: [(Self, &'static str); 6] =
        [(Self::Px, "px"), (Self::Dp, "dp"), (Self::Sp, "sp"), (Self::Pt, "pt"), (Self::In, "in"), (Self::Mm, "mm")];

    fn suffix(self) -> &'static str {
        Self::ALL[self as usize].1
    }
}

/// A dimension such as `16dp`, held in Android's complex-number encoding,
/// so decoded values re-encode exactly.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct Dimension(u32);

impl Dimension {
    /// Encodes `value` in `unit`, which must be finite and below 2^23 in magnitude.
    pub fn new(value: f32, unit: DimensionUnit) -> Result<Self, LiteralError> {
        Ok(Self(complex(value)? | unit as u32))
    }

    pub fn value(self) -> f32 {
        complex_value(self.0)
    }

    /// The unit, or `None` for a unit code Android does not define.
    pub fn unit(self) -> Option<DimensionUnit> {
        DimensionUnit::ALL.get((self.0 & UNIT_MASK) as usize).map(|(unit, _)| *unit)
    }
}

impl FromStr for Dimension {
    type Err = LiteralError;

    /// Parses `<number><unit>`, accepting `dip` as an alias of `dp`.
    fn from_str(text: &str) -> Result<Self, LiteralError> {
        let invalid = || LiteralError::Dimension { text: text.to_owned() };
        let (unit, number) = DimensionUnit::ALL
            .into_iter()
            .chain([(DimensionUnit::Dp, "dip")])
            .find_map(|(unit, suffix)| text.strip_suffix(suffix).map(|number| (unit, number)))
            .ok_or_else(invalid)?;
        Self::new(number.trim().parse().map_err(|_| invalid())?, unit)
    }
}

impl fmt::Display for Dimension {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.unit() {
            Some(unit) => write!(f, "{}{}", self.value(), unit.suffix()),
            None => write!(f, "{}(unit {})", self.value(), self.0 & UNIT_MASK),
        }
    }
}

/// A fraction such as `50%` (of the element) or `50%p` (of its parent), held
/// in Android's complex-number encoding.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct Fraction(u32);

impl Fraction {
    /// Encodes the ratio `value` (`0.5` is `50%`).
    pub fn new(value: f32, relative_to_parent: bool) -> Result<Self, LiteralError> {
        Ok(Self(complex(value)? | u32::from(relative_to_parent)))
    }

    /// The fraction as a ratio; `0.5` is `50%`.
    pub fn value(self) -> f32 {
        complex_value(self.0)
    }

    pub fn relative_to_parent(self) -> bool {
        self.0 & UNIT_MASK == 1
    }
}

impl FromStr for Fraction {
    type Err = LiteralError;

    fn from_str(text: &str) -> Result<Self, LiteralError> {
        let invalid = || LiteralError::Fraction { text: text.to_owned() };
        let (number, relative_to_parent) = match text.strip_suffix("%p") {
            Some(number) => (number, true),
            None => (text.strip_suffix('%').ok_or_else(invalid)?, false),
        };
        let percent: f32 = number.trim().parse().map_err(|_| invalid())?;
        Self::new(percent / 100.0, relative_to_parent)
    }
}

impl fmt::Display for Fraction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}%{}", self.value() * 100.0, if self.relative_to_parent() { "p" } else { "" })
    }
}

const UNIT_MASK: u32 = 0xf;
const RADIX_SHIFT: u32 = 4;
const MANTISSA_SHIFT: u32 = 8;
const MANTISSA_MASK: u32 = 0x00ff_ffff;
/// Values must be smaller than this in magnitude: the mantissa is a 24-bit
/// two's complement integer.
const COMPLEX_LIMIT: f32 = (1 << 23) as f32;

/// `complex_value` from AOSP `ResourceTypes.cpp`.
fn complex_value(data: u32) -> f32 {
    const MANTISSA_MULT: f32 = 1.0 / (1 << MANTISSA_SHIFT) as f32;
    const RADIX_MULTS: [f32; 4] = [
        MANTISSA_MULT,
        MANTISSA_MULT / (1 << 7) as f32,
        MANTISSA_MULT / (1 << 15) as f32,
        MANTISSA_MULT / (1 << 23) as f32,
    ];
    let mantissa = (data & (MANTISSA_MASK << MANTISSA_SHIFT)) as i32;
    mantissa as f32 * RADIX_MULTS[((data >> RADIX_SHIFT) & 0x3) as usize]
}

/// The mantissa and radix bits of `value`, as AOSP `ResTable::stringToFloat`
/// computes them.
fn complex(value: f32) -> Result<u32, LiteralError> {
    if !value.is_finite() || value.abs() >= COMPLEX_LIMIT {
        return Err(LiteralError::OutOfRange { value });
    }
    // Single precision, exactly as aapt2 computes it.
    let bits = (value.abs() * (1u32 << 23) as f32 + 0.5) as u64;
    let (radix, shift) = match bits {
        _ if bits & 0x7f_ffff == 0 => (0, 23),
        _ if bits & !0x7f_ffff == 0 => (3, 0),
        _ if bits & !0x7fff_ffff == 0 => (2, 8),
        _ if bits & !0x7f_ffff_ffff == 0 => (1, 16),
        _ => (0, 23),
    };
    let mut mantissa = ((bits >> shift) as u32) & MANTISSA_MASK;
    if value < 0.0 {
        mantissa = mantissa.wrapping_neg() & MANTISSA_MASK;
    }
    Ok((radix << RADIX_SHIFT) | (mantissa << MANTISSA_SHIFT))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn complex_numbers_round_trip() {
        for value in [0.0, 1.0, 16.0, 0.5, -3.25, 1234.5, 0.001, 8_388_607.0, -8_388_607.0] {
            let dimension = Dimension::new(value, DimensionUnit::Dp).unwrap();
            assert!((dimension.value() - value).abs() < 1e-3, "{value} decoded as {}", dimension.value());
            assert_eq!(dimension.unit(), Some(DimensionUnit::Dp));
        }
        // Matches aapt2's encoding of 16dp.
        assert_eq!(Dimension::new(16.0, DimensionUnit::Dp).unwrap().0, 0x0000_1001);
    }

    #[test]
    fn unrepresentable_numbers_are_rejected() {
        for value in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, 8_388_608.0, -8_388_608.0, 1e30] {
            assert!(
                matches!(Dimension::new(value, DimensionUnit::Dp), Err(LiteralError::OutOfRange { .. })),
                "{value}"
            );
        }
        assert!(matches!("1000000000%".parse::<Fraction>(), Err(LiteralError::OutOfRange { .. })));
    }

    #[test]
    fn decoded_values_re_encode_exactly() {
        // A unit code Android does not define survives.
        let raw = RawValue::new(data_type::DIMENSION, 0x0000_100f);
        let value = Value::from_raw::<()>(raw, |_| unreachable!()).unwrap();
        assert_eq!(value.to_raw::<()>(|_| unreachable!(), |_| unreachable!()).unwrap(), raw);
    }

    #[test]
    fn parses_literals() {
        let argb = |text: &str| text.parse::<Color>().unwrap().argb;
        assert_eq!(argb("#f00"), 0xffff_0000);
        assert_eq!(argb("#8f00"), 0x88ff_0000);
        assert_eq!(argb("#123456"), 0xff12_3456);
        assert_eq!(argb("#80123456"), 0x8012_3456);
        for format in [ColorFormat::Rgb4, ColorFormat::Argb4, ColorFormat::Rgb8] {
            let color = Color { argb: 0x7f12_3456, format };
            assert_eq!(color.to_string(), "#7f123456", "unrepresentable formats must preserve the ARGB value");
        }
        for invalid in ["#12345", "#+1234", "123456"] {
            assert!(matches!(invalid.parse::<Color>(), Err(LiteralError::Color { .. })), "{invalid}");
        }
        assert_eq!("4.5dip".parse::<Dimension>().unwrap(), Dimension::new(4.5, DimensionUnit::Dp).unwrap());
        for (text, value) in [("1e3dp", 1000.0), ("-2.5E-1dp", -0.25), ("1e+2dip", 100.0)] {
            assert_eq!(text.parse::<Dimension>().unwrap(), Dimension::new(value, DimensionUnit::Dp).unwrap());
        }
        assert!(matches!("4.5parsecs".parse::<Dimension>(), Err(LiteralError::Dimension { .. })));
        let fraction: Fraction = "50%p".parse().unwrap();
        assert_eq!((fraction.value(), fraction.relative_to_parent()), (0.5, true));
    }

    #[test]
    fn null_empty_and_undefined_are_distinct() {
        for value in [Value::Empty, Value::Null] {
            let raw = value.to_raw::<()>(|_| 0, |_| unreachable!()).unwrap();
            assert_eq!(Value::from_raw::<()>(raw, |_| unreachable!()).unwrap(), value);
        }
        // `@null` is what aapt2 writes: a reference to nothing.
        assert_eq!(
            Value::Null.to_raw::<()>(|_| 0, |_| unreachable!()).unwrap(),
            RawValue::new(data_type::REFERENCE, 0)
        );
        let undefined = RawValue::new(data_type::NULL, 0);
        assert_eq!(Value::from_raw::<()>(undefined, |_| unreachable!()).unwrap(), Value::Raw { data_type: 0, data: 0 });
    }
}