uu_ls 0.10.0

ls ~ (uutils) display directory contents
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
// This file is part of the uutils coreutils package.
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.

// spell-checker:ignore (ToDO) somegroup nlink tabsize dired subdired dtype colorterm stringly
// spell-checker:ignore nohash strtime clocale ilog drwxr

use core::ops::RangeInclusive;
use std::cell::LazyCell;
#[cfg(unix)]
use std::fmt::Display;
#[cfg(unix)]
use std::os::unix::fs::{FileTypeExt, MetadataExt};
#[cfg(windows)]
use std::os::windows::fs::MetadataExt;
use std::sync::LazyLock;
use std::time::SystemTime;
/// Show the directory name in the case where several arguments are given to ls
use std::{borrow::Cow, iter};
use std::{
    ffi::{OsStr, OsString},
    fmt::Write as FmtWrite,
    fs::{self, DirEntry, FileType, Metadata},
    io::{BufWriter, Stdout, Write},
};

use ansi_width::ansi_width;
use glob::MatchOptions;
#[cfg(unix)]
use rustc_hash::FxHashMap;
use term_grid::{DEFAULT_SEPARATOR_SIZE, Direction, Filling, Grid, GridOptions};

#[cfg(unix)]
use uucore::entries;
#[cfg(all(unix, not(any(target_os = "android", target_os = "macos"))))]
use uucore::fsxattr::has_acl;
#[cfg(unix)]
use uucore::libc::{dev_t, major, minor};
use uucore::{
    error::UResult,
    format::human::human_readable,
    fs::display_permissions,
    fsext::metadata_get_time,
    i18n::{UEncoding, get_ctype_encoding},
    os_str_as_bytes_lossy,
    quoting_style::{QuotingStyle, locale_aware_escape_dir_name, locale_aware_escape_name},
    show,
    time::{FormatSystemTimeFallback, format_system_time},
};

use crate::colors::{StyleManager, color_name};
use crate::config::Files;
use crate::dired::{self, DiredOutput};
use crate::{Config, ListState, LsError, PathData, get_block_size};
use lscolors::Indicator;

/// Width of the standard Unix permissions string (one file-type char plus
/// nine permission bits, e.g. `drwxr-xr-x`).
const PERMISSIONS_WIDTH: usize = 10;

// Fields that can be removed or added to the long format
pub(crate) struct LongFormat {
    pub(crate) author: bool,
    pub(crate) group: bool,
    pub(crate) owner: bool,
    pub(crate) numeric_uid_gid: bool,
}

pub(crate) struct PaddingCollection {
    #[cfg(unix)]
    pub(crate) inode: usize,
    pub(crate) link_count: usize,
    pub(crate) uname: usize,
    pub(crate) group: usize,
    pub(crate) context: usize,
    pub(crate) size: usize,
    #[cfg(unix)]
    pub(crate) major: usize,
    #[cfg(unix)]
    pub(crate) minor: usize,
    pub(crate) block_size: usize,
    /// Width of the permissions field. [`PERMISSIONS_WIDTH`] by default
    /// (e.g. `drwxr-xr-x`), or one more when any listed item has an ACL or
    /// non-trivial security context and an extra column must be reserved for
    /// the `+`/`.` indicator.
    pub(crate) permissions: usize,
}

pub(crate) struct DisplayItemName {
    pub(crate) displayed: OsString,
    pub(crate) dired_name_len: usize,

    /// Keep track of whether the quoted name started with a quote, so when
    /// needed, we don't have to look at the `displayed` field and skip
    /// the ANSI color codes that were added afterwards.
    pub(crate) starts_with_quote: bool,
}

/// Same as above, but without the `dired_name_len` field.
pub(crate) struct DisplayWithQuote {
    pub(crate) displayed: OsString,
    pub(crate) starts_with_quote: bool,
}

