file-mode 0.1.2

Decode Unix file mode bits, change them and apply them to files
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
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
/*!
Decode Unix file mode bits, change them and apply them to files.

All file type, special and protection bits described in `sys/stat.h` are represented.

The [Mode] can represent a file mode partially by the use of a bitmask. Only modified bits will be changed in the target file.
Modifications specific only to directories (search) are handled correctly.

# Usage examples

## Decoding mode bits

```
use std::path::Path;
use file_mode::{ModePath, User};

let mode = Path::new("LICENSE").mode().unwrap();

assert!(mode.file_type().unwrap().is_regular_file());
assert!(mode.user_protection(User::Owner).is_read_set());
assert!(mode.user_protection(User::Group).is_write_set());
assert!(!mode.user_protection(User::Other).is_execute_set());
```

## Applying chmod strings

```
use std::path::Path;
use file_mode::ModePath;

Path::new("LICENSE").set_mode("u+r,g+u").unwrap();
```

## Applying octal modes

```
use std::path::Path;
use file_mode::ModePath;

Path::new("LICENSE").set_mode(0o664).unwrap();
```

## Printing standard mode strings

```
use std::path::Path;
use file_mode::ModePath;

let mode = Path::new("LICENSE").mode().unwrap();

println!("{}", mode); // -rw-rw-r--
assert_eq!(&mode.to_string(), "-rw-rw-r--");
```

## Constructing Mode programmatically

```
use file_mode::{Mode, Protection, ProtectionBit, User};

let mut mode = Mode::empty();
let mut rw = Protection::empty();

rw.set(ProtectionBit::Read);
rw.set(ProtectionBit::Write);

mode.set_protection(User::Owner, &rw);
mode.set_protection(User::Group, &rw);
mode.set_protection(User::Other, &ProtectionBit::Read.into());

assert_eq!(mode.mode(), 0o664);

mode.set_mode_path("LICENSE").unwrap();
```

## For non-Unix systems mode can still be used but not set to files

```rust
use file_mode::{Mode, Protection, ProtectionBit, User};

let mut mode = Mode::empty();
let mut rw = Protection::empty();

rw.set(ProtectionBit::Read);
rw.set(ProtectionBit::Write);

mode.set_protection(User::Owner, &rw);
mode.set_protection(User::Group, &rw);
mode.set_protection(User::Other, &ProtectionBit::Read.into());

assert_eq!(mode.apply_to(0o600), 0o664);
```

Use `Mode::from` to construct mode as if it was read from a file:

```rust
use file_mode::Mode;

let mut mode = Mode::from(0o600);

mode.set_str("g+rw,o+r").unwrap();

assert_eq!(mode.mode(), 0o664);
```

# Features and platform support

This carte should compile on all platforms.
On non-Unix (not `target_family = "unix"`) systems, functions related to setting mode to files will not be available.

## The calling process's umask

On non-Unix systems, the calling process's umask is emulated via global variable and defaults to `0o002`.

## Serde

Implementations of `Serialize` and `Deserialize` for [Mode] can be enabled with `serde` feature flag.

*/

#[cfg(target_family = "unix")]
use std::io;
use std::fmt::{self, Debug, Display};
#[cfg(target_family = "unix")]
use std::path::Path;
#[cfg(target_family = "unix")]
use std::fs::{metadata, symlink_metadata, set_permissions, File};
use std::iter::FromIterator;

#[cfg(target_family = "unix")]
use std::os::unix::fs::PermissionsExt;

#[cfg(feature = "serde")]
use serde::{Serialize, Deserialize};

mod parser;
pub use parser::ModeParseError;

/* Encoding of the file mode.  */
const S_IFMT: u32 =		0o170000;	/* These bits determine file type.  */

/* File types.  */
const S_IFDIR: u32 =	0o040000;	/* Directory.  */
const S_IFCHR: u32 =	0o020000;	/* Character device.  */
const S_IFBLK: u32 =	0o060000;	/* Block device.  */
const S_IFREG: u32 =	0o100000;	/* Regular file.  */
const S_IFIFO: u32 =	0o010000;	/* FIFO.  */
const S_IFLNK: u32 =	0o120000;	/* Symbolic link.  */
const S_IFSOCK: u32 =	0o140000;	/* Socket.  */


/* Protection bits.  */
const S_ISUID: u32 =	0o4000;		/* Set user ID on execution.  */
const S_ISGID: u32 =	0o2000;		/* Set group ID on execution.  */
const S_ISVTX: u32 =	0o1000;		/* Save swapped text after use (sticky).  */
const S_IREAD: u32 =	0o400;		/* Read by owner.  */
const S_IWRITE: u32 =	0o200;		/* Write by owner.  */
const S_IEXEC: u32 =	0o100;		/* Execute by owner.  */

/// Represents which user's access to the file will be changed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum User {
    /// Represents 'u' flag
    Owner,
    /// Represents 'g' flag
    Group,
    /// Represents 'o' flag
    Other,
}

/// Type of the file as encoded in the mode value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FileType {
    Directory,
    CharacterDevice,
    BlockDevice,
    RegularFile,
    FIFO,
    SymbolicLink,
    Socket,
}

impl FileType {
    /// Gets [FileType] from mode value.
    pub fn from_mode(mode: u32) -> Option<FileType> {
        use FileType::*;
        match mode & S_IFMT {
            S_IFDIR => Some(Directory),
            S_IFCHR => Some(CharacterDevice),
            S_IFBLK => Some(BlockDevice),
            S_IFREG => Some(RegularFile),
            S_IFIFO => Some(FIFO),
            S_IFLNK => Some(SymbolicLink),
            S_IFSOCK => Some(Socket),
            _ => None
        }
    }

    /// Returns [true] if file is a directory.
    pub fn is_directory(&self) -> bool {
        *self == FileType::Directory
    }

    /// Returns [true] if file is a character device.
    pub fn is_character_device(&self) -> bool {
        *self == FileType::CharacterDevice
    }

    /// Returns [true] if file is a block device.
    pub fn is_block_device(&self) -> bool {
        *self == FileType::BlockDevice
    }

    /// Returns [true] if file is a regular file.
    pub fn is_regular_file(&self) -> bool {
        *self == FileType::RegularFile
    }

