Takahiro Suzuki | d7bf820 | 2020-12-17 20:21:59 +0900 | [diff] [blame] | 1 | // Package mstypes implements representations of Microsoft types |
| 2 | package mstypes |
| 3 | |
| 4 | import ( |
| 5 | "time" |
| 6 | ) |
| 7 | |
| 8 | /* |
| 9 | FILETIME is a windows data structure. |
| 10 | Ref: https://msdn.microsoft.com/en-us/library/windows/desktop/ms724284%28v=vs.85%29.aspx |
| 11 | It contains two parts that are 32bit integers: |
| 12 | dwLowDateTime |
| 13 | dwHighDateTime |
| 14 | We need to combine these two into one 64bit integer. |
| 15 | This gives the number of 100 nano second period from January 1, 1601, Coordinated Universal Time (UTC) |
| 16 | */ |
| 17 | |
| 18 | const unixEpochDiff = 116444736000000000 |
| 19 | |
| 20 | // FileTime implements the Microsoft FILETIME type https://msdn.microsoft.com/en-us/library/cc230324.aspx |
| 21 | type FileTime struct { |
| 22 | LowDateTime uint32 |
| 23 | HighDateTime uint32 |
| 24 | } |
| 25 | |
| 26 | // Time return a golang Time type from the FileTime |
| 27 | func (ft FileTime) Time() time.Time { |
| 28 | ns := (ft.MSEpoch() - unixEpochDiff) * 100 |
| 29 | return time.Unix(0, int64(ns)).UTC() |
| 30 | } |
| 31 | |
| 32 | // MSEpoch returns the FileTime as a Microsoft epoch, the number of 100 nano second periods elapsed from January 1, 1601 UTC. |
| 33 | func (ft FileTime) MSEpoch() int64 { |
| 34 | return (int64(ft.HighDateTime) << 32) + int64(ft.LowDateTime) |
| 35 | } |
| 36 | |
| 37 | // Unix returns the FileTime as a Unix time, the number of seconds elapsed since January 1, 1970 UTC. |
| 38 | func (ft FileTime) Unix() int64 { |
| 39 | return (ft.MSEpoch() - unixEpochDiff) / 10000000 |
| 40 | } |
| 41 | |
| 42 | // GetFileTime returns a FileTime type from the provided Golang Time type. |
| 43 | func GetFileTime(t time.Time) FileTime { |
| 44 | ns := t.UnixNano() |
| 45 | fp := (ns / 100) + unixEpochDiff |
| 46 | hd := fp >> 32 |
| 47 | ld := fp - (hd << 32) |
| 48 | return FileTime{ |
| 49 | LowDateTime: uint32(ld), |
| 50 | HighDateTime: uint32(hd), |
| 51 | } |
| 52 | } |