impl From<DisplayItemName> for DisplayWithQuote {
    fn from(
        DisplayItemName {
            displayed,
            dired_name_len: _,
            starts_with_quote,
        }: DisplayItemName,
    ) -> Self {
        Self {
            displayed,
            starts_with_quote,
        }
    }
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum IndicatorStyle {
    Slash,
    FileType,
    Classify,
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum LocaleQuoting {
    Single,
    Double,
}

#[derive(PartialEq, Eq, Debug)]
pub enum Format {
    Columns,
    Long,
    OneLine,
    Across,
    Commas,
}

#[allow(dead_code)]
enum SizeOrDeviceId {
    Size(String),
    Device(String, String),
}

/// or the recursive flag is passed.
///
/// ```no-exec
/// $ ls -R
/// .:                  <- This is printed by this function
/// dir1 file1 file2
///
/// dir1:               <- This as well
/// file11
/// ```
pub fn show_dir_name(
    path_data: &PathData,
    out: &mut BufWriter<Stdout>,
    config: &Config,
) -> std::io::Result<()> {
    let escaped_name = escape_dir_name_with_locale(path_data.path().as_os_str(), config);

    let name = if config.hyperlink && !config.dired {
        create_hyperlink(&escaped_name, path_data)
    } else {
        escaped_name
    };

    write_os_str(out, &name)?;
    write!(out, ":")
}

fn escape_with_locale<F>(name: &OsStr, config: &Config, fallback: F) -> OsString
where
    F: FnOnce(&OsStr, QuotingStyle) -> OsString,
{
    if let Some(locale) = config.locale_quoting {
        locale_quote(name, locale)
    } else {
        fallback(name, config.quoting_style)
    }
}

fn escape_dir_name_with_locale(name: &OsStr, config: &Config) -> OsString {
    escape_with_locale(name, config, locale_aware_escape_dir_name)
}

fn escape_name_with_locale(name: &OsStr, config: &Config) -> OsString {
    escape_with_locale(name, config, locale_aware_escape_name)
}

fn locale_quote(name: &OsStr, style: LocaleQuoting) -> OsString {
    let bytes = os_str_as_bytes_lossy(name);

    // In a UTF-8 locale GNU's locale/clocale quoting uses Unicode quotation
    // marks U+2018 (LEFT) and U+2019 (RIGHT) as delimiters for both styles,
    // keyed off LC_CTYPE. Since the delimiters differ from any ASCII quote,
    // embedded apostrophes and double quotes are left untouched; only control
    // characters, backslashes and invalid bytes are escaped.
    if get_ctype_encoding() == UEncoding::Utf8 {
        let mut quoted = String::with_capacity(name.len() + 6);
        quoted.push('\u{2018}');
        for chunk in bytes.utf8_chunks() {
            for c in chunk.valid().chars() {
                if c == '\\' {
                    quoted.push_str("\\\\");
                } else if c.is_ascii() && c.is_control() {
                    push_basic_escape(&mut quoted, c as u8);
                } else if c.is_control() {
                    // Non-ASCII control characters (the C1 range, e.g.
                    // U+0085 NEL) are not printable; octal-escape their
                    // UTF-8 bytes like GNU does for non-printable chars.
                    let mut buf = [0u8; 4];
                    for &byte in c.encode_utf8(&mut buf).as_bytes() {
                        let _ = write!(quoted, "\\{byte:03o}");
                    }
                } else {
                    quoted.push(c);
                }
            }
            for &byte in chunk.invalid() {
                let _ = write!(quoted, "\\{byte:03o}");
            }
        }
        quoted.push('\u{2019}');
        return OsString::from(quoted);
    }

    let mut quoted = String::with_capacity(name.len() + 2);
    match style {
        LocaleQuoting::Single => quoted.push('\''),
        LocaleQuoting::Double => quoted.push('"'),
    }
    for &byte in bytes.as_ref() {
        push_locale_byte(&mut quoted, byte, style);
    }
    match style {
        LocaleQuoting::Single => quoted.push('\''),
        LocaleQuoting::Double => quoted.push('"'),
    }
    OsString::from(quoted)
}

fn push_locale_byte(buf: &mut String, byte: u8, style: LocaleQuoting) {
    match (style, byte) {
        (LocaleQuoting::Single, b'\'') => buf.push_str("'\\''"),
        (LocaleQuoting::Double, b'"') => buf.push_str("\\\""),
        (_, b'\\') => buf.push_str("\\\\"),
        _ => push_basic_escape(buf, byte),
    }
}

fn push_basic_escape(buf: &mut String, byte: u8) {
    match byte {
        b'\x07' => buf.push_str("\\a"),
        b'\x08' => buf.push_str("\\b"),
        b'\t' => buf.push_str("\\t"),
        b'\n' => buf.push_str("\\n"),
        b'\x0b' => buf.push_str("\\v"),
        b'\x0c' => buf.push_str("\\f"),
        b'\r' => buf.push_str("\\r"),
        b'\x1b' => buf.push_str("\\e"),
        b'"' => buf.push('"'),
        b'\'' => buf.push('\''),
        b if (0x20..=0x7e).contains(&b) => buf.push(b as char),
        _ => {
            let _ = write!(buf, "\\{byte:03o}");
        }
    }
}

pub fn should_display(entry: &DirEntry, config: &Config) -> bool {
    // check if hidden
    if config.files == Files::Normal && is_hidden(entry) {
        return false;
    }

    // check if it is among ignore_patterns
    let options = MatchOptions {
        // setting require_literal_leading_dot to match behavior in GNU ls
        require_literal_leading_dot: true,
        require_literal_separator: false,
        case_sensitive: true,
    };

    let file_name = entry.file_name();
    // If the decoding fails, still match best we can
    // FIXME: use OsStrings or Paths once we have a glob crate that supports it:
    // https://github.com/rust-lang/glob/issues/23
    // https://github.com/rust-lang/glob/issues/78
    // https://github.com/BurntSushi/ripgrep/issues/1250

    let file_name = match file_name.to_str() {
        Some(s) => Cow::Borrowed(s),
        None => file_name.to_string_lossy(),
    };

    !config
        .ignore_patterns
        .iter()
        .any(|p| p.matches_with(&file_name, options))
}

fn display_dir_entry_size(
    entry: &PathData,
    config: &Config,
    state: &mut ListState,
) -> (usize, usize, usize, usize, usize, usize) {
    // TODO: Cache/memorize the display_* results so we don't have to recalculate them.
    if let Some(md) = entry.metadata() {
        let (size_len, major_len, minor_len) = match display_len_or_rdev(md, config) {
            SizeOrDeviceId::Device(major, minor) => {
                (major.len() + minor.len() + 2usize, major.len(), minor.len())
            }
            SizeOrDeviceId::Size(size) => (size.len(), 0usize, 0usize),
        };
        #[cfg(unix)]
        let nlink_len = digits(md.nlink());
        #[cfg(not(unix))]
        let nlink_len = display_symlink_count(md).len();
        (
            nlink_len,
            display_uname(md, config, &mut state.uid_cache).len(),
            display_group(md, config, &mut state.gid_cache).len(),
            size_len,
            major_len,
            minor_len,
        )
    } else {
        (0, 0, 0, 0, 0, 0)
    }
}

#[cfg(unix)]
fn digits(num: u64) -> usize {
    (num.checked_ilog10().unwrap_or(0) + 1) as usize
}

// A simple, performant, ExtendPad trait to add a string to a Vec<u8>, padding with spaces
// on the left or right, without making additional copies, or using formatting functions.
pub trait ExtendPad {
    fn extend_pad_left(&mut self, string: &str, count: usize);
    fn extend_pad_right(&mut self, string: &str, count: usize);
}

impl ExtendPad for Vec<u8> {
    fn extend_pad_left(&mut self, string: &str, count: usize) {
        if string.len() < count {
            self.extend(iter::repeat_n(b' ', count - string.len()));
        }
        self.extend(string.as_bytes());
    }

    fn extend_pad_right(&mut self, string: &str, count: usize) {
        self.extend(string.as_bytes());
        if string.len() < count {
            self.extend(iter::repeat_n(b' ', count - string.len()));
        }
    }
}

// TODO: Consider converting callers to use ExtendPad instead, as it avoids
// additional copies.
fn pad_left(string: &str, count: usize) -> String {
    format!("{string:>count$}")
}

/// Returns the alternate-access indicator that follows the 9-bit permission
/// string in long-format output: `.` for a non-trivial security context, `+`
/// for an ACL, otherwise a space (which acts as a placeholder so columns line
/// up across items that don't carry an indicator themselves).
fn alt_access_indicator(item: &PathData, config: &Config, is_acl_set: bool) -> u8 {
    if item.security_context(config).len() > 1 {
        b'.'
    } else if is_acl_set {
        b'+'
    } else {
        b' '
    }
}

#[allow(clippy::cognitive_complexity)]
pub fn display_items(
    items: &[PathData],
    config: &Config,
    state: &mut ListState,
    dired: &mut DiredOutput,
) -> UResult<()> {
    // `-Z`, `--context`:
    // Display the SELinux security context or '?' if none is found. When used with the `-l`
    // option, print the security context to the left of the size column.

    let quoted = items.iter().any(|item| {
        let name = escape_name_with_locale(item.display_name(), config);
        os_str_starts_with(&name, b"'")
    });

    if config.format == Format::Long {
        let padding_collection = calculate_padding_collection(items, config, state);

        for item in items {
            #[cfg(unix)]
            let should_display_leading_info = config.inode || config.alloc_size;
            #[cfg(not(unix))]
            let should_display_leading_info = config.alloc_size;

            if should_display_leading_info {
                display_additional_leading_info(item, &padding_collection, config, &mut state.out)?;
            }

            display_item_long(item, &padding_collection, config, state, dired, quoted)?;
        }
    } else {
        let mut longest_context_len = 1;
        let prefix_context = if config.context {
            for item in items {
                let context_len = item.security_context(config).len();
                longest_context_len = context_len.max(longest_context_len);
            }
            Some(longest_context_len)
        } else {
            None
        };

        let padding = calculate_padding_collection(items, config, state);

        // we need to apply normal color to non filename output
        if let Some(style_manager) = &mut state.style_manager {
            write!(state.out, "{}", style_manager.apply_normal())?;
        }

        let mut names_vec: Vec<DisplayWithQuote> = Vec::with_capacity(items.len());

        #[cfg(unix)]
        let should_display_leading_info = config.inode || config.alloc_size;
        #[cfg(not(unix))]
        let should_display_leading_info = config.alloc_size;

        for i in items {
            let more_info = if should_display_leading_info {
                let mut s = Vec::new();
                display_additional_leading_info(i, &padding, config, &mut s)?;
                Some(String::from_utf8(s).unwrap()) // Should always be UTF-8
            } else {
                None
            };
            // it's okay to set current column to zero which is used to decide
            // whether text will wrap or not, because when format is grid or
            // column ls will try to place the item name in a new line if it
            // wraps.
            let cell = display_item_name(
                i,
                config,
                prefix_context,
                more_info,
                state.style_manager.as_mut(),
                LazyCell::new(|| 0),
            );

            names_vec.push(cell.into());
        }

        let mut names = names_vec.into_iter();

        match config.format {
            Format::Columns => {
                display_grid(
                    names,
                    config.width,
                    Direction::TopToBottom,
                    &mut state.out,
                    quoted,
                    config.tab_size,
                )?;
            }
            Format::Across => {
                display_grid(
                    names,
                    config.width,
                    Direction::LeftToRight,
                    &mut state.out,
                    quoted,
                    config.tab_size,
                )?;
            }
            Format::Commas => {
                let mut current_col = 0;
                if let Some(name) = names.next() {
                    write_os_str(&mut state.out, &name.displayed)?;
                    current_col = ansi_width(&name.displayed.to_string_lossy()) as u16 + 2;
                }
                for name in names {
                    let name_width = ansi_width(&name.displayed.to_string_lossy()) as u16;
                    // If the width is 0 we print one single line
                    if config.width != 0 && current_col + name_width + 1 > config.width {
                        current_col = name_width + 2;
                        writeln!(state.out, ",")?;
                    } else {
                        current_col += name_width + 2;
                        write!(state.out, ", ")?;
                    }
                    write_os_str(&mut state.out, &name.displayed)?;
                }
                // Current col is never zero again if names have been printed.
                // So we print a newline.
                if current_col > 0 {
                    write!(state.out, "{}", config.line_ending)?;
                }
            }
            _ => {
                for name in names {
                    write_os_str(&mut state.out, &name.displayed)?;
                    write!(state.out, "{}", config.line_ending)?;
                }
            }
        }
    }

    Ok(())
}

fn display_grid(
    names: impl Iterator<Item = DisplayWithQuote>,
    width: u16,
    direction: Direction,
    out: &mut BufWriter<Stdout>,
    quoted: bool,
    tab_size: usize,
) -> UResult<()> {
    if width == 0 {
        // If the width is 0 we print one single line
        let mut printed_something = false;
        for name in names {
            if printed_something {
                write!(out, "  ")?;
            }
            printed_something = true;
            write_os_str(out, &name.displayed)?;
        }
        if printed_something {
            writeln!(out)?;
        }
    } else {
        let names: Vec<String> = {
            let mut buf = Vec::new();
            names
                .map(|din| {
                    // In case some names are quoted, GNU adds a space before each
                    // entry that does not start with a quote to make it prettier
                    // on multiline.
                    //
                    // Example:
                    // ```
                    // $ ls
                    // 'a\nb'   bar
                    //  foo     baz
                    // ^       ^
                    // These spaces is added
                    // ```
                    // FIXME: the Grid crate only supports &str, so can't display raw bytes
                    buf.clear();
                    if quoted && !din.starts_with_quote {
                        buf.push(b' ');
                    }
                    buf.extend(din.displayed.as_encoded_bytes());
                    String::from_utf8_lossy(&buf).into_owned()
                })
                .collect()
        };

        // Since tab_size=0 means no \t, use Spaces separator for optimization.
        let filling = match tab_size {
            0 => Filling::Spaces(DEFAULT_SEPARATOR_SIZE),
            _ => Filling::Tabs {
                spaces: DEFAULT_SEPARATOR_SIZE,
                tab_size,
            },
        };

        let grid = Grid::new(
            names,
            GridOptions {
                filling,
                direction,
                width: width as usize,
            },
        );
        write!(out, "{grid}")?;
    }
    Ok(())
}

fn display_additional_leading_info(
    item: &PathData,
    padding: &PaddingCollection,
    config: &Config,
    out: &mut impl Write,
) -> UResult<()> {
    #[cfg(unix)]
    {
        if config.inode {
            let inode = padding.inode;
            if let Some(md) = item.metadata() {
                write!(out, "{:>inode$} ", display_inode(md))?;
            } else {
                write!(out, "{:>inode$} ", '?')?;
            }
        }
    }

    if config.alloc_size {
        let s: Cow<'_, str> = if let Some(md) = item.metadata() {
            display_size(get_block_size(md, config), config).into()
        } else {
            "?".into()
        };
        // extra space is insert to align the sizes, as needed for all formats, except for the comma format.
        if config.format == Format::Commas {
            out.write_all(s.as_bytes())?;
            out.write_all(b" ")?;
        } else {
            let block_size = padding.block_size;
            write!(out, "{s:>block_size$} ")?;
        }
    }

    Ok(())
}

// Currently getpwuid is `linux` target only. If it's broken state.out into
// a posix-compliant attribute this can be updated...
#[cfg(unix)]
fn display_uname<'a>(
    metadata: &Metadata,
    config: &Config,
    uid_cache: &'a mut FxHashMap<u32, String>,
) -> &'a String {
    let uid = metadata.uid();

    uid_cache.entry(uid).or_insert_with(|| {
        if config.long.numeric_uid_gid {
            uid.to_string()
        } else {
            entries::uid2usr(uid).unwrap_or_else(|_| uid.to_string())
        }
    })
}