    /// Returns [true] if file is a first-in first-out special file.
    pub fn is_fifo(&self) -> bool {
        *self == FileType::FIFO
    }

    /// Returns [true] if file is a symbolic link.
    pub fn is_symbolic_link(&self) -> bool {
        *self == FileType::SymbolicLink
    }

    /// Returns [true] if file is a socket endpoint.
    pub fn is_socket(&self) -> bool {
        *self == FileType::Socket
    }

    /// Gets [Mode] with corresponding file type bits set.
    pub fn mode(&self) -> Mode {
        use FileType::*;
        let mode = match self {
            Directory =>          S_IFDIR,
            CharacterDevice =>    S_IFCHR,
            BlockDevice =>        S_IFBLK,
            RegularFile =>        S_IFREG,
            FIFO =>               S_IFIFO,
            SymbolicLink =>       S_IFLNK,
            Socket =>             S_IFSOCK,
        };

        Mode::new(mode, S_IFMT)
    }
}

/// Protection bit that can be set for a [User].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ProtectionBit {
    /// Permission to read.
    Read,
    /// Permission to write.
    Write,
    /// Permission to execute.
    Execute,
    /// Permission to search a directory - like execute but only applies to directories.
    Search,
}

impl From<ProtectionBit> for Protection {
    fn from(bit: ProtectionBit) -> Protection {
        Protection::empty().with_set(bit)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum ExecuteOrSearch {
    Execute(bool),
    Search(bool),
}

/// Protection bits for user's access to a file.
#[derive(Debug, Clone)]
pub struct Protection {
    read: Option<bool>,
    write: Option<bool>,
    execute: Option<ExecuteOrSearch>,
}

impl Protection {
    /// Constructs [Protection] with all bits forgotten.
    pub fn empty() -> Protection {
        Protection {
            read: None,
            write: None,
            execute: None,
        }
    }

    /// Constructs [Protection] with all bits set.
    pub fn all_set() -> Protection {
        Protection {
            read: Some(true),
            write: Some(true),
            execute: Some(ExecuteOrSearch::Execute(true)),
        }
    }

    /// Constructs [Protection] with all bits cleared.
    pub fn all_clear() -> Protection {
        Protection {
            read: Some(false),
            write: Some(false),
            execute: Some(ExecuteOrSearch::Execute(false)),
        }
    }

    /// Constructs [Protection] representing [User] access to the file described by [Mode].
    pub fn from_mode_user(mode: &Mode, user: User) -> Protection {
        let mut mask = mode.mask;
        let mut dir_mask = mode.dir_mask;
        let mut mode = mode.mode;

        let owner_mask = S_IREAD | S_IWRITE | S_IEXEC;

        let shift = Self::user_shift(user);
        mode <<= shift;
        mask <<= shift;
        dir_mask <<= shift;

        mode &= owner_mask;
        mask &= owner_mask;
        dir_mask &= owner_mask;

        let mut ret = Protection::empty();

        if mask & S_IREAD > 0 {
            ret.read = Some(mode & S_IREAD > 0);
        }

        if mask & S_IWRITE > 0 {
            ret.write = Some(mode & S_IWRITE > 0);
        }

        if mask & S_IEXEC > 0 {
            if dir_mask & S_IEXEC > 0 {
                ret.execute = Some(ExecuteOrSearch::Search(mode & S_IEXEC > 0));
            } else {
                ret.execute = Some(ExecuteOrSearch::Execute(mode & S_IEXEC > 0));
            }
        }

        ret
    }

    /// Returns [true] if read permission bit is set.
    pub fn is_read_set(&self) -> bool {
        self.read == Some(true)
    }

    /// Returns [true] if write permission bit is set.
    pub fn is_write_set(&self) -> bool {
        self.write == Some(true)
    }

    /// Returns [true] if execute permission bit is set.
    pub fn is_execute_set(&self) -> bool {
        self.execute == Some(ExecuteOrSearch::Execute(true))
    }

    /// Returns [true] if execute or search permission bits are set.
    pub fn is_search_set(&self) -> bool {
        self.execute == Some(ExecuteOrSearch::Execute(true)) ||
        self.execute == Some(ExecuteOrSearch::Search(true))
    }

    /// Returns self with given [ProtectionBit] set.
    pub fn with_set(mut self, bit: ProtectionBit) -> Protection {
        self.set(bit);
        self
    }

    /// Returns self with given [ProtectionBit] cleared.
    pub fn with_cleared(mut self, bit: ProtectionBit) -> Protection {
        self.clear(bit);
        self
    }

    /// Returns self with given [ProtectionBit] value forgotten.
    pub fn with_forgotten(mut self, bit: ProtectionBit) -> Protection {
        self.forget(bit);
        self
    }

    /// Sets given [ProtectionBit].
    pub fn set(&mut self, bit: ProtectionBit) {
        match bit {
            ProtectionBit::Read => self.read = Some(true),
            ProtectionBit::Write => self.write = Some(true),
            ProtectionBit::Execute => self.execute = Some(ExecuteOrSearch::Execute(true)),
            ProtectionBit::Search => self.execute = Some(ExecuteOrSearch::Search(true)),
        }
    }

    /// Clears given [ProtectionBit].
    pub fn clear(&mut self, bit: ProtectionBit) {
        match bit {
            ProtectionBit::Read => self.read = Some(false),
            ProtectionBit::Write => self.write = Some(false),
            ProtectionBit::Execute => self.execute = Some(ExecuteOrSearch::Execute(false)),
            ProtectionBit::Search => self.execute = Some(ExecuteOrSearch::Search(false)),
        }
    }

    /// Forgets the value of given [ProtectionBit].
    pub fn forget(&mut self, bit: ProtectionBit) {
        match bit {
            ProtectionBit::Read => self.read = None,
            ProtectionBit::Write => self.write = None,
            ProtectionBit::Execute | ProtectionBit::Search => self.execute = None,
        }
    }

    fn user_shift(user: User) -> u32 {
        match user {
                User::Owner => 0,
                User::Group => 3,
                User::Other => 6,
        }
    }

    /// Constructs [Mode] with protection bits set for [User].
    pub fn for_user(&self, user: User) -> Mode {
        let mut mode = Mode::empty();

        if let Some(read) = self.read {
            if read {
                mode.mode |= S_IREAD;
            } else {
                mode.mode &= !S_IREAD;
            }
            mode.mask |= S_IREAD;
        }

        if let Some(write) = self.write {
            if write {
                mode.mode |= S_IWRITE;
            } else {
                mode.mode &= !S_IWRITE;
            }
            mode.mask |= S_IWRITE;
        }

        if let Some(execute) = self.execute {
            match execute {
                ExecuteOrSearch::Execute(execute) | ExecuteOrSearch::Search(execute) => if execute {
                    mode.mode |= S_IEXEC;
                } else {
                    mode.mode &= !S_IEXEC;
                }
            }
            mode.mask |= S_IEXEC;

            if let ExecuteOrSearch::Search(_) = execute {
                mode.dir_mask |= S_IEXEC;
            }
        }

        let shift = Self::user_shift(user);
        mode.mode >>= shift;
        mode.mask >>= shift;
        mode.dir_mask >>= shift;

        mode
    }
}

/// Special bit that can be set for a [User].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SpecialBit {
    /// Sets the effective user ID of the calling process.
    SetId,
    /// Sticky Bit.
    Sticky,
}

impl From<SpecialBit> for Special {
    fn from(bit: SpecialBit) -> Special {
        Special::empty().with_set(bit)
    }
}

/// Special bits set on a file.
#[derive(Debug, Clone)]
pub struct Special {
    set_id: Option<bool>,
    sticky: Option<bool>,
}

impl Special {
    pub fn empty() -> Special {
        Special {
            set_id: None,
            sticky: None,
        }
    }

