using System;
using System.Text;
namespace SharpCompress.Common;
///
/// Specifies the type of encoding to use.
///
public enum EncodingType
{
///
/// Uses the default encoding.
///
Default,
///
/// Uses UTF-8 encoding.
///
UTF8,
}
///
/// Provides extension methods for archive encoding.
///
public static class ArchiveEncodingExtensions
{
#if !NETFRAMEWORK
///
/// Registers the code pages encoding provider.
///
static ArchiveEncodingExtensions() =>
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
#endif
extension(IArchiveEncoding encoding)
{
///
/// Gets the encoding based on the archive encoding settings.
///
/// Whether to use UTF-8.
/// The encoding.
public Encoding GetEncoding(bool useUtf8 = false) =>
encoding.Forced ?? (useUtf8 ? encoding.UTF8 : encoding.Default);
///
/// Gets the decoder function for the archive encoding.
///
/// The decoder function.
public Func GetDecoder() =>
encoding.CustomDecoder
?? (
(bytes, index, count, type) =>
encoding.GetEncoding(type == EncodingType.UTF8).GetString(bytes, index, count)
);
///
/// Encodes a string using the default encoding.
///
/// The string to encode.
/// The encoded bytes.
public byte[] Encode(string str) => encoding.Default.GetBytes(str);
///
/// Decodes bytes using the specified encoding type.
///
/// The bytes to decode.
/// The encoding type.
/// The decoded string.
public string Decode(byte[] bytes, EncodingType type = EncodingType.Default) =>
encoding.Decode(bytes, 0, bytes.Length, type);
///
/// Decodes a portion of bytes using the specified encoding type.
///
/// The bytes to decode.
/// The start index.
/// The length.
/// The encoding type.
/// The decoded string.
public string Decode(
byte[] bytes,
int start,
int length,
EncodingType type = EncodingType.Default
) => encoding.GetDecoder()(bytes, start, length, type);
}
}