#[cfg(unix)]
fn display_group<'a>(
    metadata: &Metadata,
    config: &Config,
    gid_cache: &'a mut FxHashMap<u32, String>,
) -> &'a String {
    let gid = metadata.gid();
    gid_cache.entry(gid).or_insert_with(|| {
        if config.long.numeric_uid_gid {
            gid.to_string()
        } else {
            entries::gid2grp(gid).unwrap_or_else(|_| gid.to_string())
        }
    })
}

#[cfg(not(unix))]
fn display_uname(_metadata: &Metadata, config: &Config, _uid_cache: &mut ()) -> &'static str {
    // No uid to report on this platform; with `-n` fall back to "0" so the
    // output still looks numeric, matching the intent of --numeric-uid-gid.
    if config.long.numeric_uid_gid {
        "0"
    } else {
        "somebody"
    }
}

#[cfg(not(unix))]
fn display_group(_metadata: &Metadata, config: &Config, _gid_cache: &mut ()) -> &'static str {
    if config.long.numeric_uid_gid {
        return "0";
    }
    "somegroup"
}

fn display_date(
    metadata: &Metadata,
    config: &Config,
    recent_time_range: &RangeInclusive<SystemTime>,
    out: &mut Vec<u8>,
) -> UResult<()> {
    let Some(time) = metadata_get_time(metadata, config.time) else {
        out.extend(b"???");
        return Ok(());
    };

    // Use "recent" format if the given date is considered recent (i.e., in the last 6 months),
    // or if no "older" format is available.
    let fmt = match &config.time_format_older {
        Some(time_format_older) if !recent_time_range.contains(&time) => time_format_older,
        _ => &config.time_format_recent,
    };

    format_system_time(out, time, fmt, FormatSystemTimeFallback::Integer)
}

