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
// Copyright (c) 2016 George Burton
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

// Copyright (c) 1985-2008 by Apple Inc.. All rights reserved.
// @APPLE_LICENSE_HEADER_START@
//
// This file contains Original Code and/or Modifications of Original Code
// as defined in and that are subject to the Apple Public Source License
// Version 2.0 (the 'License'). You may not use this file except in
// compliance with the License. Please obtain a copy of the License at
// http://www.opensource.apple.com/apsl/ and read it before using this
// file.
//
// The Original Code and all software distributed under the License are
// distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
// EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
// INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
// Please see the License for the specific language governing rights and
// limitations under the License.
//
// @APPLE_LICENSE_HEADER_END@

#![allow(non_camel_case_types, non_upper_case_globals, non_snake_case)]
#![cfg_attr(not(feature = "use_std"), no_std)]
#![cfg_attr(feature = "nightly", feature(untagged_unions))]

//! The `MacTypes-sys` library provides bindings to the MacTypes.h header on OSX.
//! This library defines base types used in both Carbon and legacy Cocoa APIs.

extern crate libc;

#[cfg(feature = "use_std")]
extern crate core;

use core::cmp::{Eq, PartialEq};
use core::hash::{Hash, Hasher};
use core::{fmt, mem, ptr, str};
use libc::*;

/// 8-bit unsigned integer.
pub type UInt8 = u8;
/// 8-bit signed integer.
pub type SInt8 = i8;
/// 16-bit unsigned integer.
pub type UInt16 = u16;
/// 16-bit signed integer.
pub type SInt16 = i16;
/// 32-bit unsigned integer.
pub type UInt32 = u32;
/// 32-bit signed integer.
pub type SInt32 = i32;

#[cfg(target_endian = "big")]
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub struct wide {
    pub hi: SInt32,
    pub lo: UInt32,
}

#[cfg(target_endian = "big")]
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub struct UnsignedWide {
    pub hi: UInt32,
    pub lo: UInt32,
}

#[cfg(target_endian = "little")]
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub struct wide {
    pub lo: UInt32,
    pub hi: SInt32,
}

#[cfg(target_endian = "little")]
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub struct UnsignedWide {
    pub lo: UInt32,
    pub hi: UInt32,
}

/// 64-bit signed integer.
pub type SInt64 = i64;
/// 64-bit unsigned integer.
pub type UInt64 = u64;

/// 16-bit signed integer plus 16-bit fraction.
pub type Fixed = SInt32;
/// A pointer to a `Fixed`.
pub type FixedPtr = *mut Fixed;
/// 2-bit signed integer plus 30-bit fraction.
pub type Fract = SInt32;
/// A pointer to a `Fract`.
pub type FractPtr = *mut Fract;
/// 16-bit unsigned integer plus 16-bit fraction.
pub type UnsignedFixed = UInt32;
/// A pointer to an `UnsignedFixed`.
pub type UnsignedFixedPtr = *mut UnsignedFixed;
/// 8-bit signed integer plus 8-bit fraction.
pub type ShortFixed = SInt16;
/// A pointer to a `ShortFixed`.
pub type ShortFixedPtr = *mut ShortFixed;

/// 32 bit IEEE float:  1 sign bit, 8 exponent bits, 23 fraction bits.
pub type Float32 = f32;
/// 64 bit IEEE float:  1 sign bit, 11 exponent bits, 52 fraction bits.
pub type Float64 = f64;

/// 80 bit MacOS float: 1 sign bit, 15 exponent bits, 1 integer bit, 63 fraction bits.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub struct Float80 {
    pub exp: SInt16,
    pub man: [UInt16; 4],
}

/// 96 bit 68881 float: 1 sign bit, 15 exponent bits, 16 pad bits, 1 integer bit, 63
/// fraction bits.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub struct Float96 {
    pub exp: [SInt16; 2],
    pub man: [UInt16; 4],
}

#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Float32Point {
    pub x: Float32,
    pub y: Float32,
}

/// Pointer to a non-relocatable block.
pub type Ptr = *mut c_char;
/// Pointer to a master pointer to a relocatable block.
pub type Handle = *mut Ptr;
/// The number of bytes in a block (signed for historical reasons).
pub type size = c_long;