    /// Constructs [Special] representing [User]-specific special bits set on the file described by [Mode].
    ///
    /// * For [User::Owner] the [SpecialBit::SetId] bit will represent the `set-user-ID` mode bit.
    /// * For [User::Group] the [SpecialBit::SetId] bit will represent the `set-group-ID` mode bit.
    pub fn from_mode_user(mode: &Mode, user: User) -> Special {
        let mut ret = Special::empty();

        match user {
            User::Owner if mode.mask & S_ISUID > 0 => ret.set_id = Some(mode.mode & S_ISUID > 0),
            User::Group if mode.mask & S_ISGID > 0 => ret.set_id = Some(mode.mode & S_ISGID > 0),
            _ => (),
        }

        if mode.mask & S_ISVTX > 0 {
            ret.sticky = Some(mode.mode & S_ISVTX > 0);
        }

        ret
    }

    /// Returns [true] if set ID bit is set.
    ///
    /// * For [User::Owner] the bit will represent the `set-user-ID` mode bit.
    /// * For [User::Group] the bit will represent the `set-group-ID` mode bit.
    pub fn is_set_id_set(&self) -> bool {
        self.set_id == Some(true)
    }

    /// Returns [true] if sticky bit is set.
    pub fn is_sticky_set(&self) -> bool {
        self.sticky == Some(true)
    }

    /// Returns self with given [SpecialBit] set.
    pub fn with_set(mut self, bit: SpecialBit) -> Special {
        self.set(bit);
        self
    }

    /// Returns self with given [SpecialBit] cleared.
    pub fn with_cleared(mut self, bit: SpecialBit) -> Special {
        self.clear(bit);
        self
    }

    /// Returns self with given [SpecialBit] value forgotten.
    pub fn with_forgotten(mut self, bit: SpecialBit) -> Special {
        self.forget(bit);
        self
    }

    /// Sets given [SpecialBit].
    pub fn set(&mut self, bit: SpecialBit) {
        match bit {
            SpecialBit::SetId => self.set_id = Some(true),
            SpecialBit::Sticky => self.sticky = Some(true),
        }
    }

    /// Clears given [SpecialBit].
    pub fn clear(&mut self, bit: SpecialBit) {
        match bit {
            SpecialBit::SetId => self.set_id = Some(false),
            SpecialBit::Sticky => self.sticky = Some(false),
        }
    }

    /// Forgets the value of given [SpecialBit].
    pub fn forget(&mut self, bit: SpecialBit) {
        match bit {
            SpecialBit::SetId => self.set_id = None,
            SpecialBit::Sticky => self.sticky = None,
        }
    }

    /// Constructs [Mode] with special bits set according to [User].
    ///
    /// * For [User::Owner] the [SpecialBit::SetId] bit will represent the `set-user-ID` mode bit.
    /// * For [User::Group] the [SpecialBit::SetId] bit will represent the `set-group-ID` mode bit.
    pub fn for_user(&self, user: User) -> Mode {
        let mut mode = Mode::empty();

        if let Some(sticky) = self.sticky {
            if sticky {
                mode.mode |= S_ISVTX;
            } else {
                mode.mode &= !S_ISVTX;
            }
            mode.mask |= S_ISVTX;
        }

        if let Some(set_id) = self.set_id {
            match user {
                User::Owner => {
                    if set_id {
                        mode.mode |= S_ISUID;
                    } else {
                        mode.mode &= !S_ISUID;
                    }
                    mode.mask |= S_ISUID;
                }
                User::Group => {
                    if set_id {
                        mode.mode |= S_ISGID;
                    } else {
                        mode.mode &= !S_ISGID;
                    }
                    mode.mask |= S_ISGID;
                }
                _ => (), // don't set for other
            }
        }

        mode
    }
}

/// Unix file mode.
///
/// All file type, special and protection bits described in `sys/stat.h` are represented.
///
/// The `Mode` can represent a file mode partially by the use of a bitmask. Only modified bits will be changed in the target file.
/// Modifications specific only to directories (see [ProtectionBit::Search]) are handled correctly.
///
/// The `Mode` can be displayed as a string according to the POSIX standard for the `ls` command.
///
/// Mode bits can be set with `chmod` compatible string.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Mode {
    mode: u32,
    mask: u32,
    // bits set only apply to directories
    dir_mask: u32,
}

impl Debug for Mode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Mode")
            .field("mode", &format_args!("{:06o}", self.mode))
            .field("mask", &format_args!("{:06o}", self.mask))
            .field("dirm", &format_args!("{:06o}", self.dir_mask))
            .finish()
    }
}

