/IronPython_2_0/Src/IronPython/Runtime/Operations/StringOps.cs
C# | 2412 lines | 2117 code | 233 blank | 62 comment | 354 complexity | 7f5752d01ce870c21a534be4bfc5b52d MD5 | raw file
Possible License(s): GPL-2.0, MPL-2.0-no-copyleft-exception, CPL-1.0, CC-BY-SA-3.0, BSD-3-Clause, ISC, AGPL-3.0, LGPL-2.1, Apache-2.0
Large files files are truncated, but you can click here to view the full file
- /* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Microsoft Public License. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Microsoft Public License, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Microsoft Public License.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
- using System; using Microsoft;
- using System.Collections;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Globalization;
- using System.Reflection;
- using System.Runtime.InteropServices;
- using System.Text;
- using IronPython.Runtime.Exceptions;
- using IronPython.Runtime.Types;
- using Microsoft.Scripting;
- using Microsoft.Scripting.Math;
- using Microsoft.Scripting.Runtime;
- using Microsoft.Scripting.Utils;
- using SpecialNameAttribute = System.Runtime.CompilerServices.SpecialNameAttribute;
-
- namespace IronPython.Runtime.Operations {
- /// <summary>
- /// ExtensibleString is the base class that is used for types the user defines
- /// that derive from string. It carries along with it the string's value and
- /// our converter recognizes it as a string.
- /// </summary>
- public class ExtensibleString : Extensible<string>, ICodeFormattable, IValueEquality, ISequence {
- public ExtensibleString() : base(String.Empty) { }
- public ExtensibleString(string self) : base(self) { }
-
- public override string ToString() {
- return Value;
- }
-
- #region ICodeFormattable Members
-
- public virtual string/*!*/ __repr__(CodeContext/*!*/ context) {
- return StringOps.Quote(Value);
- }
-
- #endregion
-
- [return: MaybeNotImplemented]
- public object __eq__(object other) {
- if (other is string || other is ExtensibleString)
- return RuntimeHelpers.BooleanToObject(((IValueEquality)this).ValueEquals(other));
-
- return NotImplementedType.Value;
- }
-
- [return: MaybeNotImplemented]
- public object __ne__(object other) {
- object res = __eq__(other);
- if (res != NotImplementedType.Value) return PythonOps.Not(res);
-
- return res;
- }
-
- #region IValueEquality members
-
- int IValueEquality.GetValueHashCode() {
- return GetHashCode();
- }
-
- bool IValueEquality.ValueEquals(object other) {
- if (other == null) return false;
-
- ExtensibleString es = other as ExtensibleString;
- if (es != null) return Value == es.Value;
- string os = other as string;
- if (os != null) return Value == os;
-
- return false;
- }
-
- #endregion
-
- #region ISequence Members
-
- public virtual object this[int index] {
- get { return RuntimeHelpers.CharToString(Value[index]); }
- }
-
- public object this[Slice slice] {
- get { return StringOps.GetItem(Value, slice); }
- }
-
- public object __getslice__(int start, int stop) {
- return StringOps.__getslice__(Value, start, stop);
- }
-
- #endregion
-
- #region IPythonContainer Members
-
- public virtual int __len__() {
- return Value.Length;
- }
-
- public virtual bool __contains__(object value) {
- if (value is string) return Value.Contains((string)value);
- else if (value is ExtensibleString) return Value.Contains(((ExtensibleString)value).Value);
-
- throw PythonOps.TypeErrorForBadInstance("expected string, got {0}", value);
- }
-
- #endregion
-
- }
-
- /// <summary>
- /// StringOps is the static class that contains the methods defined on strings, i.e. 'abc'
- ///
- /// Here we define all of the methods that a Python user would see when doing dir('abc').
- /// If the user is running in a CLS aware context they will also see all of the methods
- /// defined in the CLS System.String type.
- /// </summary>
- public static class StringOps {
- internal const int LowestUnicodeValue = 0x7f;
- private static readonly char[] Whitespace = new char[] { ' ', '\t', '\n', '\r', '\f' };
-
- internal static object FastNew(CodeContext/*!*/ context, object x) {
- if (x == null) {
- return "None";
- }
- if (x is string) {
- // check ascii
- return CheckAsciiString(context, (string)x);
- }
-
- // we don't invoke PythonOps.StringRepr here because we want to return the
- // Extensible<string> directly back if that's what we received from __str__.
- object value = PythonContext.InvokeUnaryOperator(context, UnaryOperators.String, x);
- if (value is string || value is Extensible<string>) {
- return value;
- }
-
- throw PythonOps.TypeError("expected str, got {0} from __str__", DynamicHelpers.GetPythonType(value).Name);
- }
-
- private static object CheckAsciiString(CodeContext context, string s) {
- for (int i = 0; i < s.Length; i++) {
- if (s[i] > '\x80')
- return StringOps.__new__(
- context,
- (PythonType)DynamicHelpers.GetPythonTypeFromType(typeof(String)),
- s,
- null,
- "strict"
- );
- }
- return s;
- }
-
- #region Python Constructors
-
- [StaticExtensionMethod]
- public static object __new__(CodeContext/*!*/ context, PythonType cls) {
- if (cls == TypeCache.String) {
- return "";
- } else {
- return cls.CreateInstance(context);
- }
- }
-
- [StaticExtensionMethod]
- public static object __new__(CodeContext/*!*/ context, PythonType cls, object @object) {
- if (cls == TypeCache.String) {
- return FastNew(context, @object);
- } else {
- return cls.CreateInstance(context, @object);
- }
- }
-
- [StaticExtensionMethod]
- public static object __new__(CodeContext/*!*/ context, PythonType cls, [NotNull]string @object) {
- if (cls == TypeCache.String) {
- return CheckAsciiString(context, @object);
- } else {
- return cls.CreateInstance(context, @object);
- }
- }
-
- [StaticExtensionMethod]
- public static object __new__(CodeContext/*!*/ context, PythonType cls, [NotNull]ExtensibleString @object) {
- if (cls == TypeCache.String) {
- return FastNew(context, @object);
- } else {
- return cls.CreateInstance(context, @object);
- }
- }
-
- [StaticExtensionMethod]
- public static object __new__(CodeContext/*!*/ context, PythonType cls, char @object) {
- if (cls == TypeCache.String) {
- return CheckAsciiString(context, RuntimeHelpers.CharToString(@object));
- } else {
- return cls.CreateInstance(context, @object);
- }
- }
-
- [StaticExtensionMethod]
- public static object __new__(CodeContext/*!*/ context, PythonType cls, [NotNull]BigInteger @object) {
- if (cls == TypeCache.String) {
- return @object.ToString();
- } else {
- return cls.CreateInstance(context, @object);
- }
- }
-
- [StaticExtensionMethod]
- public static object __new__(CodeContext/*!*/ context, PythonType cls, [NotNull]Extensible<BigInteger> @object) {
- if (cls == TypeCache.String) {
- return FastNew(context, @object);
- } else {
- return cls.CreateInstance(context, @object);
- }
- }
-
- [StaticExtensionMethod]
- public static object __new__(CodeContext/*!*/ context, PythonType cls, int @object) {
- if (cls == TypeCache.String) {
- return @object.ToString();
- } else {
- return cls.CreateInstance(context, @object);
- }
- }
-
- [StaticExtensionMethod]
- public static object __new__(CodeContext/*!*/ context, PythonType cls, bool @object) {
- if (cls == TypeCache.String) {
- return @object.ToString();
- } else {
- return cls.CreateInstance(context, @object);
- }
- }
-
- [StaticExtensionMethod]
- public static object __new__(CodeContext/*!*/ context, PythonType cls, double @object) {
- if (cls == TypeCache.String) {
- return DoubleOps.__str__(context, @object);
- } else {
- return cls.CreateInstance(context, @object);
- }
- }
-
- [StaticExtensionMethod]
- public static object __new__(CodeContext/*!*/ context, PythonType cls, Extensible<double> @object) {
- if (cls == TypeCache.String) {
- return FastNew(context, @object);
- } else {
- return cls.CreateInstance(context, @object);
- }
- }
-
- [StaticExtensionMethod]
- public static object __new__(CodeContext/*!*/ context, PythonType cls, float @object) {
- if (cls == TypeCache.String) {
- return SingleOps.__str__(context, @object);
- } else {
- return cls.CreateInstance(context, @object);
- }
- }
-
- [StaticExtensionMethod]
- public static object __new__(CodeContext/*!*/ context, PythonType cls,
- object @string,
- [DefaultParameterValue(null)] string encoding,
- [DefaultParameterValue("strict")] string errors) {
-
- string str = @string as string;
- if (str == null) throw PythonOps.TypeError("converting to unicode: need string, got {0}", DynamicHelpers.GetPythonType(@string).Name);
-
- if (cls == TypeCache.String) {
- return decode(context, str, encoding ?? PythonContext.GetContext(context).GetDefaultEncodingName(), errors);
- } else {
- return cls.CreateInstance(context, str, encoding, errors);
- }
- }
-
- #endregion
-
- #region Python __ methods
-
- public static bool __contains__(string s, string item) {
- return s.Contains(item);
- }
-
- public static bool __contains__(string s, char item) {
- return s.IndexOf(item) != -1;
- }
-
- public static int __len__(string s) {
- return s.Length;
- }
-
- [SpecialName]
- public static string GetItem(string s, int index) {
- return RuntimeHelpers.CharToString(s[PythonOps.FixIndex(index, s.Length)]);
- }
-
- [SpecialName]
- public static string GetItem(string s, object index) {
- return GetItem(s, Converter.ConvertToIndex(index));
- }
-
- [SpecialName]
- public static string GetItem(string s, Slice slice) {
- if (slice == null) throw PythonOps.TypeError("string indicies must be slices or integers");
- int start, stop, step;
- slice.indices(s.Length, out start, out stop, out step);
- if (step == 1) {
- return stop > start ? s.Substring(start, stop - start) : String.Empty;
- } else {
- int index = 0;
- char[] newData;
- if (step > 0) {
- if (start > stop) return String.Empty;
-
- int icnt = (stop - start + step - 1) / step;
- newData = new char[icnt];
- for (int i = start; i < stop; i += step) {
- newData[index++] = s[i];
- }
- } else {
- if (start < stop) return String.Empty;
-
- int icnt = (stop - start + step + 1) / step;
- newData = new char[icnt];
- for (int i = start; i > stop; i += step) {
- newData[index++] = s[i];
- }
- }
- return new string(newData);
- }
- }
-
- public static string __getslice__(string self, int x, int y) {
- Slice.FixSliceArguments(self.Length, ref x, ref y);
- if (x >= y) return String.Empty;
-
- return self.Substring(x, y - x);
- }
-
-
- #endregion
-
- #region Public Python methods
-
- public static string capitalize(this string self) {
- if (self.Length == 0) return self;
- return Char.ToUpper(self[0]) + self.Substring(1).ToLower();
- }
-
- // default fillchar (padding char) is a space
- public static string center(this string self, int width) {
- return center(self, width, ' ');
- }
-
- public static string center(this string self, int width, char fillchar) {
- int spaces = width - self.Length;
- if (spaces <= 0) return self;
-
- StringBuilder ret = new StringBuilder(width);
- ret.Append(fillchar, spaces / 2);
- ret.Append(self);
- ret.Append(fillchar, (spaces + 1) / 2);
- return ret.ToString();
- }
-
- public static int count(this string self, string sub) {
- return count(self, sub, 0, self.Length);
- }
-
- public static int count(this string self, string sub, int start) {
- return count(self, sub, start, self.Length);
- }
-
- public static int count(this string self, string ssub, int start, int end) {
- if (ssub == null) throw PythonOps.TypeError("expected string for 'sub' argument, got NoneType");
- string v = self;
-
- if (start > self.Length) {
- return 0;
- }
-
- start = PythonOps.FixSliceIndex(start, self.Length);
- end = PythonOps.FixSliceIndex(end, self.Length);
-
- if (ssub.Length == 0) {
- return Math.Max((end - start) + 1, 0);
- }
-
- int count = 0;
- while (true) {
- if (end <= start) break;
- int index = v.IndexOf(ssub, start, end - start);
- if (index == -1) break;
- count++;
- start = index + ssub.Length;
- }
- return count;
- }
-
- public static string decode(CodeContext/*!*/ context, string s) {
- return decode(context, s, Missing.Value, "strict");
- }
-
- public static string decode(CodeContext/*!*/ context, string s, [Optional]object encoding, [DefaultParameterValue("strict")]string errors) {
- return RawDecode(context, s, encoding, errors);
- }
-
- public static string encode(CodeContext/*!*/ context, string s, [Optional]object encoding, [DefaultParameterValue("strict")]string errors) {
- return RawEncode(context, s, encoding, errors);
- }
-
- private static string CastString(object o) {
- string res = o as string;
- if (res != null) {
- return res;
- }
-
- return ((Extensible<string>)o).Value;
- }
-
- private static string AsString(object o) {
- string res = o as string;
- if (res != null) {
- return res;
- }
-
- Extensible<string> es = o as Extensible<string>;
- if (es != null) {
- return es.Value;
- }
-
- return null;
- }
-
- public static bool endswith(this string self, object suffix) {
- TryStringOrTuple(suffix);
- if (suffix is PythonTuple)
- return endswith(self, (PythonTuple)suffix);
- else
- return endswith(self, CastString(suffix));
- }
-
- public static bool endswith(this string self, object suffix, int start) {
- TryStringOrTuple(suffix);
- if (suffix is PythonTuple)
- return endswith(self, (PythonTuple)suffix, start);
- else
- return endswith(self, CastString(suffix), start);
- }
-
- public static bool endswith(this string self, object suffix, int start, int end) {
- TryStringOrTuple(suffix);
- if (suffix is PythonTuple)
- return endswith(self, (PythonTuple)suffix, start, end);
- else
- return endswith(self, CastString(suffix), start, end);
- }
-
- public static string expandtabs(string self) {
- return expandtabs(self, 8);
- }
-
- public static string expandtabs(this string self, int tabsize) {
- StringBuilder ret = new StringBuilder(self.Length * 2);
- string v = self;
- int col = 0;
- for (int i = 0; i < v.Length; i++) {
- char ch = v[i];
- switch (ch) {
- case '\n':
- case '\r': col = 0; ret.Append(ch); break;
- case '\t':
- if (tabsize > 0) {
- int tabs = tabsize - (col % tabsize);
- ret.Append(' ', tabs);
- col = 0;
- }
- break;
- default:
- col++;
- ret.Append(ch);
- break;
- }
- }
- return ret.ToString();
- }
-
- public static int find(this string self, string sub) {
- if (sub == null) throw PythonOps.TypeError("expected string, got NoneType");
- if (sub.Length == 1) return self.IndexOf(sub[0]);
- CompareInfo c = CultureInfo.InvariantCulture.CompareInfo;
- return c.IndexOf(self, sub, CompareOptions.Ordinal);
-
- }
-
- public static int find(this string self, string sub, int start) {
- if (sub == null) throw PythonOps.TypeError("expected string, got NoneType");
- if (start > self.Length) return -1;
- start = PythonOps.FixSliceIndex(start, self.Length);
- return self.IndexOf(sub, start);
- }
-
- public static int find(this string self, string sub, int start, int end) {
- if (sub == null) throw PythonOps.TypeError("expected string, got NoneType");
- if (start > self.Length) return -1;
- start = PythonOps.FixSliceIndex(start, self.Length);
- end = PythonOps.FixSliceIndex(end, self.Length);
- if (end < start) return -1;
-
- return self.IndexOf(sub, start, end - start);
- }
-
- public static int index(this string self, string sub) {
- if (sub == null) throw PythonOps.TypeError("expected string, got NoneType");
- return index(self, sub, 0, self.Length);
- }
-
- public static int index(this string self, string sub, int start) {
- if (sub == null) throw PythonOps.TypeError("expected string, got NoneType");
- return index(self, sub, start, self.Length);
- }
-
- public static int index(this string self, string sub, int start, int end) {
- if (sub == null) throw PythonOps.TypeError("expected string, got NoneType");
- int ret = find(self, sub, start, end);
- if (ret == -1) throw PythonOps.ValueError("substring {0} not found in {1}", sub, self);
- return ret;
- }
-
- public static bool isalnum(this string self) {
- if (self.Length == 0) return false;
- string v = self;
- for (int i = v.Length - 1; i >= 0; i--) {
- if (!Char.IsLetterOrDigit(v, i)) return false;
- }
- return true;
- }
-
- public static bool isalpha(this string self) {
- if (self.Length == 0) return false;
- string v = self;
- for (int i = v.Length - 1; i >= 0; i--) {
- if (!Char.IsLetter(v, i)) return false;
- }
- return true;
- }
-
- public static bool isdigit(this string self) {
- if (self.Length == 0) return false;
- string v = self;
- for (int i = v.Length - 1; i >= 0; i--) {
- if (!Char.IsDigit(v, i)) return false;
- }
- return true;
- }
-
- public static bool isspace(this string self) {
- if (self.Length == 0) return false;
- string v = self;
- for (int i = v.Length - 1; i >= 0; i--) {
- if (!Char.IsWhiteSpace(v, i)) return false;
- }
- return true;
- }
-
- public static bool isdecimal(this string self) {
- return isnumeric(self);
- }
-
- public static bool isnumeric(this string self) {
- if (String.IsNullOrEmpty(self)) return false;
-
- foreach (char c in self) {
- if (!Char.IsDigit(c)) return false;
- }
- return true;
- }
-
- public static bool islower(this string self) {
- if (self.Length == 0) return false;
- string v = self;
- bool hasLower = false;
- for (int i = v.Length - 1; i >= 0; i--) {
- if (!hasLower && Char.IsLower(v, i)) hasLower = true;
- if (Char.IsUpper(v, i)) return false;
- }
- return hasLower;
- }
-
- public static bool isupper(this string self) {
- if (self.Length == 0) return false;
- string v = self;
- bool hasUpper = false;
- for (int i = v.Length - 1; i >= 0; i--) {
- if (!hasUpper && Char.IsUpper(v, i)) hasUpper = true;
- if (Char.IsLower(v, i)) return false;
- }
- return hasUpper;
- }
-
- // return true if self is a titlecased string and there is at least one
- // character in self; also, uppercase characters may only follow uncased
- // characters (e.g. whitespace) and lowercase characters only cased ones.
- // return false otherwise.
- public static bool istitle(this string self) {
- if (self == null || self.Length == 0) return false;
-
- string v = self;
- bool prevCharCased = false, currCharCased = false, containsUpper = false;
- for (int i = 0; i < v.Length; i++) {
- if (Char.IsUpper(v, i) || Char.GetUnicodeCategory(v, i) == UnicodeCategory.TitlecaseLetter) {
- containsUpper = true;
- if (prevCharCased)
- return false;
- else
- currCharCased = true;
- } else if (Char.IsLower(v, i))
- if (!prevCharCased)
- return false;
- else
- currCharCased = true;
- else
- currCharCased = false;
- prevCharCased = currCharCased;
- }
-
- // if we've gone through the whole string and haven't encountered any rule
- // violations but also haven't seen an Uppercased char, then this is not a
- // title e.g. '\n', all whitespace etc.
- return containsUpper;
- }
-
- public static bool isunicode(this string self) {
- foreach (char c in self) {
- if (c >= LowestUnicodeValue) return true;
- }
- return false;
- }
-
- // Return a string which is the concatenation of the strings
- // in the sequence seq. The separator between elements is the
- // string providing this method
- public static string join(this string self, object sequence) {
- IEnumerator seq = PythonOps.GetEnumerator(sequence);
- if (!seq.MoveNext()) return "";
-
- // check if we have just a sequnce of just one value - if so just
- // return that value.
- object curVal = seq.Current;
- if (!seq.MoveNext()) return Converter.ConvertToString(curVal);
-
- StringBuilder ret = new StringBuilder();
- AppendJoin(curVal, 0, ret);
-
- int index = 1;
- do {
- ret.Append(self);
-
- AppendJoin(seq.Current, index, ret);
-
- index++;
- } while (seq.MoveNext());
-
- return ret.ToString();
- }
-
- public static string join(this string/*!*/ self, [NotNull]List/*!*/ sequence) {
- if (sequence.__len__() == 0) return String.Empty;
-
- lock (sequence) {
- if (sequence.__len__() == 1) {
- return Converter.ConvertToString(sequence[0]);
- }
-
- StringBuilder ret = new StringBuilder();
-
- AppendJoin(sequence._data[0], 0, ret);
- for (int i = 1; i < sequence._size; i++) {
- ret.Append(self);
- AppendJoin(sequence._data[i], i, ret);
- }
-
- return ret.ToString();
- }
- }
-
- public static string ljust(this string self, int width) {
- return ljust(self, width, ' ');
- }
-
- public static string ljust(this string self, int width, char fillchar) {
- int spaces = width - self.Length;
- if (spaces <= 0) return self;
-
- StringBuilder ret = new StringBuilder(width);
- ret.Append(self);
- ret.Append(fillchar, spaces);
- return ret.ToString();
- }
-
- public static string lower(this string self) {
- return self.ToLower();
- }
-
- public static string lstrip(this string self) {
- return self.TrimStart(Whitespace);
- }
-
- public static string lstrip(this string self, string chars) {
- if (chars == null) return lstrip(self);
- return self.TrimStart(chars.ToCharArray());
- }
-
- public static PythonTuple partition(this string self, string sep) {
- if (sep == null)
- throw PythonOps.TypeError("expected string, got NoneType");
- if (sep.Length == 0)
- throw PythonOps.ValueError("empty separator");
-
- object[] obj = new object[3] { "", "", "" };
-
- if (self.Length != 0) {
- int index = find(self, sep);
- if (index == -1) {
- obj[0] = self;
- } else {
- obj[0] = self.Substring(0, index);
- obj[1] = sep;
- obj[2] = self.Substring(index + sep.Length, self.Length - index - sep.Length);
- }
- }
- return new PythonTuple(obj);
- }
-
- private static string StringOrBuffer(object input) {
- string result = (input as string);
- if (result != null) {
- return result;
- }
- PythonBuffer buffer = (input as PythonBuffer);
- if (buffer != null) {
- return buffer.ToString();
- }
- throw PythonOps.TypeError("expected a character buffer object");
- }
-
- public static string replace(this string self, object old, object new_) {
- string oldString = StringOrBuffer(old);
- string newString = StringOrBuffer(new_);
- if (oldString.Length == 0) return ReplaceEmpty(self, newString, self.Length + 1);
- return self.Replace(oldString, newString);
- }
-
- public static string replace(this string self, object old, object new_, int maxsplit) {
- if (maxsplit == -1) return replace(self, old, new_);
- string oldString = StringOrBuffer(old);
- string newString = StringOrBuffer(new_);
- if (oldString.Length == 0) return ReplaceEmpty(self, newString, maxsplit);
-
- string v = self;
- StringBuilder ret = new StringBuilder(v.Length);
-
- int index;
- int start = 0;
-
- while (maxsplit > 0 && (index = v.IndexOf(oldString, start)) != -1) {
- ret.Append(v.Substring(start, index - start));
- ret.Append(newString);
- start = index + oldString.Length;
- maxsplit--;
- }
- ret.Append(v.Substring(start));
-
- return ret.ToString();
- }
-
- public static int rfind(this string self, string sub) {
- if (sub == null) throw PythonOps.TypeError("expected string, got NoneType");
- return rfind(self, sub, 0, self.Length);
- }
-
- public static int rfind(this string self, string sub, int start) {
- if (sub == null) throw PythonOps.TypeError("expected string, got NoneType");
- if (start > self.Length) return -1;
- return rfind(self, sub, start, self.Length);
- }
-
- public static int rfind(this string self, string sub, int start, int end) {
- if (sub == null) throw PythonOps.TypeError("expected string, got NoneType");
- if (start > self.Length) return -1;
-
- start = PythonOps.FixSliceIndex(start, self.Length);
- end = PythonOps.FixSliceIndex(end, self.Length);
-
- if (start > end) return -1; // can't possibly match anything, not even an empty string
- if (sub.Length == 0) return end; // match at the end
- if (end == 0) return -1; // can't possibly find anything
-
- return self.LastIndexOf(sub, end - 1, end - start);
- }
-
- public static int rindex(this string self, string sub) {
- return rindex(self, sub, 0, self.Length);
- }
-
- public static int rindex(this string self, string sub, int start) {
- return rindex(self, sub, start, self.Length);
- }
-
- public static int rindex(this string self, string sub, int start, int end) {
- int ret = rfind(self, sub, start, end);
- if (ret == -1) throw PythonOps.ValueError("substring {0} not found in {1}", sub, self);
- return ret;
- }
-
- public static string rjust(this string self, int width) {
- return rjust(self, width, ' ');
- }
-
- public static string rjust(this string self, int width, char fillchar) {
- int spaces = width - self.Length;
- if (spaces <= 0) return self;
-
- StringBuilder ret = new StringBuilder(width);
- ret.Append(fillchar, spaces);
- ret.Append(self);
- return ret.ToString();
- }
-
- public static PythonTuple rpartition(this string self, string sep) {
- if (sep == null)
- throw PythonOps.TypeError("expected string, got NoneType");
- if (sep.Length == 0)
- throw PythonOps.ValueError("empty separator");
-
- object[] obj = new object[3] { "", "", "" };
- if (self.Length != 0) {
- int index = rfind(self, sep);
- if (index == -1) {
- obj[2] = self;
- } else {
- obj[0] = self.Substring(0, index);
- obj[1] = sep;
- obj[2] = self.Substring(index + sep.Length, self.Length - index - sep.Length);
- }
- }
- return new PythonTuple(obj);
- }
-
- // when no maxsplit arg is given then just use split
- public static List rsplit(this string self) {
- return SplitInternal(self, (char[])null, -1);
- }
-
- public static List rsplit(this string self, string sep) {
- return rsplit(self, sep, -1);
- }
-
- public static List rsplit(this string self, string sep, int maxsplit) {
- // rsplit works like split but needs to split from the right;
- // reverse the original string (and the sep), split, reverse
- // the split list and finally reverse each element of the list
- string reversed = Reverse(self);
- if (sep != null) sep = Reverse(sep);
- List temp = null, ret = null;
- temp = split(reversed, sep, maxsplit);
- temp.reverse();
- int resultlen = temp.__len__();
- if (resultlen != 0) {
- ret = new List(resultlen);
- foreach (string s in temp)
- ret.AddNoLock(Reverse(s));
- } else {
- ret = temp;
- }
- return ret;
- }
-
- public static string rstrip(this string self) {
- return self.TrimEnd(Whitespace);
- }
-
- public static string rstrip(this string self, string chars) {
- if (chars == null) return rstrip(self);
- return self.TrimEnd(chars.ToCharArray());
- }
-
- public static List split(this string self) {
- return SplitInternal(self, (char[])null, -1);
- }
-
- public static List split(this string self, string sep) {
- return split(self, sep, -1);
- }
-
- public static List split(this string self, string sep, int maxsplit) {
- if (sep == null) {
- if (maxsplit == 0) {
- // Corner case for CPython compatibility
- List result = PythonOps.MakeEmptyList(1);
- result.AddNoLock(self.TrimStart());
- return result;
-
- } else {
- return SplitInternal(self, (char[])null, maxsplit);
- }
- }
-
- if (sep.Length == 0) {
- throw PythonOps.ValueError("empty separator");
- } else if (sep.Length == 1) {
- return SplitInternal(self, new char[] { sep[0] }, maxsplit);
- } else {
- return SplitInternal(self, sep, maxsplit);
- }
- }
-
- public static List splitlines(this string self) {
- return splitlines(self, false);
- }
-
- public static List splitlines(this string self, bool keepends) {
- List ret = new List();
- int i, linestart;
- for (i = 0, linestart = 0; i < self.Length; i++) {
- if (self[i] == '\n' || self[i] == '\r' || self[i] == '\x2028') {
- // special case of "\r\n" as end of line marker
- if (i < self.Length - 1 && self[i] == '\r' && self[i + 1] == '\n') {
- if (keepends)
- ret.AddNoLock(self.Substring(linestart, i - linestart + 2));
- else
- ret.AddNoLock(self.Substring(linestart, i - linestart));
- linestart = i + 2;
- i++;
- } else { //'\r', '\n', or unicode new line as end of line marker
- if (keepends)
- ret.AddNoLock(self.Substring(linestart, i - linestart + 1));
- else
- ret.AddNoLock(self.Substring(linestart, i - linestart));
- linestart = i + 1;
- }
- }
- }
- // the last line needs to be accounted for if it is not empty
- if (i - linestart != 0)
- ret.AddNoLock(self.Substring(linestart, i - linestart));
- return ret;
- }
-
-
- public static bool startswith(this string self, object prefix) {
- TryStringOrTuple(prefix);
- if (prefix is PythonTuple)
- return startswith(self, (PythonTuple)prefix);
- else
- return startswith(self, CastString(prefix));
-
- }
-
- public static bool startswith(this string self, object prefix, int start) {
- TryStringOrTuple(prefix);
- if (prefix is PythonTuple)
- return startswith(self, (PythonTuple)prefix, start);
- else
- return startswith(self, CastString(prefix), start);
- }
-
- public static bool startswith(this string self, object prefix, int start, int end) {
- TryStringOrTuple(prefix);
- if (prefix is PythonTuple)
- return startswith(self, (PythonTuple)prefix, start, end);
- else
- return startswith(self, CastString(prefix), start, end);
- }
-
- public static string strip(this string self) {
- return self.Trim();
- }
-
- public static string strip(this string self, string chars) {
- if (chars == null) return strip(self);
- return self.Trim(chars.ToCharArray());
- }
-
- public static string swapcase(this string self) {
- StringBuilder ret = new StringBuilder(self);
- for (int i = 0; i < ret.Length; i++) {
- char ch = ret[i];
- if (Char.IsUpper(ch)) ret[i] = Char.ToLower(ch);
- else if (Char.IsLower(ch)) ret[i] = Char.ToUpper(ch);
- }
- return ret.ToString();
- }
-
- public static string title(this string self) {
- if (self == null || self.Length == 0) return self;
-
- char[] retchars = self.ToCharArray();
- bool prevCharCased = false;
- bool currCharCased = false;
- int i = 0;
- do {
- if (Char.IsUpper(retchars[i]) || Char.IsLower(retchars[i])) {
- if (!prevCharCased)
- retchars[i] = Char.ToUpper(retchars[i]);
- else
- retchars[i] = Char.ToLower(retchars[i]);
- currCharCased = true;
- } else {
- currCharCased = false;
- }
- i++;
- prevCharCased = currCharCased;
- }
- while (i < retchars.Length);
- return new string(retchars);
- }
-
- //translate on a unicode string differs from that on an ascii
- //for unicode, the table argument is actually a dictionary with
- //character ordinals as keys and the replacement strings as values
- public static string translate(this string self, PythonDictionary table) {
- if (table == null) throw PythonOps.TypeError("expected dictionary or string, got NoneType");
- if (self.Length == 0) return self;
- StringBuilder ret = new StringBuilder();
- for (int i = 0, idx = 0; i < self.Length; i++) {
- idx = (int)self[i];
- if (table.__contains__(idx))
- ret.Append((string)table[idx]);
- else
- ret.Append(self[i]);
- }
- return ret.ToString();
- }
-
- public static string translate(this string self, string table) {
- return translate(self, table, (string)null);
- }
-
- public static string translate(this string self, string table, string deletechars) {
- if (table == null) {
- throw PythonOps.TypeError("expected string, got NoneType");
- } else if (table.Length != 256) {
- throw PythonOps.ValueError("translation table must be 256 characters long");
- } else if (self.Length == 0) {
- return self;
- }
-
- // List<char> is about 2/3rds as expensive as StringBuilder appending individual
- // char's so we use that instead of a StringBuilder
- List<char> res = new List<char>();
- for (int i = 0; i < self.Length; i++) {
- if (deletechars == null || !deletechars.Contains(Char.ToString(self[i]))) {
- int idx = (int)self[i];
- if (idx >= 0 && idx < 256) {
- res.Add(table[idx]);
- }
- }
- }
- return new String(res.ToArray());
- }
-
- public static string upper(this string self) {
- return self.ToUpper();
- }
-
- public static string zfill(this string self, int width) {
- int spaces = width - self.Length;
- if (spaces <= 0) return self;
-
- StringBuilder ret = new StringBuilder(width);
- if (self.Length > 0 && IsSign(self[0])) {
- ret.Append(self[0]);
- ret.Append('0', spaces);
- ret.Append(self.Substring(1));
- } else {
- ret.Append('0', spaces);
- ret.Append(self);
- }
- return ret.ToString();
- }
- #endregion
-
- #region operators
- [SpecialName]
- public static string Add(string self, string other) {
- return self + other;
- }
-
- [SpecialName]
- public static string Add(string self, char other) {
- return self + other;
- }
-
- [SpecialName]
- public static string Add(char self, string other) {
- return self + other;
- }
-
- [SpecialName]
- public static string Mod(CodeContext/*!*/ context, string self, object other) {
- return new StringFormatter(context, self, other).Format();
- }
-
- [SpecialName]
- [return: MaybeNotImplemented]
- public static object Mod(CodeContext/*!*/ context, object other, string self) {
- string str = other as string;
- if (str != null) {
- return new StringFormatter(context, str, self).Format();
- }
-
- Extensible<string> es = other as Extensible<string>;
- if (es != null) {
- return new StringFormatter(context, es.Value, self).Format();
- }
-
- return NotImplementedType.Value;
- }
-
- [SpecialName]
- public static string Multiply(string s, int count) {
- if (count <= 0) return String.Empty;
- if (count == 1) return s;
-
- long size = (long)s.Length * (long)count;
- if (size > Int32.MaxValue) throw PythonOps.OverflowError("repeated string is too long");
-
- int sz = s.Length;
- if (sz == 1) return new string(s[0], count);
-
- StringBuilder ret = new StringBuilder(sz * count);
- ret.Insert(0, s, count);
- // the above code is MUCH faster than the simple loop
- //for (int i=0; i < count; i++) ret.Append(s);
- return ret.ToString();
- }
-
- [SpecialName]
- public static string Multiply(int other, string self) {
- return Multiply(self, other);
- }
-
- [SpecialName]
- public static object Multiply(string self, [NotNull]Index count) {
- return PythonOps.MultiplySequence<string>(Multiply, self, count, true);
- }
-
- [SpecialName]
- public static object Multiply([NotNull]Index count, string self) {
- return PythonOps.MultiplySequence<string>(Multiply, self, count, false);
- }
-
- [SpecialName]
- public static object Multiply(string self, object count) {
- int index;
- if (Converter.TryConvertToIndex(count, out index)) {
- return Multiply(self, index);
- }
-
- throw PythonOps.TypeErrorForUnIndexableObject(count);
- }
-
- [SpecialName]
- public static object Multiply(object count, string self) {
- int index;
- if (Converter.TryConvertToIndex(count, out index)) {
- return Multiply(index, self);
- }
-
- throw PythonOps.TypeErrorForUnIndexableObject(count);
- }
-
- [SpecialName]
- public static bool GreaterThan(string x, string y) {
- return string.CompareOrdinal(x, y) > 0;
- }
- [SpecialName]
- public static bool LessThan(string x, string y) {
- return string.CompareOrdinal(x, y) < 0;
- }
- [SpecialName]
- public static bool LessThanOrEqual(string x, string y) {
- return string.CompareOrdinal(x, y) <= 0;
- }
- [SpecialName]
- public static bool GreaterThanOrEqual(string x, string y) {
- return string.CompareOrdinal(x, y) >= 0;
- }
- [SpecialName]
- public static bool Equals(string x, string y) {
- return string.Equals(x, y);
- }
- [SpecialName]
- public static bool NotEquals(string x, string y) {
- return !string.Equals(x, y);
- }
-
- #endregion
-
- [SpecialName, ImplicitConversionMethod]
- public static string ConvertFromChar(char c) {
- return RuntimeHelpers.CharToString(c);
- }
-
- [SpecialName, ExplicitConversionMethod]
- public static char ConvertToChar(string s) {
- if (s.Length == 1) return s[0];
- throw PythonOps.TypeErrorForTypeMismatch("char", s);
- }
-
- [SpecialName, ImplicitConversionMethod]
- public static IEnumerable ConvertToIEnumerable(string s) {
- return StringOps.GetEnumerable(s);
- }
-
- public static int __cmp__(string self, string obj) {
- int ret = string.CompareOrdinal(self, obj);
- return ret == 0 ? 0 : (ret < 0 ? -1 : +1);
- }
-
- public static int __cmp__(string self, ExtensibleString obj) {
- int ret = string.CompareOrdinal(self, obj.Value);
- return ret == 0 ? 0 : (ret < 0 ? -1 : +1);
- }
-
- public static int __cmp__(string self, char obj) {
- return (int)(self[0] - (char)obj);
- }
-
- public static object __getnewargs__(CodeContext/*!*/ context, string self) {
- if (!Object.ReferenceEquals(self, null)) {
- // Cast self to object to avoid exception caused by trying to access SystemState on DefaultContext
- return PythonTuple.MakeTuple(StringOps.__new__(context, TypeCache.String, (object)self));
- }
- throw PythonOps.TypeErrorForBadInstance("__getnewargs__ requires a 'str' object but received a '{0}'", self);
- }
-
- public static string __str__(string self) {
- return self;
- }
-
- public static Extensible<string> __str__(ExtensibleString self) {
- return self;
- }
-
- #region Internal implementation details
-
- internal static IEnumerable GetEnumerable(string s) {
- // make an enumerator that produces strings instead of chars
- return new PythonStringEnumerable(s);
- }
-
- internal static string Quote(string s) {
-
- bool isUnicode = false;
- StringBuilder b = new StringBuilder(s.Length + 5);
- char quote = '\'';
- if (s.IndexOf('\'') != -1 && s.IndexOf('\"') == -1) {
- quote = '\"';
- }
- b.Append(quote);
- b.Append(ReprEncode(s, quote, ref isUnicode));
- b.Append(quote);
- if (isUnicode) return "u" + b.ToString();
- return b.ToString();
- }
-
- internal static string ReprEncode(string s, ref bool isUnicode) {
- return ReprEncode(s, (char)0, ref isUnicode);
- }
-
- internal static bool TryGetEncoding(string name, out Encoding encoding) {
- #if SILVERLIGHT // EncodingInfo
- switch (NormalizeEncodingName(name)) {
- case "us_ascii":
- case "ascii": encoding = PythonAsciiEncoding.Instance; return true;
- case "utf_8": encoding = (Encoding)new EncodingWrapper(Encoding.UTF8, new byte[0]).Clone(); return true;
- case "utf_16_le": encoding = (Encoding)new EncodingWrapper(Encoding.Unicode, new byte[0]).Clone(); return true;
- case "utf_16_be": encoding = (Encoding)new EncodingWrapper(Encoding.BigEndianUnicode, new byte[0]).Clone(); return true;
- case "utf_8_sig": encoding = Encoding.UTF8; return true;
- }
- #else
- name = NormalizeEncodingName(name);
-
- EncodingInfoWrapper encInfo;
- if (CodecsInfo.Codecs.TryGetValue(name, out encInfo)) {
- encoding = (Encoding)encInfo.GetEncoding().Clone();
- return true;
- }
- #endif
- encoding = null;
- return false;
- }
-
- internal static byte[] ToByteArray(string s) {
- byte[] ret = new byte[s.Length];
- for (int i = 0; i < s.Length; i++) {
- if (…
Large files files are truncated, but you can click here to view the full file