/// 16-bit result error code.
pub type OSErr = SInt16;
/// 32-bit result error code.
pub type OSStatus = SInt32;
/// Address in the clients virtual address space.
pub type LogicalAddress = *mut c_void;
/// Address in the clients virtual address space that will only be read.
pub type ConstLogicalAddress = *const c_void;
/// Real address as used on the hardware bus.
pub type PhysicalAddress = *mut c_void;
/// Pointer to an array of bytes.
pub type BytePtr = *mut UInt8;
/// The size of an array of bytes.
pub type ByteCount = c_ulong;
/// An offset into an array of bytes.
pub type ByteOffset = c_ulong;
/// 32-bit millisecond timer for drivers.
pub type Duration = SInt32;
/// 64-bit clock.
pub type AbsoluteTime = UnsignedWide;
/// Standard 32-bit set of bit flags.
pub type OptionBits = UInt32;
/// 32-bit iteration count.
pub type ItemCount = c_ulong;
/// ?
pub type PBVersion = UInt32;
/// A particular set of written characters (e.g. Roman vs Cyrillic) and their encoding.
pub type ScriptCode = SInt16;
/// A particular language (e.g. English), as represented using a particular ScriptCode.
pub type LangCode = SInt16;
/// Designates a language as used in a particular region (e.g. British vs American
/// English) together with other region-dependent characteristics (e.g. date format).
pub type RegionCode = SInt16;
/// A 32-bit value made by packing four 1 byte characters together.
pub type FourCharCode = UInt32;
/// A FourCharCode used in the OS and file system (e.g. creator).
pub type OSType = FourCharCode;
/// A FourCharCode used to tag resources (e.g. 'DLOG').
pub type ResType = FourCharCode;
/// A pointer to an `OSType`.
pub type OSTypePtr = *mut OSType;
/// A pointer to a `ResType`.
pub type ResTypePtr = *mut ResType;

/// Mac OS historic type, sizeof(Boolean)==1.
pub type Boolean = c_uchar;

/// Generic pointer to a function.
pub type ProcPtr = unsafe extern "C" fn(c_long);
/// Pointer to a 68K function that expects parameters in registers.
pub type Register68kProcPtr = unsafe extern "C" fn();

/// Pointer to classic 68K code or a `RoutineDescriptor.
pub type UniversalProcPtr = ProcPtr;

/// Pointer to a `ProcPtr`.
pub type ProcHandle = *mut ProcPtr;
/// Pointer to a `UniversalProcPtr`.
pub type UniversalProcHandle = *mut UniversalProcPtr;

/// # RefCon Types
///
/// For access to private data in callbacks, etc.; refcons are generally
/// used as a pointer to something, but in the 32-bit world refcons in
/// different APIs have had various types: pointer, unsigned scalar, and
/// signed scalar. The RefCon types defined here support the current 32-bit
/// usage but provide normalization to pointer types for 64-bit.
///
/// `PRefCon` is preferred for new APIs; `URefCon` and `SRefCon` are primarily
/// for compatibility with existing APIs.
pub type PRefCon = *mut c_void;

/// # RefCon Types
///
/// For access to private data in callbacks, etc.; refcons are generally
/// used as a pointer to something, but in the 32-bit world refcons in
/// different APIs have had various types: pointer, unsigned scalar, and
/// signed scalar. The RefCon types defined here support the current 32-bit
/// usage but provide normalization to pointer types for 64-bit.
///
/// `PRefCon` is preferred for new APIs; `URefCon` and `SRefCon` are primarily
/// for compatibility with existing APIs.
#[cfg(target_pointer_width = "64")]
pub type URefCon = *mut c_void;

/// # RefCon Types
///
/// For access to private data in callbacks, etc.; refcons are generally
/// used as a pointer to something, but in the 32-bit world refcons in
/// different APIs have had various types: pointer, unsigned scalar, and
/// signed scalar. The RefCon types defined here support the current 32-bit
/// usage but provide normalization to pointer types for 64-bit.
///
/// `PRefCon` is preferred for new APIs; `URefCon` and `SRefCon` are primarily
/// for compatibility with existing APIs.
#[cfg(target_pointer_width = "64")]
pub type SRefCon = *mut c_void;