impl Display for Mode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use FileType::*;
        match self.file_type() {
            Some(Directory) =>          f.write_str("d")?,
            Some(CharacterDevice) =>    f.write_str("c")?,
            Some(BlockDevice) =>        f.write_str("b")?,
            Some(RegularFile) =>        f.write_str("-")?,
            Some(FIFO) =>               f.write_str("p")?,
            Some(SymbolicLink) =>       f.write_str("l")?,
            Some(Socket) =>             f.write_str("s")?,
            None =>                     f.write_str("?")?,
        }

        use User::*;
        for user in &[Owner, Group, Other] {
            let special = self.user_special(*user);
            let protection = self.user_protection(*user);

            if protection.is_read_set() {
                f.write_str("r")?;
            } else {
                f.write_str("-")?;
            }

            if protection.is_write_set() {
                f.write_str("w")?;
            } else {
                f.write_str("-")?;
            }

            match user {
                Owner | Group => match (special.is_set_id_set(), protection.is_execute_set(), protection.is_search_set()) {
                    (true, true, _) => f.write_str("s")?,
                    (true, false, _) => f.write_str("S")?,
                    (false, false, true) => f.write_str("X")?,
                    (false, true, _) => f.write_str("x")?,
                    (false, false, _) => f.write_str("-")?,
                }
                Other => match (special.is_sticky_set(), protection.is_execute_set(), protection.is_search_set()) {
                    (true, true, _) => f.write_str("t")?,
                    (true, false, _) => f.write_str("T")?,
                    (false, false, true) => f.write_str("X")?,
                    (false, true, _) => f.write_str("x")?,
                    (false, false, _) => f.write_str("-")?,
                }
            }
        }

        Ok(())
    }
}

impl Mode {
    /// Constructs [Mode] from mode value and mask representing which special and permissions bits
    /// will be applied to the target file mode.
    pub fn new(mode: u32, mask: u32) -> Mode {
        Mode {
            mode: mode & (mask | S_IFMT),
            mask,
            dir_mask: 0,
        }
    }

    /// Constructs [Mode] with no bits sets and empty mask.
    pub fn empty() -> Mode {
        Mode {
            mode: 0,
            mask: 0,
            dir_mask: 0,
        }
    }

    /// Constructs [Mode] from mode value of the file represented by the path.
    ///
    /// The mask will be set to `0o7777` meaning that all the special and permissions bits will be applied
    /// to the target file mode.
    #[cfg(target_family = "unix")]
    pub fn from_path(path: impl AsRef<Path>) -> Result<Mode, io::Error> {
        Ok(Mode::new(metadata(path.as_ref())?.permissions().mode(), 0o7777 | S_IFMT))
    }

    /// Like [Mode::from_path] but will not follow symbolic links.
    #[cfg(target_family = "unix")]
    pub fn from_path_nofollow(path: impl AsRef<Path>) -> Result<Mode, io::Error> {
        Ok(Mode::new(symlink_metadata(path.as_ref())?.permissions().mode(), 0o7777 | S_IFMT))
    }

    /// Constructs [Mode] from mode value of the file.
    ///
    /// The mask will be set to `0o7777` meaning that all the special and permissions bits will be applied
    /// to the target file mode.
    #[cfg(target_family = "unix")]
    pub fn from_file(file: &File) -> Result<Mode, io::Error> {
        Ok(Mode::new(file.metadata()?.permissions().mode(), 0o7777 | S_IFMT))
    }

    /// Gets mode value.
    pub fn mode(&self) -> u32 {
        self.mode_mask().0
    }

    /// Gets mode value and mask that represents bits of the mode that would be applied to the target
    /// file mode.
    ///
    /// If the mode represents a directory the search bit will be handled accordingly.
    pub fn mode_mask(&self) -> (u32, u32) {
        if let Some(true) = self.file_type().map(|m| m.is_directory()) {
            (self.mode, self.mask)
        } else {
            (self.mode & !self.dir_mask, self.mask & !self.dir_mask)
        }
    }

    /// Gets [FileType] if corresponding bit patterns are present and valid in the mode value.
    pub fn file_type(&self) -> Option<FileType> {
        FileType::from_mode(self.mode)
    }

    /// Gets [Protection] bits for [User].
    pub fn user_protection(&self, user: User) -> Protection {
        Protection::from_mode_user(self, user)
    }

    /// Gets [Special] bits for [User].
    ///
    /// * For [User::Owner] the [SpecialBit::SetId] bit will represent the `set-user-ID` mode bit.
    /// * For [User::Group] the [SpecialBit::SetId] bit will represent the `set-group-ID` mode bit.
    pub fn user_special(&self, user: User) -> Special {
        Special::from_mode_user(self, user)
    }

    /// Sets bits that are set in the given mode according to mask.
    pub fn add(&mut self, mode: &Mode) {
        self.mode |= mode.mode;
        self.mask |= mode.mask;
        self.dir_mask |= mode.dir_mask;
    }

    /// Clears bits that are set in the given mode according to mask.
    pub fn sub(&mut self, mode: &Mode) {
        self.mode &= !mode.mode;
        self.mask |= mode.mask;
        self.dir_mask |= mode.dir_mask;
    }

    /// Sets values of bits that are set or clear in the given mode according to mask.
    pub fn set(&mut self, mode: &Mode) {
        self.mode &= !mode.mask;
        self.mode |= mode.mode;
        self.mask |= mode.mask;
        self.dir_mask |= mode.dir_mask;
    }

    /// Forgets values of bits that are set or clear in the given mode by clearing bits in the mask.
    pub fn forget(&mut self, mode: &Mode) {
        self.mode &= !mode.mask;
        self.mask &= !mode.mask;
        self.dir_mask &= !mode.dir_mask;
    }

    /// Returns self with given bit pattern representing [FileType] set.
    pub fn with_file_type(mut self, file_type: FileType) -> Mode {
        self.set(&file_type.mode());
        self
    }

    /// Returns self with bit pattern and mask for [Protection] bits set for [User].
    pub fn with_protection(mut self, user: User, protection: &Protection) -> Mode {
        self.set(&protection.for_user(user));
        self
    }

    /// Returns self with bit pattern and mask for [Special] bits set for [User].
    ///
    /// * For [User::Owner] the [SpecialBit::SetId] bit will represent the `set-user-ID` mode bit.
    /// * For [User::Group] the [SpecialBit::SetId] bit will represent the `set-group-ID` mode bit.
    pub fn with_special(mut self, user: User, special: &Special) -> Mode {
        self.set(&special.for_user(user));
        self
    }

