Files
sharpcompress/src/SharpCompress/Common/ArchiveEncoding.cs

58 lines
1.8 KiB
C#
Raw Normal View History

2022-12-20 15:06:44 +00:00
using System;
using System.Text;
2015-12-30 11:19:42 +00:00
2022-12-20 15:06:44 +00:00
namespace SharpCompress.Common;
public class ArchiveEncoding
2015-12-30 11:19:42 +00:00
{
2022-12-20 15:06:44 +00:00
/// <summary>
/// Default encoding to use when archive format doesn't specify one.
/// </summary>
2024-04-22 15:17:24 +01:00
public Encoding? Default { get; set; }
2015-12-30 11:19:42 +00:00
2022-12-20 15:06:44 +00:00
/// <summary>
/// ArchiveEncoding used by encryption schemes which don't comply with RFC 2898.
/// </summary>
2024-04-22 15:17:24 +01:00
public Encoding? Password { get; set; }
2015-12-30 11:19:42 +00:00
2022-12-20 15:06:44 +00:00
/// <summary>
/// Set this encoding when you want to force it for all encoding operations.
/// </summary>
public Encoding? Forced { get; set; }
2022-12-20 15:06:44 +00:00
/// <summary>
/// Set this when you want to use a custom method for all decoding operations.
/// </summary>
/// <returns>string Func(bytes, index, length)</returns>
public Func<byte[], int, int, string>? CustomDecoder { get; set; }
2023-03-21 13:14:08 +00:00
public ArchiveEncoding()
: this(Encoding.Default, Encoding.Default) { }
2022-12-20 13:45:47 +00:00
2022-12-20 15:06:44 +00:00
public ArchiveEncoding(Encoding def, Encoding password)
{
Default = def;
Password = password;
}
2021-10-01 16:34:00 +00:00
#if !NETFRAMEWORK
2022-12-20 15:20:49 +00:00
static ArchiveEncoding() => Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
2021-10-01 16:34:00 +00:00
#endif
2018-04-29 16:27:26 +01:00
2022-12-20 15:20:49 +00:00
public string Decode(byte[] bytes) => Decode(bytes, 0, bytes.Length);
2022-12-20 15:20:49 +00:00
public string Decode(byte[] bytes, int start, int length) =>
GetDecoder().Invoke(bytes, start, length);
2018-04-29 16:27:26 +01:00
2022-12-20 15:20:49 +00:00
public string DecodeUTF8(byte[] bytes) => Encoding.UTF8.GetString(bytes, 0, bytes.Length);
2022-12-20 15:20:49 +00:00
public byte[] Encode(string str) => GetEncoding().GetBytes(str);
2022-12-20 15:20:49 +00:00
public Encoding GetEncoding() => Forced ?? Default ?? Encoding.UTF8;
2024-04-22 15:17:24 +01:00
public Encoding GetPasswordEncoding() => Password ?? Encoding.UTF8;
2022-12-20 15:20:49 +00:00
public Func<byte[], int, int, string> GetDecoder() =>
CustomDecoder ?? ((bytes, index, count) => GetEncoding().GetString(bytes, index, count));
}