/// # RefCon Types
///
/// For access to private data in callbacks, etc.; refcons are generally
/// used as a pointer to something, but in the 32-bit world refcons in
/// different APIs have had various types: pointer, unsigned scalar, and
/// signed scalar. The RefCon types defined here support the current 32-bit
/// usage but provide normalization to pointer types for 64-bit.
///
/// `PRefCon` is preferred for new APIs; `URefCon` and `SRefCon` are primarily
/// for compatibility with existing APIs.
#[cfg(target_pointer_width = "32")]
pub type URefCon = UInt32;

/// # RefCon Types
///
/// For access to private data in callbacks, etc.; refcons are generally
/// used as a pointer to something, but in the 32-bit world refcons in
/// different APIs have had various types: pointer, unsigned scalar, and
/// signed scalar. The RefCon types defined here support the current 32-bit
/// usage but provide normalization to pointer types for 64-bit.
///
/// `PRefCon` is preferred for new APIs; `URefCon` and `SRefCon` are primarily
/// for compatibility with existing APIs.
#[cfg(target_pointer_width = "32")]
pub type SRefCon = SInt32;

/// OSErr: function performed properly - no error.
pub const kNoErr: OSErr = 0;
/// OptionBits: all flags false
pub const kNilOptions: OptionBits = 0;
/// KernelID: `NULL` is for pointers as `kInvalidID` is for ID's
pub const kInvalidId: u32 = 0;
/// Array bounds: variable length array
///
/// # Note
///
/// `kVariableLengthArray` is used in array bounds to specify a variable length array.
/// It is ususally used in variable length structs when the last field is an array
/// of any size.  Before ANSI C, we used zero as the bounds of variable length
/// array, but zero length array are illegal in ANSI C.  Example usage:
///
/// struct FooList
/// {
///     short   listLength;
///     Foo     elements[kVariableLengthArray];
/// };
pub const kVariableLengthArray: ItemCount = 1;
/// "????" QuickTime 3.0: default unknown ResType or OSType
pub const kUnknownType: OSType = 0x3F3F3F3F;

/// A complete Unicode character in UTF-32 format, with
/// values from 0 through 0x10FFFF (excluding the surrogate
/// range 0xD800-0xDFFF and certain disallowed values).
pub type UnicodeScalarValue = UInt32;
/// A complete Unicode character in UTF-32 format, with
/// values from 0 through 0x10FFFF (excluding the surrogate
/// range 0xD800-0xDFFF and certain disallowed values).
pub type UTF32Char = UInt32;
/// A 16-bit Unicode code value in the default UTF-16 format.
/// UnicodeScalarValues 0-0xFFFF are expressed in UTF-16
/// format using a single `UTF16Char` with the same value.
/// UnicodeScalarValues 0x10000-0x10FFFF are expressed in
/// UTF-16 format using a pair of `UTF16Char`s - one in the
/// high surrogate range (0xD800-0xDBFF) followed by one in
/// the low surrogate range (0xDC00-0xDFFF). All of the
/// characters defined in Unicode versions through 3.0 are
/// in the range 0-0xFFFF and can be expressed using a single
/// UTF16Char, thus the term "Unicode character" generally
/// refers to a `UniChar` = `UTF16Char`.
pub type UniChar = UInt16;
/// A 16-bit Unicode code value in the default UTF-16 format.
/// UnicodeScalarValues 0-0xFFFF are expressed in UTF-16
/// format using a single `UTF16Char` with the same value.
/// UnicodeScalarValues 0x10000-0x10FFFF are expressed in
/// UTF-16 format using a pair of `UTF16Char`s - one in the
/// high surrogate range (0xD800-0xDBFF) followed by one in
/// the low surrogate range (0xDC00-0xDFFF). All of the
/// characters defined in Unicode versions through 3.0 are
/// in the range 0-0xFFFF and can be expressed using a single
/// UTF16Char, thus the term "Unicode character" generally
/// refers to a `UniChar` = `UTF16Char`.
pub type UTF16Char = UInt16;
/// An 8-bit code value in UTF-8 format. `UnicodeScalarValue`s
/// 0-0x7F are expressed in UTF-8 format using one `UTF8Char`
/// with the same value. `UnicodeScalarValue`s above 0x7F are
/// expressed in UTF-8 format using 2-4 `UTF8Char`s, all with
/// values in the range 0x80-0xF4 (`UnicodeScalarValue`s
/// 0x100-0xFFFF use two or three `UTF8Char`s,
/// `UnicodeScalarValue`s 0x10000-0x10FFFF use four `UTF8Chars`).
pub type UTF8Char = UInt8;
/// A pointer to an array of `UniChar`s.
pub type UniCharPtr = *mut UniChar;
/// A count of UTF-16 code values in an array or buffer.
pub type UniCharCount = c_ulong;
/// A pointer to a `UniCharCount`.
pub type UniCharCountPtr = *mut UniCharCount;
/// Pascal string holding up to 255 bytes
pub type Str255 = [c_uchar; 256];
/// Pascal string holding up to 63 bytes
pub type Str63 = [c_uchar; 64];
/// Pascal string holding up to 31 bytes
pub type Str31 = [c_uchar; 32];
/// Pascal string holding up to 27 bytes
pub type Str27 = [c_uchar; 28];
/// Pascal string holding up to 15 bytes
pub type Str15 = [c_uchar; 16];