fn display_len_or_rdev(metadata: &Metadata, config: &Config) -> SizeOrDeviceId {
    #[cfg(unix)]
    {
        let ft = metadata.file_type();
        if ft.is_char_device() || ft.is_block_device() {
            // A type cast is needed here as the `dev_t` type varies across OSes.
            let dev = metadata.rdev() as dev_t;
            let major = major(dev);
            let minor = minor(dev);
            return SizeOrDeviceId::Device(major.to_string(), minor.to_string());
        }
    }
    let len_adjusted = {
        let d = metadata.len() / config.file_size_block_size;
        let r = metadata.len() % config.file_size_block_size;
        if r == 0 { d } else { d + 1 }
    };
    SizeOrDeviceId::Size(display_size(len_adjusted, config))
}

pub fn display_size(size: u64, config: &Config) -> String {
    human_readable(size, config.size_format)
}

/// Takes a [`PathData`] struct and returns a cell with a name ready for displaying.
///
/// This function relies on the following parameters in the provided `&Config`:
/// * `config.quoting_style` to decide how we will escape `name` using [`locale_aware_escape_name`].
/// * `config.inode` decides whether to display inode numbers beside names using [`display_inode`].
/// * `config.color` decides whether it's going to color `name` using [`color_name`].
/// * `config.indicator_style` to append specific characters to `name` using [`classify_file`].
/// * `config.format` to display symlink targets if `Format::Long`. This function is also
///   responsible for coloring symlink target names if `config.color` is specified.
/// * `config.context` to prepend security context to `name` if compiled with `feat_selinux`.
/// * `config.hyperlink` decides whether to hyperlink the item
///
/// Note that non-unicode sequences in symlink targets are dealt with using
/// [`std::path::Path::to_string_lossy`].
#[allow(clippy::cognitive_complexity)]
fn display_item_name(
    path: &PathData,
    config: &Config,
    prefix_context: Option<usize>,
    more_info: Option<String>,
    mut style_manager: Option<&mut StyleManager>,
    current_column: LazyCell<usize, impl FnOnce() -> usize>,
) -> DisplayItemName {
    // This is our return value. We start by `&path.display_name` and modify it along the way.
    let mut name = escape_name_with_locale(path.display_name(), config);
    let starts_with_quote = os_str_starts_with(&name, b"'") || os_str_starts_with(&name, b"\"");

    let is_wrap =
        |namelen: usize| config.width != 0 && *current_column + namelen > config.width.into();

    if config.hyperlink {
        name = create_hyperlink(&name, path);
    }

    if let Some(style_manager) = style_manager.as_mut() {
        let len = name.len();
        name = color_name(name, path, style_manager, None, is_wrap(len));
    }

    if config.format != Format::Long
        && let Some(info) = more_info
    {
        let old_name = name;
        name = info.into();
        name.push(&old_name);
    }

    let is_long_symlink = config.format == Format::Long
        && path.file_type().is_some_and(FileType::is_symlink)
        && !path.must_dereference;

    if !is_long_symlink && let Some(c) = indicator_char(path, config.indicator_style) {
        let _ = name.write_char(c);
    }

    let dired_name_len = if config.dired { name.len() } else { 0 };

    if is_long_symlink {
        let has_mi_or_or = style_manager.as_ref().is_some_and(|sm| {
            sm.has_indicator_style(Indicator::OrphanedSymbolicLink)
                || sm.has_indicator_style(Indicator::MissingFile)
        });
        // Only stat symlink target when:
        // 1. Color is enabled AND LS_COLORS has mi= or or=, OR
        // 2. Long format AND (--classify or --file-type)
        let should_stat_target = has_mi_or_or
            || matches!(
                config.indicator_style,
                Some(IndicatorStyle::Classify) | Some(IndicatorStyle::FileType)
            );

        match path.path().read_link() {
            Ok(target_path) => {
                name.push(" -> ");

                // We might as well color the symlink output after the arrow.
                // This makes extra system calls, but provides important information that
                // people run `ls -l --color` are very interested in.
                let escaped_target = escape_name_with_locale(target_path.as_os_str(), config);

                // We get the absolute path to be able to construct PathData with valid Metadata.
                // This is because relative symlinks will fail to get_metadata.
                if should_stat_target {
                    let absolute_target = if target_path.is_relative() {
                        match path.path().parent() {
                            Some(p) => &p.join(&target_path),
                            None => &target_path,
                        }
                    } else {
                        &target_path
                    };
                    match fs::canonicalize(absolute_target) {
                        Ok(resolved_target) => {
                            let target_data = PathData::new(
                                resolved_target.as_path().into(),
                                None,
                                target_path.file_name().map(Cow::Borrowed),
                                config,
                                false,
                                false,
                            );

                            let target_display = if let Some(style_manager) = style_manager {
                                let md = match target_data.metadata() {
                                    Some(md) => Some(Cow::Borrowed(md)),
                                    None => {
                                        target_data.p_buf.symlink_metadata().ok().map(Cow::Owned)
                                    }
                                };
                                // Check if the target actually needs coloring
                                if style_manager
                                    .colors
                                    .style_for_path_with_metadata(&target_data.p_buf, md.as_deref())
                                    .is_some()
                                {
                                    // Only apply coloring if there's actually a style
                                    color_name(
                                        escaped_target,
                                        &target_data,
                                        style_manager,
                                        None,
                                        is_wrap(name.len()),
                                    )
                                } else {
                                    // For regular files with no coloring, just use plain text
                                    escaped_target
                                }
                            } else {
                                escaped_target
                            };
                            name.push(target_display);
                            // Add appropriate indicator based on indicator_style
                            if let Some(c) = indicator_char(&target_data, config.indicator_style) {
                                let _ = name.write_char(c);
                            }
                        }
                        Err(_) => {
                            if let Some(style_manager) = &mut style_manager {
                                name.push(style_manager.apply_missing_target_style(
                                    escaped_target,
                                    is_wrap(name.len()),
                                ));
                            } else {
                                // If no coloring is required, we just use target as is.
                                // with the right quoting
                                name.push(escaped_target);
                            }
                        }
                    }
                } else {
                    name.push(&escaped_target);
                }
            }
            Err(err) => {
                show!(LsError::IOErrorContext(
                    path.path().to_path_buf(),
                    err,
                    false
                ));
            }
        }
    }

    // Prepend the security context to the `name` and adjust `width` in order
    // to get correct alignment from later calls to`display_grid()`.
    if config.context
        && let Some(pad_count) = prefix_context
    {
        let security_context: Cow<'_, str> = if matches!(config.format, Format::Commas) {
            path.security_context(config).into()
        } else {
            pad_left(path.security_context(config), pad_count).into()
        };

        let old_name = name;
        name = OsString::with_capacity(security_context.len() + 1 + old_name.len());
        name.push(security_context.as_ref());
        name.push(" ");
        name.push(old_name);
    }

    DisplayItemName {
        displayed: name,
        dired_name_len,
        starts_with_quote,
    }
}