    /// Sets bit pattern representing given [FileType].
    pub fn set_file_type(&mut self, file_type: FileType) {
        self.set(&file_type.mode())
    }

    /// Sets bit pattern and mask for [Protection] bits for [User].
    pub fn set_protection(&mut self, user: User, protection: &Protection) {
        self.set(&protection.for_user(user))
    }

    /// Sets bit pattern and mask for [Special] bits for [User].
    ///
    /// * For [User::Owner] the [SpecialBit::SetId] bit will represent the `set-user-ID` mode bit.
    /// * For [User::Group] the [SpecialBit::SetId] bit will represent the `set-group-ID` mode bit.
    pub fn set_special(&mut self, user: User, special: &Special) {
        self.set(&special.for_user(user))
    }

    /// Sets bits according to the mode string (as described in Linux `chmod` manual).
    ///
    /// Only bits described by the string will be represented in the mask.
    ///
    /// Note: Current value of mode is used as a reference for operations that use the
    /// user as the source of bits (like `g+u`). Consider constructing [Mode]
    /// using [Mode::from_file] or [Mode::from_path] before using this method.
    pub fn set_str(&mut self, mode_str: &str) -> Result<(), ModeParseError> {
        self.set_str_umask(mode_str, umask())
    }

    /// Like [Mode::set_str] but allows to specify umask value to use instead of the calling process's umask.
    pub fn set_str_umask(&mut self, mode_str: &str, umask: u32) -> Result<(), ModeParseError> {
        parser::mode_set_from_str(self, mode_str, umask)
    }

    /// Clears protection bits set in the umask value if they were set.
    pub fn apply_umask(&mut self, mut umask: u32) {
        umask &= 0o777;
        self.mode &= !umask;
    }

    /// Applies mode changes to given mode value.
    ///
    /// Only bits set in the mask are modified.
    ///
    /// Returns the resulting mode value.
    ///
    /// If the mode value passed as an argument represents a directory the search bit will be handled
    /// accordingly.
    pub fn apply_to(&self, mut mode: u32) -> u32 {
        let (amode, amask) = if let Some(true) = FileType::from_mode(mode).map(|m| m.is_directory()) {
            (self.mode, self.mask)
        } else {
            (self.mode & !self.dir_mask, self.mask & !self.dir_mask)
        };

        mode &= !amask;
        mode | amode
    }

    /// Applies mode changes to the mode of a file represented by the path.
    ///
    /// Only bits set in the mask are modified.
    ///
    /// Returns the resulting mode value.
    ///
    /// If the mode value of the file passed as an argument represents a directory the search bit will be handled accordingly.
    ///
    /// The file's mode is not modified.
    #[cfg(target_family = "unix")]
    pub fn apply_to_path(&self, path: impl AsRef<Path>) -> Result<u32, io::Error> {
        let file_mode = metadata(path.as_ref())?.permissions().mode();
        Ok(self.apply_to(file_mode))
    }

    /// Like [Mode::apply_to_path] but does not follow symbolic links.
    #[cfg(target_family = "unix")]
    pub fn apply_to_path_nofollow(&self, path: impl AsRef<Path>) -> Result<u32, io::Error> {
        let file_mode = symlink_metadata(path.as_ref())?.permissions().mode();
        Ok(self.apply_to(file_mode))
    }

    /// Sets the mode of the file, represented by the path, by applying the mode changes to its
    /// current mode.
    ///
    /// Only bits set in the mask are modified.
    ///
    /// Returns the new file mode value.
    ///
    /// If the mode value of the file passed as an argument represents a directory the search bit will be handled accordingly.
    ///
    /// The file's mode **is** modified.
    #[cfg(target_family = "unix")]
    pub fn set_mode_path(&self, path: impl AsRef<Path>) -> Result<u32, io::Error> {
        let path = path.as_ref();
        let mut perms = metadata(path)?.permissions();
        let mode = self.apply_to(perms.mode());
        perms.set_mode(mode);
        set_permissions(path, perms)?;
        Ok(mode)
    }

    /// Like [Mode::set_mode_path] but does not follow symbolic links.
    #[cfg(target_family = "unix")]
    pub fn set_mode_path_nofollow(&self, path: impl AsRef<Path>) -> Result<u32, io::Error> {
        let path = path.as_ref();
        let mut perms = symlink_metadata(path)?.permissions();
        let mode = self.apply_to(perms.mode());
        perms.set_mode(mode);
        set_permissions(path, perms)?;
        Ok(mode)
    }

    /// Sets the mode of the file by applying the mode changes to its current mode.
    ///
    /// Only bits set in the mask are modified.
    ///
    /// Returns the new file mode value.
    ///
    /// If the mode value of the file passed as an argument represents a directory the search bit will be handled accordingly.
    ///
    /// The file's mode **is** modified.
    #[cfg(target_family = "unix")]
    pub fn set_mode_file(&self, file: &File) -> Result<u32, io::Error> {
        let mut perms = file.metadata()?.permissions();
        let mode = self.apply_to(perms.mode());
        perms.set_mode(mode);
        file.set_permissions(perms)?;
        Ok(mode)
    }
}

impl From<u32> for Mode {
    fn from(mode: u32) -> Mode {
        Mode::new(mode, 0o7777)
    }
}

impl FromIterator<Mode> for Mode {
    fn from_iter<I: IntoIterator<Item=Mode>>(iter: I) -> Self {
        let mut mode = Mode::empty();

        for m in iter {
            mode.set(&m);
        }

        mode
    }
}


#[cfg(target_family = "unix")]
mod unix {
    use super::*;
    use std::error::Error;
    use std::convert::Infallible;

    /// Error setting mode to a file.
    #[derive(Debug)]
    pub enum ModeError {
        ModeParseError(ModeParseError),
        IoError(io::Error),
    }