/// The type Str32 is used in many AppleTalk based data structures.
/// It holds up to 32 one byte chars.  The problem is that with the
/// length byte it is 33 bytes long.  This can cause weird alignment
/// problems in structures.  To fix this the type "Str32Field" has
/// been created.  It should only be used to hold 32 chars, but
/// it is 34 bytes long so that there are no alignment problems.
pub type Str32Field = [c_uchar; 34];

/// This type is just an alias for `Str32Field`. It is only included
/// so that `MacTypes-sys 1.3.0` is not a breaking change. It will be
/// removed in version 2.0.0
#[deprecated(since = "0.1.3",
             note = "Please use Str32Field instead - this type is spelled incorrectly")]
pub type StrField32 = Str32Field;

/// QuickTime 3.0:
///
/// The type `StrFileName` is used to make MacOS structs work
/// cross-platform.  For example `FSSpec` or `SFReply` previously
/// contained a `Str63` field.  They now contain a `StrFileName`
/// field which is the same when targeting the MacOS but is
/// a 256 char buffer for Win32 and unix, allowing them to
/// contain long file names.
pub type StrFileName = Str63;

/// Pointer to a pascal string.
pub type StringPtr = *mut c_uchar;
/// Pointer to a StringPtr.
pub type StringHandle = *mut StringPtr;
/// Pointer to a read-only pascal string.
pub type ConstStringPtr = *const c_uchar;
/// For function parameters only - means string is const.
pub type ConstStr255Param = *const c_uchar;
/// For function parameters only - means string is const.
pub type ConstStr63Param = *const c_uchar;
/// For function parameters only - means string is const.
pub type ConstStr31Param = *const c_uchar;
/// For function parameters only - means string is const.
pub type ConstStr27Param = *const c_uchar;
/// For function parameters only - means string is const.
pub type ConstStr15Param = *const c_uchar;
/// For function parameters only - means string is const.
pub type ConstStrFileNameParam = *const ConstStr63Param;

/// Get the length of a pascal string.
#[inline(always)]
pub unsafe fn StrLength(string: ConstStr255Param) -> c_uchar {
    *string
}

/// Type for unique process identifier.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub struct ProcessSerialNumber {
    pub highLongOfPSN: UInt32,
    pub lowLongOfPSN: UInt32,
}

pub type ProcessSerialNumberPtr = *mut ProcessSerialNumber;

/// 2D Quickdraw coordinate, range: -32K to +32K.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub struct Point {
    pub v: c_short,
    pub h: c_short,
}

pub type PointPtr = *mut Point;

/// Rectangular Quickdraw area.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub struct Rect {
    pub top: c_short,
    pub left: c_short,
    pub bottom: c_short,
    pub right: c_short,
}

pub type RectPtr = *mut Rect;

#[repr(C)]
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub struct FixedRect {
    pub top: Fixed,
    pub left: Fixed,
    pub bottom: Fixed,
    pub right: Fixed,
}