/// This writes to the [`BufWriter`] `state.out` a single string of the output of `ls -l`.
///
/// It writes the following keys, in order:
/// * `inode` ([`display_inode`], config-optional)
/// * `permissions` ([`display_permissions`])
/// * `symlink_count` ([`display_symlink_count`])
/// * `owner` ([`display_uname`], config-optional)
/// * `group` ([`display_group`], config-optional)
/// * `author` ([`display_uname`], config-optional)
/// * `size / rdev` ([`display_len_or_rdev`])
/// * `system_time` ([`display_date`])
/// * `item_name` ([`display_item_name`])
///
/// This function needs to display information in columns:
/// * permissions and `system_time` are already guaranteed to be pre-formatted in fixed length.
/// * `item_name` is the last column and is left-aligned.
/// * Everything else needs to be padded using [`pad_left`].
///
/// That's why we have the parameters:
/// ```txt
///    longest_link_count_len: usize,
///    longest_uname_len: usize,
///    longest_group_len: usize,
///    longest_context_len: usize,
///    longest_size_len: usize,
/// ```
/// that decide the maximum possible character count of each field.
#[allow(clippy::write_literal)]
#[allow(clippy::cognitive_complexity)]
fn display_item_long(
    item: &PathData,
    padding: &PaddingCollection,
    config: &Config,
    state: &mut ListState,
    dired: &mut DiredOutput,
    quoted: bool,
) -> UResult<()> {
    // apply normal color to non filename outputs
    if let Some(style_manager) = &mut state.style_manager {
        state
            .display_buf
            .extend(style_manager.apply_normal().as_bytes());
    }
    if config.dired {
        state.display_buf.extend(b"  ");
    }
    if let Some(md) = item.metadata() {
        #[cfg(any(not(unix), target_os = "android", target_os = "macos"))]
        // TODO: See how Mac should work here
        let is_acl_set = false;
        #[cfg(all(unix, not(any(target_os = "android", target_os = "macos"))))]
        let is_acl_set = has_acl(item.path());
        state
            .display_buf
            .extend(display_permissions(md, true).as_bytes());
        if padding.permissions > PERMISSIONS_WIDTH {
            state
                .display_buf
                .push(alt_access_indicator(item, config, is_acl_set));
        }
        state.display_buf.push(b' ');
        state
            .display_buf
            .extend_pad_left(&display_symlink_count(md), padding.link_count);

        if config.long.owner {
            state.display_buf.push(b' ');
            state.display_buf.extend_pad_right(
                display_uname(md, config, &mut state.uid_cache),
                padding.uname,
            );
        }

        if config.long.group {
            state.display_buf.push(b' ');
            state.display_buf.extend_pad_right(
                display_group(md, config, &mut state.gid_cache),
                padding.group,
            );
        }

        if config.context {
            state.display_buf.push(b' ');
            state
                .display_buf
                .extend_pad_right(item.security_context(config), padding.context);
        }

        // Author is only different from owner on GNU/Hurd, so we reuse
        // the owner, since GNU/Hurd is not currently supported by Rust.
        if config.long.author {
            state.display_buf.push(b' ');
            state.display_buf.extend_pad_right(
                display_uname(md, config, &mut state.uid_cache),
                padding.uname,
            );
        }

        match display_len_or_rdev(md, config) {
            SizeOrDeviceId::Size(size) => {
                state.display_buf.push(b' ');
                state.display_buf.extend_pad_left(&size, padding.size);
            }
            SizeOrDeviceId::Device(major, minor) => {
                state.display_buf.push(b' ');
                state.display_buf.extend_pad_left(
                    &major,
                    #[cfg(not(unix))]
                    0usize,
                    #[cfg(unix)]
                    padding.major.max(
                        padding
                            .size
                            .saturating_sub(padding.minor.saturating_add(2usize)),
                    ),
                );
                state.display_buf.extend(b", ");
                state.display_buf.extend_pad_left(
                    &minor,
                    #[cfg(not(unix))]
                    0usize,
                    #[cfg(unix)]
                    padding.minor,
                );
            }
        }

        state.display_buf.push(b' ');
        display_date(md, config, &state.recent_time_range, &mut state.display_buf)?;
        state.display_buf.push(b' ');

        let item_display = display_item_name(
            item,
            config,
            None,
            None,
            state.style_manager.as_mut(),
            LazyCell::new(|| ansi_width(&String::from_utf8_lossy(&state.display_buf))),
        );

        let needs_space = quoted && !item_display.starts_with_quote;

        if config.dired {
            let mut dired_name_len = item_display.dired_name_len;
            if needs_space {
                dired_name_len += 1;
            }
            let displayed_len = item_display.displayed.len() + usize::from(needs_space);
            update_dired_for_item(
                dired,
                state.display_buf.len(),
                displayed_len,
                dired_name_len,
            );
        }

        let item_name = item_display.displayed;
        let displayed_item = if needs_space {
            let mut ret = OsString::with_capacity(item_name.len() + 1);
            let _ = ret.write_char(' ');
            ret.push(&item_name);
            ret
        } else {
            item_name
        };

        write_os_str(&mut state.display_buf, &displayed_item)?;
        state.display_buf.push(config.line_ending as u8);
    } else {
        #[cfg(unix)]
        let leading_char = {
            if let Some(ft) = item.file_type() {
                if ft.is_char_device() {
                    'c'
                } else if ft.is_block_device() {
                    'b'
                } else if ft.is_symlink() {
                    'l'
                } else if ft.is_dir() {
                    'd'
                } else {
                    '-'
                }
            } else if item.is_dangling_link() {
                'l'
            } else {
                '-'
            }
        };
        #[cfg(not(unix))]
        let leading_char = {
            if let Some(ft) = item.file_type() {
                if ft.is_symlink() {
                    'l'
                } else if ft.is_dir() {
                    'd'
                } else {
                    '-'
                }
            } else if item.is_dangling_link() {
                'l'
            } else {
                '-'
            }
        };

        state.display_buf.push(leading_char as u8);
        state.display_buf.extend(b"?????????");
        if padding.permissions > PERMISSIONS_WIDTH {
            // Metadata is unknown, so we can't probe for ACLs; only the
            // security-context indicator is detectable here.
            state
                .display_buf
                .push(alt_access_indicator(item, config, false));
        }
        state.display_buf.push(b' ');
        state.display_buf.extend_pad_left("?", padding.link_count);

        if config.long.owner {
            state.display_buf.push(b' ');
            state.display_buf.extend_pad_right("?", padding.uname);
        }

        if config.long.group {
            state.display_buf.push(b' ');
            state.display_buf.extend_pad_right("?", padding.group);
        }

        if config.context {
            state.display_buf.push(b' ');
            state
                .display_buf
                .extend_pad_right(item.security_context(config), padding.context);
        }

        // Author is only different from owner on GNU/Hurd, so we reuse
        // the owner, since GNU/Hurd is not currently supported by Rust.
        if config.long.author {
            state.display_buf.push(b' ');
            state.display_buf.extend_pad_right("?", padding.uname);
        }

        let displayed_item = display_item_name(
            item,
            config,
            None,
            None,
            state.style_manager.as_mut(),
            LazyCell::new(|| ansi_width(&String::from_utf8_lossy(&state.display_buf))),
        );
        let date_len = 12;

        state.display_buf.push(b' ');
        state.display_buf.extend_pad_left("?", padding.size);
        state.display_buf.push(b' ');
        state.display_buf.extend_pad_left("?", date_len);
        state.display_buf.push(b' ');

        if config.dired {
            update_dired_for_item(
                dired,
                state.display_buf.len(),
                displayed_item.displayed.len(),
                displayed_item.dired_name_len,
            );
        }
        let displayed_item = displayed_item.displayed;
        write_os_str(&mut state.display_buf, &displayed_item)?;
        state.display_buf.push(config.line_ending as u8);
    }
    state.out.write_all(&state.display_buf)?;
    state.display_buf.clear();

    Ok(())
}