    impl Display for ModeError {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            use ModeError::*;
            match self {
                ModeParseError(_) => write!(f, "error parsing file mode string"),
                IoError(_) => write!(f, "I/O error setting file mode"),
            }
        }
    }

    impl Error for ModeError {
        fn source(&self) -> Option<&(dyn Error + 'static)> {
            use ModeError::*;
            match self {
                ModeParseError(err) => Some(err),
                IoError(err) => Some(err),
            }
        }
    }

    impl From<ModeParseError> for ModeError {
        fn from(err: ModeParseError) -> ModeError {
            ModeError::ModeParseError(err)
        }
    }

    impl From<io::Error> for ModeError {
        fn from(err: io::Error) -> ModeError {
            ModeError::IoError(err)
        }
    }

    impl From<Infallible> for ModeError {
        fn from(_err: Infallible) -> ModeError {
            unreachable!()
        }
    }

    /// Types that convert to this type can be used with `set_mode` methods.
    pub enum SetMode<'s> {
        Value(Mode),
        Str(&'s str),
    }

    impl<'s, M: Into<Mode>> From<M> for SetMode<'s> {
        fn from(val: M) -> SetMode<'s> {
            SetMode::Value(val.into())
        }
    }

    impl<'s> From<&'s str> for SetMode<'s> {
        fn from(val: &'s str) -> SetMode<'s> {
            SetMode::Str(val)
        }
    }

    /// Extension methods for objects that can reference as [Path](std::path::Path).
    pub trait ModePath {
        /// Constructs [Mode] from mode value of the file.
        ///
        /// See [Mode::from_path] for details.
        fn mode(&self) -> Result<Mode, io::Error>;

        /// Sets the mode of the file, represented by this path, by applying the mode changes to its
        /// current mode.
        ///
        /// See [Mode::set_mode_path] for details.
        fn set_mode<'s, M: Into<SetMode<'s>>>(&self, mode: M) -> Result<u32, ModeError>;
    }

    impl<T: AsRef<Path>> ModePath for T {
        fn mode(&self) -> Result<Mode, io::Error> {
            Mode::from_path(self.as_ref())
        }

        fn set_mode<'s, M: Into<SetMode<'s>>>(&self, mode: M) -> Result<u32, ModeError> {
            let mut m = Mode::from_path(self)?; // need file mode as reference
            match mode.into() {
                SetMode::Value(val) => m.set(&val),
                SetMode::Str(val) => m.set_str(val)?, // this will use file mode as reference
            }
            Ok(m.set_mode_path(self)?)
        }
    }

    /// Extension methods for [File](std::fs::File).
    pub trait ModeFile {
        /// Constructs [Mode] from mode value of the file.
        ///
        /// See [Mode::from_path] for details.
        fn mode(&self) -> Result<Mode, io::Error>;

        /// Sets the mode of this file by applying the mode changes to its current mode.
        ///
        /// See [Mode::set_mode_file].
        fn set_mode<'s, M: Into<SetMode<'s>>>(&self, mode: M) -> Result<u32, ModeError>;
    }

    impl ModeFile for File {
        fn mode(&self) -> Result<Mode, io::Error> {
            Mode::from_file(&self)
        }

        fn set_mode<'s, M: Into<SetMode<'s>>>(&self, mode: M) -> Result<u32, ModeError> {
            let mut m = Mode::from_file(self)?; // need file mode as reference
            match mode.into() {
                SetMode::Value(val) => m.set(&val),
                SetMode::Str(val) => m.set_str(val)?, // this will use file mode as reference
            }
            Ok(m.set_mode_file(self)?)
        }
    }

    /// Sets the calling process's umask.
    ///
    /// Note: On non-Unix systems this is emulated by global variable.
    pub fn set_umask(umask: u32) -> u32 {
        unsafe {
            libc::umask(umask as libc::mode_t) as u32
        }
    }

    /// Gets the calling process's umask.
    ///
    /// Note: On non-Unix systems this is emulated by global variable.
    pub fn umask() -> u32 {
        let m = set_umask(0);
        set_umask(m);
        m
    }
}

#[cfg(target_family = "unix")]
pub use unix::*;

#[cfg(not(target_family = "unix"))]
mod non_unix {
    use std::sync::atomic::{AtomicU32, Ordering};

    static UMASK: AtomicU32 = AtomicU32::new(0o002);

    /// Sets the calling process's umask.
    ///
    /// Note: On non-Unix systems this is emulated by global variable.
    pub fn set_umask(umask: u32) -> u32 {
        UMASK.swap(umask, Ordering::Release)
    }

    /// Gets the calling process's umask.
    ///
    /// Note: On non-Unix systems this is emulated by global variable.
    pub fn umask() -> u32 {
        UMASK.load(Ordering::Acquire)
    }
}