pub type FixedRectPtr = *mut FixedRect;

/// Char when used as a parameter (historical 68K convention).
pub type CharParameter = c_short;

pub const normal: Style = 0;
pub const bold: Style = 1;
pub const italic: Style = 2;
pub const underline: Style = 4;
pub const outline: Style = 8;
pub const shadow: Style = 0x10;
pub const condense: Style = 0x20;
pub const extend: Style = 0x40;

/// Quickdraw font rendering styles.
///
/// # Note
///
/// The original Macintosh toolbox in 68K Pascal defined Style as a SET.
/// Both Style and CHAR occupy 8-bits in packed records or 16-bits when
/// used as fields in non-packed records or as parameters.
pub type Style = c_uchar;
/// Style when used as a parameter (historical 68K convention).
pub type StyleParameter = c_short;
/// Style when used as a field (historical 68K convention).
pub type StyleField = Style;

/// Count of units.
pub type TimeValue = SInt32;
/// Units per second.
pub type TimeScale = SInt32;
/// 64-bit count of units (always a struct).
pub type CompTimeValue = wide;
/// 64-bit count of units (long long or struct).
pub type TimeValue64 = SInt64;
/// An opaque reference to a time base.
pub type TimeBase = *mut TimeBaseRecord;

#[doc(hidden)]
#[repr(C)]
pub struct TimeBaseRecord {
    _priv: c_void,
}

/// Package of TimeBase, duration, and scale.
#[repr(C)]
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct TimeRecord {
    /// Units (duration or absolute).
    pub value: CompTimeValue,
    /// Units per second.
    pub scale: TimeScale,
    /// Reference to the time base
    pub base: TimeBase,
}

/// Packed BCD version representation (e.g. "4.2.1a3" is 0x04214003).
#[cfg(target_endian = "big")]
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub struct NumVersion {
    /// 1st part of version number in BCD.
    pub majorRev: UInt8,
    /// 2nd & 3rd part of version number share a byte.
    pub minorAndBugRef: UInt8,
    /// stage code: dev, alpha, beta, final.
    pub stage: UInt8,
    /// revision level of non-released version.
    pub nonRelRev: UInt8,
}

/// Packed BCD version representation (e.g. "4.2.1a3" is 0x04214003).
#[cfg(target_endian = "little")]
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub struct NumVersion {
    /// 1st part of version number in BCD.
    pub nonRelRev: UInt8,
    /// 2nd & 3rd part of version number share a byte.
    pub stage: UInt8,
    /// stage code: dev, alpha, beta, final.
    pub minorAndBugRef: UInt8,
    /// revision level of non-released version.
    pub majorRev: UInt8,
}

/// Version Release Stage Code.
pub const developStage: UInt8 = 0x20;
/// Version Release Stage Code.
pub const alphaStage: UInt8 = 0x40;
/// Version Release Stage Code.
pub const betaStage: UInt8 = 0x60;
/// Version Release Stage Code.
pub const finalStage: UInt8 = 0x80;

/// `NumVersionVariant` is a wrapper so `NumVersion` can be accessed as a 32-bit value,
#[cfg(feature = "nightly")]
#[repr(C)]
#[derive(Clone, Copy)]
pub union NumVersionVariant {
    pub parts: NumVersion,
    pub whole: UInt32,
}

#[cfg(feature = "nightly")]
impl Default for NumVersionVariant {
    #[inline]
    fn default() -> Self {
        NumVersionVariant { whole: 0 }
    }
}

#[cfg(feature = "nightly")]
impl fmt::Debug for NumVersionVariant {
    #[inline]
    fn fmt(&self, fmtr: &mut fmt::Formatter) -> fmt::Result {
        let parts = unsafe { self.parts };
        fmtr.debug_struct("NumVersionVariant")
            .field("parts", &parts)
            .finish()
    }
}

#[cfg(feature = "nightly")]
impl PartialEq for NumVersionVariant {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        unsafe { self.whole.eq(&other.whole) }
    }
}

#[cfg(feature = "nightly")]
impl Eq for NumVersionVariant {}

#[cfg(feature = "nightly")]
impl Hash for NumVersionVariant {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        unsafe {
            state.write_u32(self.whole);
        }
    }
}