fn indicator_char(path: &PathData, style: Option<IndicatorStyle>) -> Option<char> {
    let style = style?;
    let sym = classify_file(path);

    match style {
        IndicatorStyle::Classify => sym,
        IndicatorStyle::FileType => sym.filter(|&c| c != '*'),
        IndicatorStyle::Slash => sym.filter(|&c| c == '/'),
    }
}

fn classify_file(path: &PathData) -> Option<char> {
    let file_type = path.file_type()?;

    if file_type.is_dir() {
        Some('/')
    } else if file_type.is_symlink() {
        Some('@')
    } else {
        #[cfg(unix)]
        {
            if file_type.is_socket() {
                Some('=')
            } else if file_type.is_fifo() {
                Some('|')
                // Safe unwrapping if the file was removed between listing and display
                // See https://github.com/uutils/coreutils/issues/5371
            } else if path.is_executable_file() {
                Some('*')
            } else {
                None
            }
        }
        #[cfg(not(unix))]
        None
    }
}

fn create_hyperlink(name: &OsStr, path: &PathData) -> OsString {
    // The `hostname` crate does not support WASI (no OS-level hostname API),
    // so we use an empty string for hyperlinks on WASI.
    #[cfg(not(target_os = "wasi"))]
    static HOSTNAME: LazyLock<OsString> = LazyLock::new(|| hostname::get().unwrap_or_default());
    #[cfg(target_os = "wasi")]
    static HOSTNAME: LazyLock<OsString> = LazyLock::new(OsString::new);

    // OSC 8 hyperlink format: \x1b]8;;URL\x1b\\TEXT\x1b]8;;\x1b\\
    // \x1b = ESC, \x1b\\ = ESC backslash
    // FIXME: switch to constants once OsStr::new() is const-stable and over our MSRV.
    let osc_8_head = OsStr::new("\x1b]8;;file://");
    let osc_8_tail = OsStr::new("\x1b]8;;\x1b\\");
    let esc_bl = OsStr::new("\x1b\\");

    let absolute_path = fs::canonicalize(path.path()).unwrap_or_default();
    let mut ret = OsString::with_capacity(
        osc_8_head.len()
            + osc_8_tail.len()
            + HOSTNAME.len()
            + esc_bl.len()
            + absolute_path.as_os_str().len(),
    );
    ret.push(osc_8_head);
    ret.push(HOSTNAME.as_os_str());

    // a set of safe ASCII bytes that don't need encoding
    #[cfg(not(target_os = "windows"))]
    let unencoded = |c| matches!(c, '_' | '-' | '.' | '~' | '/');
    #[cfg(target_os = "windows")]
    let unencoded = |c| matches!(c, '_' | '-' | '.' | '~' | '/' | '\\' | ':');

    for &b in absolute_path.as_os_str().as_encoded_bytes() {
        if b.is_ascii_alphanumeric() || unencoded(b as char) {
            let _ = ret.write_char(b as char);
        } else {
            let _ = write!(ret, "%{b:02x}");
        }
    }

    ret.push(esc_bl);
    ret.push(name);
    ret.push(osc_8_tail);

    ret
}