#[cfg(not(target_family = "unix"))]
pub use non_unix::*;

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

    const UMASK_LOCK: Mutex<()> = parking_lot::const_mutex(());

    #[test]
    fn test_mode() {
        assert_eq!(Mode::new(0o700, 0o700).apply_to(0o412), 0o712);
        assert_eq!(Mode::new(0o700, 0o400).apply_to(0o412), 0o412);
        assert_eq!(Mode::new(0o000, 0o700).apply_to(0o412), 0o012);
        assert_eq!(Mode::new(0o000, 0o111).apply_to(0o412), 0o402);
        assert_eq!(Mode::new(0o111, 0o111).apply_to(0o412), 0o513);
        assert_eq!(Mode::new(0o777, 0o111).apply_to(0o412), 0o513);
    }

    #[test]
    fn test_protection() {
        use ProtectionBit::*;
        use User::*;

        let mut o_700 = Protection::empty();
        o_700.set(Read);
        assert!(o_700.is_read_set());
        assert!(!o_700.is_write_set());
        assert!(!o_700.is_execute_set());

        o_700.set(Write);
        assert!(o_700.is_read_set());
        assert!(o_700.is_write_set());
        assert!(!o_700.is_execute_set());

        o_700.set(Execute);
        assert!(o_700.is_read_set());
        assert!(o_700.is_write_set());
        assert!(o_700.is_execute_set());

        assert_eq!(o_700.for_user(Owner), Mode::new(0o700, 0o700));
        assert_eq!(o_700.for_user(Group), Mode::new(0o070, 0o070));
        assert_eq!(o_700.for_user(Other), Mode::new(0o007, 0o007));

        let mut o_100 = Protection::empty();
        o_100.set(Execute);

        assert_eq!(o_100.for_user(Owner), Mode::new(0o100, 0o100));
        assert_eq!(o_100.for_user(Group), Mode::new(0o010, 0o010));
        assert_eq!(o_100.for_user(Other), Mode::new(0o001, 0o001));

        let mut o_200 = Protection::empty();
        o_200.set(Write);

        assert_eq!(o_200.for_user(Owner), Mode::new(0o200, 0o200));
        assert_eq!(o_200.for_user(Group), Mode::new(0o020, 0o020));
        assert_eq!(o_200.for_user(Other), Mode::new(0o002, 0o002));

        let mut o_600 = o_700.clone();
        o_600.clear(Execute);
        assert_eq!(o_600.for_user(Owner), Mode::new(0o600, 0o700));

        let mut o_777 = o_700.for_user(Owner);
        o_777.set(&o_700.for_user(Group));
        o_777.set(&o_700.for_user(Other));

        assert_eq!(o_777, Mode::new(0o777, 0o777));

        let mut o_123 = Mode::empty();
        o_123.set_protection(Owner, &Protection::empty().with_set(Execute));
        o_123.set_protection(Group, &Protection::empty().with_set(Write));
        o_123.set_protection(Other, &Protection::empty().with_set(Execute).with_set(Write));

        assert_eq!(o_123, Mode::new(0o123, 0o123));

        let mut o_102 = o_123;
        o_102.set_protection(Group, &Protection::empty().with_cleared(Write));
        o_102.set_protection(Other, &Protection::empty().with_cleared(Execute));

        assert_eq!(o_102, Mode::new(0o102, 0o123));
    }

    #[test]
    fn test_special() {
        use SpecialBit::*;

        let mut mode = Mode::empty();
        mode.set_special(User::Owner, &SetId.into());
        assert_eq!(mode, Mode::new(0o4000, 0o4000));
        mode.set_special(User::Group, &SetId.into());
        assert_eq!(mode, Mode::new(0o6000, 0o6000));

        let mut mode = Mode::empty();
        mode.set_special(User::Other, &SetId.into());
        assert_eq!(mode, Mode::new(0o0000, 0o0000)); // according to chmod behaviour

        let mut mode = Mode::empty();
        mode.set_special(User::Owner, &Sticky.into());
        assert_eq!(mode, Mode::new(0o1000, 0o1000));
        mode.set_special(User::Group, &Sticky.into());
        assert_eq!(mode, Mode::new(0o1000, 0o1000));
        mode.set_special(User::Other, &Sticky.into());
        assert_eq!(mode, Mode::new(0o1000, 0o1000));

        mode.set_special(User::Group, &SetId.into());
        assert_eq!(mode, Mode::new(0o3000, 0o3000));

        mode.set_special(User::Owner, &SetId.into());
        assert_eq!(mode, Mode::new(0o7000, 0o7000));

        let mut mode = Mode::empty();
        let special = Special::empty();
        mode.set_special(User::Owner, &special);
        assert_eq!(mode, Mode::new(0o0000, 0o0000));

        let special = mode.user_special(User::Owner);
        assert!(!special.is_set_id_set());
        assert!(!special.is_sticky_set());

        mode.set_special(User::Group, &special);
        assert_eq!(mode, Mode::new(0o0000, 0o0000));

        let special = mode.user_special(User::Owner);
        assert!(!special.is_set_id_set());
        assert!(!special.is_sticky_set());

        let mut mode = Mode::empty();
        let mut special = Special::empty();

        special.set(SetId);
        special.set(Sticky);

        mode.set_special(User::Owner, &special);
        assert_eq!(mode, Mode::new(0o5000, 0o5000));

        let special = mode.user_special(User::Owner);
        assert!(special.is_set_id_set());
        assert!(special.is_sticky_set());

        mode.set_special(User::Group, &special);
        assert_eq!(mode, Mode::new(0o7000, 0o7000));

        let special = mode.user_special(User::Owner);
        assert!(special.is_set_id_set());
        assert!(special.is_sticky_set());
    }

    #[test]
    fn test_set_str_umask_symbolic() {
        let mut mode = Mode::empty();
        mode.set_str("u=rwx,g=rw,o+x").unwrap();
        assert_eq!(mode, Mode::new(0o761, 0o771));

        let mut mode = Mode::new(0o2777, 0o2777);
        mode.set_str_umask("o=t", 0o002).unwrap();
        assert_eq!(mode, Mode::new(0o3770, 0o3777)); // according to chmod behaviour

        let mut mode = Mode::new(0o1770, 0o1770);
        mode.set_str_umask("g+s", 0o002).unwrap();
        assert_eq!(mode, Mode::new(0o3770, 0o3770)); // according to chmod behaviour

        let mut mode = Mode::new(0o0, 0o0);
        mode.set_str_umask("=rwx", 0o002).unwrap();
        assert_eq!(mode, Mode::new(0o0775, 0o0777)); // according to chmod behaviour; with umask 0o002

        let mut mode = Mode::new(0o0, 0o0);
        mode.set_str_umask("=s", 0o002).unwrap();
        assert_eq!(mode, Mode::new(0o6000, 0o6777)); // according to chmod behaviour; with umask 0o002

        let mut mode = Mode::new(0o0, 0o0);
        mode.set_str_umask("=", 0o002).unwrap();
        assert_eq!(mode, Mode::new(0o0000, 0o0777)); // according to chmod behaviour; with umask 0o002

        let mut mode = Mode::new(0o777, 0o7777);
        mode.set_str_umask("+w", 0o002).unwrap();
        assert_eq!(mode, Mode::new(0o777, 0o7777));

        let mut mode = Mode::new(0o000, 0o7777);
        mode.set_str_umask("+w", 0o002).unwrap();
        assert_eq!(mode, Mode::new(0o220, 0o7777));

        let mut mode = Mode::new(0o700, 0o700);
        mode.set_str_umask("o=u", 0o002).unwrap();
        assert_eq!(mode, Mode::new(0o707, 0o707)); // according to chmod behaviour

        let mut mode = Mode::new(0o100, 0o100);
        mode.set_str_umask("o=u", 0o002).unwrap();
        assert_eq!(mode, Mode::new(0o101, 0o107)); // according to chmod behaviour

        let mut mode = Mode::new(0o000, 0o000);
        mode.set_str_umask("u=rw,og=u", 0o002).unwrap();
        assert_eq!(mode, Mode::new(0o666, 0o777)); // according to chmod behaviour

        let mut mode = Mode::new(0o700, 0o700);
        mode.set_str_umask("o=u,g=o", 0o002).unwrap();
        assert_eq!(mode, Mode::new(0o777, 0o777)); // according to chmod behaviour

        let mut mode = Mode::new(0o604, 0o777); // file is rw-rw-r--
        mode.set_str("u+r,g+u").unwrap();
        assert_eq!(mode.apply_to(0o664), 0o664); // according to chmod behaviour

        let mut mode = Mode::new(0o664, 0o777); // file is rw-rw-r--
        mode.set_str("u+r,g-u").unwrap(); // g-u will copy rw- from u and unset bot bits
        assert_eq!(mode.apply_to(0o664), 0o604); // according to chmod behaviour

        let dir = 0o040664; // no exec/search
        let file = 0o100664; // no exec/search

        let mut mode = Mode::empty();
        mode.set_str("u+x,g+X").unwrap();

        assert_eq!(mode.apply_to(dir), 0o040774);
        assert_eq!(mode.apply_to(file), 0o100764);
    }

    #[test]
    fn test_set_str_umask_octal() {
        let mut mode = Mode::new(0o000,0o000);
        mode.set_str_umask("=777", 0o002).unwrap();
        assert_eq!(mode, Mode::new(0o777, 0o7777));

        let mut mode = Mode::new(0o000,0o000);
        mode.set_str_umask("+777,-111", 0o002).unwrap();
        assert_eq!(mode, Mode::new(0o666, 0o7777));

        let mut mode = Mode::new(0o000,0o000);
        mode.set_str_umask("=0,+7,-1", 0o002).unwrap();
        assert_eq!(mode, Mode::new(0o006, 0o7777));

        let mut mode = Mode::new(0o000,0o000);
        mode.set_str_umask("a=t,ug=s,+7,-1", 0o002).unwrap();
        assert_eq!(mode, Mode::new(0o7006, 0o7777));
    }

    #[test]
    fn test_from_str() {
        let lock = UMASK_LOCK;
        let guard = lock.lock();
        let umask = umask();

        set_umask(0o002);
        let mut mode = Mode::empty();
        mode.set_str("=rwx").unwrap();
        assert_eq!(mode, Mode::new(0o0775, 0o0777)); // according to chmod behaviour; with umask 0o002

        set_umask(0o022);
        let mut mode = Mode::empty();
        mode.set_str("=rwx").unwrap();
        assert_eq!(mode, Mode::new(0o0755, 0o0777));

        set_umask(0o002);
        let mut mode = Mode::empty();
        mode.set_str("+w").unwrap();
        assert_eq!(mode, Mode::new(0o0220, 0o0222)); // according to chmod behaviour; with umask 0o002

        set_umask(umask);
        drop(guard);
    }

    #[test]
    fn test_file_type() {
        // originally taken with from_path assuming umask 0o002
        assert_eq!(Mode::new(0o040775, 0o177777).file_type(), Some(FileType::Directory)); // from_path("src")
        assert_eq!(Mode::new(0o020666, 0o177777).file_type(), Some(FileType::CharacterDevice)); // from_path("/dev/null")
        assert_eq!(Mode::new(0o060660, 0o177777).file_type(), Some(FileType::BlockDevice)); // from_path("/dev/loop0")
        assert_eq!(Mode::new(0o100644, 0o177777).file_type(), Some(FileType::RegularFile)); // from_path(".gitignore")
        assert_eq!(Mode::new(0o010664, 0o177777).file_type(), Some(FileType::FIFO));
        assert_eq!(Mode::new(0o120777, 0o177777).file_type(), Some(FileType::SymbolicLink)); // from_path("/etc/localtime")
        assert_eq!(Mode::new(0o140777, 0o177777).file_type(), Some(FileType::Socket)); // from_path("/dev/log")
    }

    #[test]
    fn test_apply_to() {
        let dir = 0o040664; // no exec/search
        let file = 0o100664; // no exec/search

        let mut search = Mode::empty();
        search.set_protection(User::Owner, &ProtectionBit::Execute.into());
        search.set_protection(User::Group, &ProtectionBit::Search.into());

        assert_eq!(search.apply_to(dir), 0o040774);
        assert_eq!(search.apply_to(file), 0o100764);
    }

    #[test]
    fn test_to_string() {
        // originally taken with from_path assuming umask 0o002
        assert_eq!(&Mode::new(0o040775, 0o177777).to_string(), "drwxrwxr-x"); // from_path("src")
        assert_eq!(&Mode::new(0o100644, 0o177777).to_string(), "-rw-r--r--"); // from_path(".gitignore")
        assert_eq!(&Mode::new(0o104755, 0o177777).to_string(), "-rwsr-xr-x"); // from_path("/sbin/sudo")
        assert_eq!(&Mode::new(0o041777, 0o177777).to_string(), "drwxrwxrwt"); // from_path("/tmp")

        assert_eq!(&Mode::new(0o7000, 0o7777).to_string(), "?--S--S--T");

        let mut mode = Mode::new(0o7000, 0o7777);
        mode.set_file_type(FileType::Directory);
        assert_eq!(&mode.to_string(), "d--S--S--T");

        let mut mode = Mode::empty();
        mode.set_str("u+x,g+X").unwrap();
        assert_eq!(&mode.to_string(), "?--x--X---");
    }

    #[test]
    fn test_mode_debug() {
        let mode = Mode::new(0o040775, 0o177777); // from_path("src")
        eprintln!("{}", mode);
        eprintln!("{:?}", mode);
        eprintln!("{:#?}", mode);
    }

    #[test]
    #[cfg(target_family = "unix")]
    fn test_set_mode_traits() {
        //TODO: use temp file
        let file = Path::new("LICENSE");
        file.set_mode(0o600).unwrap();
        assert_eq!(file.set_mode("+r").unwrap() & 0o777, 0o644);

        let file = File::open(file).unwrap();
        file.set_mode(0o600).unwrap();
        assert_eq!(file.set_mode("+r").unwrap() & 0o777, 0o644);
        assert_eq!(file.set_mode("g-u").unwrap() & 0o777, 0o604);
        assert_eq!(file.set_mode("g+u").unwrap() & 0o777, 0o664);
    }
}