/// `NumVersionVariant` is a wrapper so `NumVersion` can be accessed as a 32-bit value.
#[cfg(not(feature = "nightly"))]
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub struct NumVersionVariant {
    pub whole: UInt32,
}

pub type NumVersionVariantPtr = *mut NumVersionVariant;
pub type NumVersionVariantHandle = *mut NumVersionVariantPtr;

/// Contents of a `vers` resource.
#[repr(C)]
pub struct VersRec {
    pub numericVersion: NumVersion,
    pub countryCode: c_short,
    pub shortVersion: Str255,
    pub reserved: Str255,
}

// Manual implementation of various traits on VersRec as the Str255 members prevent auto-derive

impl Clone for VersRec {
    fn clone(&self) -> Self {
        let mut clone = VersRec::default();
        clone.numericVersion = self.numericVersion;
        clone.countryCode = self.countryCode;
        unsafe {
            ptr::copy_nonoverlapping(&self.shortVersion, &mut clone.shortVersion, 1);
            ptr::copy_nonoverlapping(&self.reserved, &mut clone.reserved, 1);
        }
        clone
    }
}

impl Copy for VersRec {}

impl Default for VersRec {
    #[inline]
    fn default() -> Self {
        VersRec {
            numericVersion: Default::default(),
            countryCode: Default::default(),
            shortVersion: [0; 256],
            reserved: [0; 256],
        }
    }
}

impl Eq for VersRec {}

impl fmt::Debug for VersRec {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.debug_struct("VersRec")
            .field("numericVersion", &self.numericVersion)
            .field("countryCode", &self.countryCode)
            .field("shortVersion",
                   &try!(str::from_utf8(&self.shortVersion).map_err(|_| fmt::Error)))
            .field("reserved",
                   &try!(str::from_utf8(&self.reserved).map_err(|_| fmt::Error)))
            .finish()
    }
}

impl Hash for VersRec {
    fn hash<H: Hasher>(&self, state: &mut H) {
        state.write_u32(unsafe { mem::transmute(self.numericVersion) });
        state.write_i16(self.countryCode);
        state.write(&self.shortVersion);
        state.write(&self.reserved);
    }
}

impl PartialEq for VersRec {
    fn eq(&self, other: &Self) -> bool {
        #[inline]
        fn ptr<T>(slice: &[T]) -> *const c_void {
            slice.as_ptr() as *const _
        }

        unsafe {
            self.numericVersion == other.numericVersion && self.countryCode == other.countryCode &&
            memcmp(ptr(&self.shortVersion),
                   ptr(&other.shortVersion),
                   mem::size_of::<Str255>()) == 0 &&
            memcmp(ptr(&self.reserved),
                   ptr(&other.reserved),
                   mem::size_of::<Str255>()) == 0
        }
    }
}

/// Pointer to a `VersRecPtr`.
pub type VersRecPtr = *mut VersRec;
/// Resource Handle containing a `VersRec`.
pub type VersRecHndl = *mut VersRecPtr;

pub type Byte = UInt8;
pub type SignedByte = SInt8;
pub type WidePtr = *mut wide;
pub type UnsignedWidePtr = *mut UnsignedWide;
pub type extended80 = Float80;
pub type extended96 = Float96;
pub type VHSelect = SInt8;

#[cfg(target_os = "macos")]
#[cfg_attr(target_os = "macos", link(name = "CoreServices", kind = "framework"))]
extern "C" {
    pub fn Debugger();
    pub fn DebugStr(debuggerMsg: ConstStr255Param);
    pub fn SysBreak();
    pub fn SysBreakStr(debuggerMsg: ConstStr255Param);
    pub fn SysBreakFunc(debuggerMsg: ConstStr255Param);
}

#[cfg(test)]
mod versrec_manual_derive_tests {
    use super::*;
    #[test]
    fn test_clone_and_eq() {
        let mut rec0 = VersRec::default();
        rec0.countryCode = 14;

        let random_string = b"Hello, world!A)R\xE2Q$";
        for i in 0..random_string.len() {
            rec0.shortVersion[i] = random_string[i];
        }

        let rec1 = rec0.clone();
        assert_eq!(rec0, rec1);
    }
}