fn is_hidden(file_path: &DirEntry) -> bool {
    #[cfg(windows)]
    {
        let metadata = file_path.metadata().unwrap();
        let attr = metadata.file_attributes();
        (attr & 0x2) > 0
    }
    #[cfg(not(windows))]
    {
        file_path.file_name().as_encoded_bytes().starts_with(b".")
    }
}

fn update_dired_for_item(
    dired: &mut DiredOutput,
    output_display_len: usize,
    displayed_len: usize,
    dired_name_len: usize,
) {
    let line_len = output_display_len + displayed_len + 1; // +1 for line ending
    dired::calculate_and_update_positions(dired, output_display_len, dired_name_len, line_len);
}

#[cfg(unix)]
fn display_symlink_count(metadata: &Metadata) -> String {
    metadata.nlink().to_string()
}

#[cfg(unix)]
fn display_inode(metadata: &Metadata) -> impl Display {
    metadata.ino().to_string()
}

#[cfg(unix)]
fn calculate_padding_collection(
    items: &[PathData],
    config: &Config,
    state: &mut ListState,
) -> PaddingCollection {
    let mut padding_collections = PaddingCollection {
        inode: 1,
        link_count: 1,
        uname: 1,
        group: 1,
        context: 1,
        size: 1,
        major: 1,
        minor: 1,
        block_size: 1,
        permissions: PERMISSIONS_WIDTH,
    };

    for item in items {
        #[cfg(unix)]
        if config.inode {
            let inode_len = if let Some(md) = item.metadata() {
                digits(md.ino())
            } else {
                continue;
            };
            padding_collections.inode = inode_len.max(padding_collections.inode);
        }

        if config.alloc_size
            && let Some(md) = item.metadata()
        {
            let block_size_len = display_size(get_block_size(md, config), config).len();
            padding_collections.block_size = block_size_len.max(padding_collections.block_size);
        }

        if config.format == Format::Long {
            let context_len = item.security_context(config).len();
            let (link_count_len, uname_len, group_len, size_len, major_len, minor_len) =
                display_dir_entry_size(item, config, state);
            padding_collections.link_count = link_count_len.max(padding_collections.link_count);
            padding_collections.uname = uname_len.max(padding_collections.uname);
            padding_collections.group = group_len.max(padding_collections.group);
            if config.context {
                padding_collections.context = context_len.max(padding_collections.context);
            }

            // If any item has an ACL or non-trivial security context, widen
            // the permissions column by one to reserve space for the `+`/`.`
            // indicator.
            {
                #[cfg(any(not(unix), target_os = "android", target_os = "macos"))]
                // TODO: See how Mac should work here
                let is_acl_set = false;
                #[cfg(all(unix, not(any(target_os = "android", target_os = "macos"))))]
                let is_acl_set = has_acl(item.path());
                if context_len > 1 || is_acl_set {
                    padding_collections.permissions = PERMISSIONS_WIDTH + 1;
                }
            }

            if items.len() == 1usize {
                padding_collections.size = 0usize;
                padding_collections.major = 0usize;
                padding_collections.minor = 0usize;
            } else {
                padding_collections.major = major_len.max(padding_collections.major);
                padding_collections.minor = minor_len.max(padding_collections.minor);
                padding_collections.size = size_len
                    .max(padding_collections.size)
                    .max(padding_collections.major);
            }
        }
    }

    padding_collections
}

#[cfg(not(unix))]
fn display_symlink_count(_metadata: &Metadata) -> String {
    // Currently not sure of how to get this on Windows, so I'm punting.
    // Git Bash looks like it may do the same thing.
    String::from("1")
}

#[cfg(not(unix))]
fn calculate_padding_collection(
    items: &[PathData],
    config: &Config,
    state: &mut ListState,
) -> PaddingCollection {
    let mut padding_collections = PaddingCollection {
        link_count: 1,
        uname: 1,
        group: 1,
        context: 1,
        size: 1,
        block_size: 1,
        permissions: PERMISSIONS_WIDTH,
    };

    for item in items {
        if config.alloc_size
            && let Some(md) = item.metadata()
        {
            let block_size_len = display_size(get_block_size(md, config), config).len();
            padding_collections.block_size = block_size_len.max(padding_collections.block_size);
        }

        let context_len = item.security_context(config).len();
        let (link_count_len, uname_len, group_len, size_len, _major_len, _minor_len) =
            display_dir_entry_size(item, config, state);
        padding_collections.link_count = link_count_len.max(padding_collections.link_count);
        padding_collections.uname = uname_len.max(padding_collections.uname);
        padding_collections.group = group_len.max(padding_collections.group);
        if config.context {
            padding_collections.context = context_len.max(padding_collections.context);
        }
        padding_collections.size = size_len.max(padding_collections.size);
    }

    padding_collections
}

fn os_str_starts_with(haystack: &OsStr, needle: &[u8]) -> bool {
    os_str_as_bytes_lossy(haystack).starts_with(needle)
}

fn write_os_str<W: Write>(writer: &mut W, string: &OsStr) -> std::io::Result<()> {
    writer.write_all(&os_str_as_bytes_lossy(string))
}