From 93cd1e99be6b904b6374c4d15d74e5a8ee89eb1c Mon Sep 17 00:00:00 2001 From: Shad Storhaug Date: Tue, 21 Dec 2021 01:09:23 +0700 Subject: [PATCH] BREAKING: Removed (more) unnecessary nullable value types (see #574 and #581) (#583) * BREAKING: Lucene.Net.Queries.Function.ValueSources.EnumFieldSource: Removed nullable value types from public API * Lucene.Net.Queries: Removed unnecessary nullable value types * SWEEP: Removed several unnecessary nullable value type declarations in the test framework and in tests * BREAKING: Lucene.Net.QueryParsers.Flexible: Removed unnecessary nullable value types from ConfigurationKeys and configuration setters/getters in StandardQueryParser. Added AbstractQueryConfig.TryGetValue() method to allow retrieving value types so they can be defaulted properly. --- .../ValueSources/DoubleFieldSource.cs | 2 +- .../Function/ValueSources/EnumFieldSource.cs | 34 +++++++--------- .../Function/ValueSources/FloatFieldSource.cs | 2 +- .../Function/ValueSources/IntFieldSource.cs | 2 +- .../Function/ValueSources/ShortFieldSource.cs | 2 +- .../Core/Config/AbstractQueryConfig.cs | 35 ++++++++++++++++- .../Config/FieldBoostMapFCListener.cs | 10 +---- .../Config/FieldDateResolutionFCListener.cs | 20 +++------- .../Config/StandardQueryConfigHandler.cs | 18 ++++----- .../Processors/AnalyzerQueryNodeProcessor.cs | 11 +++--- .../Processors/BoostQueryNodeProcessor.cs | 6 +-- .../DefaultPhraseSlopQueryNodeProcessor.cs | 6 +-- ...owercaseExpandedTermsQueryNodeProcessor.cs | 5 +-- .../Flexible/Standard/StandardQueryParser.cs | 21 +++++----- .../Analysis/BaseTokenStreamTestCase.cs | 12 +++--- .../Codecs/RAMOnly/RAMOnlyPostingsFormat.cs | 4 +- .../Index/BaseTermVectorsFormatTestCase.cs | 2 +- .../CharFilters/TestMappingCharFilter.cs | 4 +- .../Analysis/Util/TestCharArraySet.cs | 6 +-- .../SortedSet/TestSortedSetDocValuesFacets.cs | 12 +++--- .../Taxonomy/TestTaxonomyCombined.cs | 6 +-- .../Taxonomy/TestTaxonomyFacetCounts.cs | 12 +++--- .../Taxonomy/TestTaxonomyFacetCounts2.cs | 38 +++++++++--------- .../TestTaxonomyFacetSumValueSource.cs | 12 +++--- .../TestDrillSideways.cs | 10 ++--- .../Mlt/TestMoreLikeThis.cs | 39 +++++++++---------- .../TestCustomScoreQuery.cs | 2 +- .../Precedence/TestPrecedenceQueryParser.cs | 2 +- .../Standard/TestMultiFieldQPHelper.cs | 2 +- .../Flexible/Standard/TestQPHelper.cs | 2 +- .../PortedSolr3Test.cs | 6 +-- .../Prefix/TestRecursivePrefixTreeStrategy.cs | 6 +-- .../Analyzing/TestFreeTextSuggester.cs | 16 ++++---- src/Lucene.Net.Tests/Index/TestDocTermOrds.cs | 6 +-- .../Index/TestDocValuesWithThreads.cs | 12 +++--- .../Index/TestDocsAndPositions.cs | 6 +-- .../Index/TestDocumentsWriterDeleteQueue.cs | 12 +++--- .../Index/TestIndexWriterDelete.cs | 2 +- .../Index/TestMaxTermFrequency.cs | 4 +- src/Lucene.Net.Tests/Index/TestMixedCodecs.cs | 4 +- .../Index/TestMultiDocValues.cs | 4 +- src/Lucene.Net.Tests/Index/TestMultiFields.cs | 6 +-- .../Index/TestPostingsOffsets.cs | 6 +-- src/Lucene.Net.Tests/Index/TestTermsEnum.cs | 4 +- .../Search/TestCustomSearcherSort.cs | 12 +++--- src/Lucene.Net.Tests/Search/TestDocIdSet.cs | 6 +-- .../Search/TestFieldCacheRangeFilter.cs | 28 ++++++------- .../Search/TestMinShouldMatch2.cs | 2 +- .../Search/TestSubScorerFreqs.cs | 38 +++++++++--------- src/Lucene.Net.Tests/Util/TestBytesRefHash.cs | 4 +- .../Util/TestDoubleBarrelLRUCache.cs | 4 +- .../Util/TestMergedIterator.cs | 8 ++-- 52 files changed, 267 insertions(+), 268 deletions(-) diff --git a/src/Lucene.Net.Queries/Function/ValueSources/DoubleFieldSource.cs b/src/Lucene.Net.Queries/Function/ValueSources/DoubleFieldSource.cs index 55dd2f88d8..0165b0fd34 100644 --- a/src/Lucene.Net.Queries/Function/ValueSources/DoubleFieldSource.cs +++ b/src/Lucene.Net.Queries/Function/ValueSources/DoubleFieldSource.cs @@ -100,7 +100,7 @@ public override bool Equals(object o) public override int GetHashCode() { - int h = m_parser == null ? typeof(double?).GetHashCode() : m_parser.GetType().GetHashCode(); + int h = m_parser == null ? typeof(double).GetHashCode() : m_parser.GetType().GetHashCode(); h += base.GetHashCode(); return h; } diff --git a/src/Lucene.Net.Queries/Function/ValueSources/EnumFieldSource.cs b/src/Lucene.Net.Queries/Function/ValueSources/EnumFieldSource.cs index 4981ca64be..617e764ab7 100644 --- a/src/Lucene.Net.Queries/Function/ValueSources/EnumFieldSource.cs +++ b/src/Lucene.Net.Queries/Function/ValueSources/EnumFieldSource.cs @@ -31,17 +31,17 @@ namespace Lucene.Net.Queries.Function.ValueSources /// /// Obtains field values from and makes /// those values available as other numeric types, casting as needed. - /// StrVal of the value is not the value, but its (displayed) value + /// StrVal of the value is not the value, but its (displayed) value. /// public class EnumFieldSource : FieldCacheSource { private const int DEFAULT_VALUE = -1; private readonly FieldCache.IInt32Parser parser; - private readonly IDictionary enumIntToStringMap; - private readonly IDictionary enumStringToIntMap; + private readonly IDictionary enumIntToStringMap; + private readonly IDictionary enumStringToIntMap; - public EnumFieldSource(string field, FieldCache.IInt32Parser parser, IDictionary enumIntToStringMap, IDictionary enumStringToIntMap) + public EnumFieldSource(string field, FieldCache.IInt32Parser parser, IDictionary enumIntToStringMap, IDictionary enumStringToIntMap) : base(field) { this.parser = parser; @@ -54,15 +54,11 @@ public EnumFieldSource(string field, FieldCache.IInt32Parser parser, IDictionary /// /// NOTE: This was intValueToStringValue() in Lucene /// - private string Int32ValueToStringValue(int? intVal) + private string Int32ValueToStringValue(int intVal) { - if (intVal == null) - { - return null; - } + // LUCENENET: null value not applicable for value types (it defaults to 0 anyway) - string enumString = enumIntToStringMap[intVal]; - if (enumString != null) + if (enumIntToStringMap.TryGetValue(intVal, out string enumString)) { return enumString; } @@ -80,8 +76,7 @@ private string Int32ValueToStringValue(int? intVal) return null; } - int? enumInt = enumStringToIntMap[stringVal]; - if (enumInt != null) //enum int found for str + if (enumStringToIntMap.TryGetValue(stringVal, out int enumInt)) //enum int found for str { return enumInt; } @@ -91,8 +86,7 @@ private string Int32ValueToStringValue(int? intVal) { intValue = DEFAULT_VALUE; } - string enumString = enumIntToStringMap[intValue]; - if (enumString != null) //has matching str + if (enumIntToStringMap.ContainsKey(intValue)) //has matching str { return intValue; } @@ -163,7 +157,7 @@ public override double DoubleVal(int doc) public override string StrVal(int doc) { - int? intValue = arr.Get(doc); + int intValue = arr.Get(doc); return outerInstance.Int32ValueToStringValue(intValue); } @@ -255,11 +249,11 @@ public override bool Equals(object o) // LUCENENET specific: must use DictionaryEqualityComparer.Equals() to ensure values // contained within the dictionaries are compared for equality - if (!JCG.DictionaryEqualityComparer.Default.Equals(enumIntToStringMap, that.enumIntToStringMap)) + if (!JCG.DictionaryEqualityComparer.Default.Equals(enumIntToStringMap, that.enumIntToStringMap)) { return false; } - if (!JCG.DictionaryEqualityComparer.Default.Equals(enumStringToIntMap, that.enumStringToIntMap)) + if (!JCG.DictionaryEqualityComparer.Default.Equals(enumStringToIntMap, that.enumStringToIntMap)) { return false; } @@ -277,8 +271,8 @@ public override int GetHashCode() result = 31 * result + parser.GetHashCode(); // LUCENENET specific: must use DictionaryEqualityComparer.GetHashCode() to ensure values // contained within the dictionaries are compared for equality - result = 31 * result + JCG.DictionaryEqualityComparer.Default.GetHashCode(enumIntToStringMap); - result = 31 * result + JCG.DictionaryEqualityComparer.Default.GetHashCode(enumStringToIntMap); + result = 31 * result + JCG.DictionaryEqualityComparer.Default.GetHashCode(enumIntToStringMap); + result = 31 * result + JCG.DictionaryEqualityComparer.Default.GetHashCode(enumStringToIntMap); return result; } } diff --git a/src/Lucene.Net.Queries/Function/ValueSources/FloatFieldSource.cs b/src/Lucene.Net.Queries/Function/ValueSources/FloatFieldSource.cs index d56c9d9a2b..7a8a559113 100644 --- a/src/Lucene.Net.Queries/Function/ValueSources/FloatFieldSource.cs +++ b/src/Lucene.Net.Queries/Function/ValueSources/FloatFieldSource.cs @@ -107,7 +107,7 @@ public override bool Equals(object o) public override int GetHashCode() { - int h = m_parser == null ? typeof(float?).GetHashCode() : m_parser.GetType().GetHashCode(); + int h = m_parser == null ? typeof(float).GetHashCode() : m_parser.GetType().GetHashCode(); h += base.GetHashCode(); return h; } diff --git a/src/Lucene.Net.Queries/Function/ValueSources/IntFieldSource.cs b/src/Lucene.Net.Queries/Function/ValueSources/IntFieldSource.cs index 457d73b4ef..8cbc1cf207 100644 --- a/src/Lucene.Net.Queries/Function/ValueSources/IntFieldSource.cs +++ b/src/Lucene.Net.Queries/Function/ValueSources/IntFieldSource.cs @@ -147,7 +147,7 @@ public override bool Equals(object o) public override int GetHashCode() { - int h = parser == null ? typeof(int?).GetHashCode() : parser.GetType().GetHashCode(); + int h = parser == null ? typeof(int).GetHashCode() : parser.GetType().GetHashCode(); h += base.GetHashCode(); return h; } diff --git a/src/Lucene.Net.Queries/Function/ValueSources/ShortFieldSource.cs b/src/Lucene.Net.Queries/Function/ValueSources/ShortFieldSource.cs index 6e219b238c..c47720f572 100644 --- a/src/Lucene.Net.Queries/Function/ValueSources/ShortFieldSource.cs +++ b/src/Lucene.Net.Queries/Function/ValueSources/ShortFieldSource.cs @@ -133,7 +133,7 @@ public override bool Equals(object o) public override int GetHashCode() { - var h = parser == null ? typeof(short?).GetHashCode() : parser.GetType().GetHashCode(); + var h = parser == null ? typeof(short).GetHashCode() : parser.GetType().GetHashCode(); h += base.GetHashCode(); return h; } diff --git a/src/Lucene.Net.QueryParser/Flexible/Core/Config/AbstractQueryConfig.cs b/src/Lucene.Net.QueryParser/Flexible/Core/Config/AbstractQueryConfig.cs index f0ab7c72bd..879d5ff605 100644 --- a/src/Lucene.Net.QueryParser/Flexible/Core/Config/AbstractQueryConfig.cs +++ b/src/Lucene.Net.QueryParser/Flexible/Core/Config/AbstractQueryConfig.cs @@ -38,6 +38,32 @@ internal AbstractQueryConfig() // although this class is public, it can only be constructed from package } + /// + /// Gets the value associated with the specified key. + /// + /// the value's type + /// the key, cannot be null + /// When this method returns, contains the value associated with the specified key, + /// if the key is found; otherwise, the default value for the type of the parameter. + /// This parameter is passed uninitialized. + /// true if the configuration contains an element with the specified ; otherwise, false. + // LUCENENET specific - using this method allows us to store non-nullable value types + public virtual bool TryGetValue(ConfigurationKey key, out T value) + { + if (key is null) + throw new ArgumentNullException(nameof(key), "key cannot be null!"); + if (this.configMap.TryGetValue(key, out object resultObj)) + { + if (typeof(T).IsValueType) + value = ((T[])resultObj)[0]; // LUCENENET: Retrieve a 1 dimensionsal array for value types to avoid unboxing + else + value = (T)resultObj; + return true; + } + value = default; + return false; + } + /// /// Returns the value held by the given key. /// @@ -50,8 +76,9 @@ public virtual T Get(ConfigurationKey key) { throw new ArgumentNullException(nameof(key), "key cannot be null!"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) } - this.configMap.TryGetValue(key, out object result); - return result == null ? default : (T)result; + return !this.configMap.TryGetValue(key, out object result) || result is null ? default : + // LUCENENET: Retrieve a 1 dimensionsal array for value types to avoid unboxing + (typeof(T).IsValueType ? ((T[])result)[0] : (T)result); } /// @@ -87,6 +114,10 @@ public virtual void Set(ConfigurationKey key, T value) { Unset(key); } + else if (typeof(T).IsValueType) + { + this.configMap[key] = new T[] { value }; // LUCENENET: Store a 1 dimensionsal array for value types to avoid boxing + } else { this.configMap[key] = value; diff --git a/src/Lucene.Net.QueryParser/Flexible/Standard/Config/FieldBoostMapFCListener.cs b/src/Lucene.Net.QueryParser/Flexible/Standard/Config/FieldBoostMapFCListener.cs index 0679361d8d..c9ba05022d 100644 --- a/src/Lucene.Net.QueryParser/Flexible/Standard/Config/FieldBoostMapFCListener.cs +++ b/src/Lucene.Net.QueryParser/Flexible/Standard/Config/FieldBoostMapFCListener.cs @@ -41,15 +41,9 @@ public FieldBoostMapFCListener(QueryConfigHandler config) public virtual void BuildFieldConfig(FieldConfig fieldConfig) { - IDictionary fieldBoostMap = this.config.Get(ConfigurationKeys.FIELD_BOOST_MAP); - - if (fieldBoostMap != null) - { - if (fieldBoostMap.TryGetValue(fieldConfig.Field, out float? boost) && boost != null) - { + if (this.config.TryGetValue(ConfigurationKeys.FIELD_BOOST_MAP, out IDictionary fieldBoostMap) + && fieldBoostMap.TryGetValue(fieldConfig.Field, out float boost)) fieldConfig.Set(ConfigurationKeys.BOOST, boost); - } - } } } } diff --git a/src/Lucene.Net.QueryParser/Flexible/Standard/Config/FieldDateResolutionFCListener.cs b/src/Lucene.Net.QueryParser/Flexible/Standard/Config/FieldDateResolutionFCListener.cs index 322cedfe96..c6fdb1e62b 100644 --- a/src/Lucene.Net.QueryParser/Flexible/Standard/Config/FieldDateResolutionFCListener.cs +++ b/src/Lucene.Net.QueryParser/Flexible/Standard/Config/FieldDateResolutionFCListener.cs @@ -42,22 +42,12 @@ public FieldDateResolutionFCListener(QueryConfigHandler config) public virtual void BuildFieldConfig(FieldConfig fieldConfig) { - DateResolution? dateRes = null; - IDictionary dateResMap = this.config.Get(ConfigurationKeys.FIELD_DATE_RESOLUTION_MAP); - - if (dateResMap != null) - { - dateResMap.TryGetValue(fieldConfig.Field, out dateRes); - } - - if (dateRes == null) - { - dateRes = this.config.Get(ConfigurationKeys.DATE_RESOLUTION); - } - - if (dateRes != null) + // LUCENENET: Simplified logic using TryGetValue + if ((this.config.TryGetValue(ConfigurationKeys.FIELD_DATE_RESOLUTION_MAP, out IDictionary dateResMap) + && dateResMap.TryGetValue(fieldConfig.Field, out DateResolution dateRes)) + || this.config.TryGetValue(ConfigurationKeys.DATE_RESOLUTION, out dateRes)) { - fieldConfig.Set(ConfigurationKeys.DATE_RESOLUTION, dateRes.Value); + fieldConfig.Set(ConfigurationKeys.DATE_RESOLUTION, dateRes); } } } diff --git a/src/Lucene.Net.QueryParser/Flexible/Standard/Config/StandardQueryConfigHandler.cs b/src/Lucene.Net.QueryParser/Flexible/Standard/Config/StandardQueryConfigHandler.cs index 51d0529a10..314c2b5a17 100644 --- a/src/Lucene.Net.QueryParser/Flexible/Standard/Config/StandardQueryConfigHandler.cs +++ b/src/Lucene.Net.QueryParser/Flexible/Standard/Config/StandardQueryConfigHandler.cs @@ -50,11 +50,11 @@ public StandardQueryConfigHandler() Set(ConfigurationKeys.PHRASE_SLOP, 0); //default value 2.4 Set(ConfigurationKeys.LOWERCASE_EXPANDED_TERMS, true); //default value 2.4 Set(ConfigurationKeys.ENABLE_POSITION_INCREMENTS, false); //default value 2.4 - Set(ConfigurationKeys.FIELD_BOOST_MAP, new JCG.LinkedDictionary()); + Set(ConfigurationKeys.FIELD_BOOST_MAP, new JCG.LinkedDictionary()); Set(ConfigurationKeys.FUZZY_CONFIG, new FuzzyConfig()); Set(ConfigurationKeys.LOCALE, null); Set(ConfigurationKeys.MULTI_TERM_REWRITE_METHOD, MultiTermQuery.CONSTANT_SCORE_AUTO_REWRITE_DEFAULT); - Set(ConfigurationKeys.FIELD_DATE_RESOLUTION_MAP, new JCG.Dictionary()); + Set(ConfigurationKeys.FIELD_DATE_RESOLUTION_MAP, new JCG.Dictionary()); } /// @@ -76,19 +76,19 @@ public sealed class ConfigurationKeys /// Key used to set whether position increments is enabled /// /// - public readonly static ConfigurationKey ENABLE_POSITION_INCREMENTS = ConfigurationKey.NewInstance(); + public readonly static ConfigurationKey ENABLE_POSITION_INCREMENTS = ConfigurationKey.NewInstance(); /// /// Key used to set whether expanded terms should be lower-cased /// /// - public readonly static ConfigurationKey LOWERCASE_EXPANDED_TERMS = ConfigurationKey.NewInstance(); + public readonly static ConfigurationKey LOWERCASE_EXPANDED_TERMS = ConfigurationKey.NewInstance(); /// /// Key used to set whether leading wildcards are supported /// /// - public readonly static ConfigurationKey ALLOW_LEADING_WILDCARD = ConfigurationKey.NewInstance(); + public readonly static ConfigurationKey ALLOW_LEADING_WILDCARD = ConfigurationKey.NewInstance(); /// /// Key used to set the used for terms found in the query @@ -106,7 +106,7 @@ public sealed class ConfigurationKeys /// Key used to set the default phrase slop /// /// - public readonly static ConfigurationKey PHRASE_SLOP = ConfigurationKey.NewInstance(); + public readonly static ConfigurationKey PHRASE_SLOP = ConfigurationKey.NewInstance(); /// /// Key used to set the locale used when parsing the query @@ -134,14 +134,14 @@ public sealed class ConfigurationKeys /// Key used to set a field to boost map that is used to set the boost for each field /// /// - public readonly static ConfigurationKey> FIELD_BOOST_MAP = ConfigurationKey.NewInstance>(); + public readonly static ConfigurationKey> FIELD_BOOST_MAP = ConfigurationKey.NewInstance>(); /// /// Key used to set a field to map that is used /// to normalize each date field value. /// /// - public readonly static ConfigurationKey> FIELD_DATE_RESOLUTION_MAP = ConfigurationKey.NewInstance>(); + public readonly static ConfigurationKey> FIELD_DATE_RESOLUTION_MAP = ConfigurationKey.NewInstance>(); /// /// Key used to set the used to create fuzzy queries. @@ -161,7 +161,7 @@ public sealed class ConfigurationKeys /// Key used to set the boost value in objects. /// /// - public readonly static ConfigurationKey BOOST = ConfigurationKey.NewInstance(); + public readonly static ConfigurationKey BOOST = ConfigurationKey.NewInstance(); /// /// Key used to set a field to its . diff --git a/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/AnalyzerQueryNodeProcessor.cs b/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/AnalyzerQueryNodeProcessor.cs index 65c48e4cc4..e357b50af5 100644 --- a/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/AnalyzerQueryNodeProcessor.cs +++ b/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/AnalyzerQueryNodeProcessor.cs @@ -68,23 +68,22 @@ public AnalyzerQueryNodeProcessor() public override IQueryNode Process(IQueryNode queryTree) { - Analyzer analyzer = GetQueryConfigHandler().Get(ConfigurationKeys.ANALYZER); + var queryConfigHandler = GetQueryConfigHandler(); + Analyzer analyzer = queryConfigHandler.Get(ConfigurationKeys.ANALYZER); if (analyzer != null) { this.analyzer = analyzer; this.positionIncrementsEnabled = false; - bool? positionIncrementsEnabled = GetQueryConfigHandler().Get(ConfigurationKeys.ENABLE_POSITION_INCREMENTS); // LUCENENET specific - rather than using null, we are relying on the behavior that the default // value for an enum is 0 (OR in this case). - //var defaultOperator = GetQueryConfigHandler().Get(ConfigurationKeys.DEFAULT_OPERATOR); - //this.defaultOperator = defaultOperator != null ? defaultOperator.Value : Operator.OR; this.defaultOperator = GetQueryConfigHandler().Get(ConfigurationKeys.DEFAULT_OPERATOR); - if (positionIncrementsEnabled != null) + // LUCENENET: Use TryGetValue() to determine if the value exists + if (GetQueryConfigHandler().TryGetValue(ConfigurationKeys.ENABLE_POSITION_INCREMENTS, out bool positionIncrementsEnabled)) { - this.positionIncrementsEnabled = positionIncrementsEnabled.Value; + this.positionIncrementsEnabled = positionIncrementsEnabled; } if (this.analyzer != null) diff --git a/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/BoostQueryNodeProcessor.cs b/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/BoostQueryNodeProcessor.cs index 9a9342b8ac..a51de03bb4 100644 --- a/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/BoostQueryNodeProcessor.cs +++ b/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/BoostQueryNodeProcessor.cs @@ -48,11 +48,9 @@ protected override IQueryNode PostProcessNode(IQueryNode node) if (fieldConfig != null) { - float? boost = fieldConfig.Get(ConfigurationKeys.BOOST); - - if (boost != null) + if (fieldConfig.TryGetValue(ConfigurationKeys.BOOST, out float boost)) { - return new BoostQueryNode(node, boost.Value); + return new BoostQueryNode(node, boost); } } } diff --git a/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/DefaultPhraseSlopQueryNodeProcessor.cs b/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/DefaultPhraseSlopQueryNodeProcessor.cs index adf95115a7..43ea864e8c 100644 --- a/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/DefaultPhraseSlopQueryNodeProcessor.cs +++ b/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/DefaultPhraseSlopQueryNodeProcessor.cs @@ -51,11 +51,9 @@ public override IQueryNode Process(IQueryNode queryTree) if (queryConfig != null) { - int? defaultPhraseSlop = queryConfig.Get(ConfigurationKeys.PHRASE_SLOP); - - if (defaultPhraseSlop != null) + if (queryConfig.TryGetValue(ConfigurationKeys.PHRASE_SLOP, out int defaultPhraseSlop)) { - this.defaultPhraseSlop = defaultPhraseSlop.Value; + this.defaultPhraseSlop = defaultPhraseSlop; return base.Process(queryTree); } diff --git a/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/LowercaseExpandedTermsQueryNodeProcessor.cs b/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/LowercaseExpandedTermsQueryNodeProcessor.cs index f91ee5734d..fb907e7200 100644 --- a/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/LowercaseExpandedTermsQueryNodeProcessor.cs +++ b/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/LowercaseExpandedTermsQueryNodeProcessor.cs @@ -43,9 +43,8 @@ public LowercaseExpandedTermsQueryNodeProcessor() public override IQueryNode Process(IQueryNode queryTree) { - bool? lowercaseExpandedTerms = GetQueryConfigHandler().Get(ConfigurationKeys.LOWERCASE_EXPANDED_TERMS); - - if (lowercaseExpandedTerms != null && lowercaseExpandedTerms.Value) + if (GetQueryConfigHandler().TryGetValue(ConfigurationKeys.LOWERCASE_EXPANDED_TERMS, out bool lowercaseExpandedTerms) + && lowercaseExpandedTerms) { return base.Process(queryTree); } diff --git a/src/Lucene.Net.QueryParser/Flexible/Standard/StandardQueryParser.cs b/src/Lucene.Net.QueryParser/Flexible/Standard/StandardQueryParser.cs index 20b326dec3..52c673342f 100644 --- a/src/Lucene.Net.QueryParser/Flexible/Standard/StandardQueryParser.cs +++ b/src/Lucene.Net.QueryParser/Flexible/Standard/StandardQueryParser.cs @@ -160,7 +160,7 @@ public override Query Parse(string query, string defaultField) /// public virtual Operator DefaultOperator { - get => QueryConfigHandler.Get(ConfigurationKeys.DEFAULT_OPERATOR); + get => QueryConfigHandler.Get(ConfigurationKeys.DEFAULT_OPERATOR); // LUCENENET: The default value is OR, so we just rely on the compiler if it doesn't exist set => QueryConfigHandler.Set(ConfigurationKeys.DEFAULT_OPERATOR, value); } @@ -175,7 +175,7 @@ public virtual Operator DefaultOperator /// public virtual bool LowercaseExpandedTerms { - get => QueryConfigHandler.Get(ConfigurationKeys.LOWERCASE_EXPANDED_TERMS) ?? true; + get => QueryConfigHandler.TryGetValue(ConfigurationKeys.LOWERCASE_EXPANDED_TERMS, out bool value) ? value : true; set => QueryConfigHandler.Set(ConfigurationKeys.LOWERCASE_EXPANDED_TERMS, value); } @@ -190,7 +190,7 @@ public virtual bool LowercaseExpandedTerms /// public virtual bool AllowLeadingWildcard { - get => QueryConfigHandler.Get(ConfigurationKeys.ALLOW_LEADING_WILDCARD) ?? false; + get => QueryConfigHandler.Get(ConfigurationKeys.ALLOW_LEADING_WILDCARD); // LUCENENET: The default value is false, so we just rely on the compiler if it doesn't exist set => QueryConfigHandler.Set(ConfigurationKeys.ALLOW_LEADING_WILDCARD, value); } @@ -205,7 +205,7 @@ public virtual bool AllowLeadingWildcard /// public virtual bool EnablePositionIncrements { - get => QueryConfigHandler.Get(ConfigurationKeys.ENABLE_POSITION_INCREMENTS) ?? false; + get => QueryConfigHandler.Get(ConfigurationKeys.ENABLE_POSITION_INCREMENTS); // LUCENENET: The default value is false, so we just rely on the compiler if it doesn't exist set => QueryConfigHandler.Set(ConfigurationKeys.ENABLE_POSITION_INCREMENTS, value); } @@ -333,7 +333,7 @@ public virtual Analyzer Analyzer /// public virtual int PhraseSlop { - get => QueryConfigHandler.Get(ConfigurationKeys.PHRASE_SLOP) ?? 0; + get => QueryConfigHandler.Get(ConfigurationKeys.PHRASE_SLOP); // LUCENENET: The default value is 0, so we just rely on the compiler if it doesn't exist set => QueryConfigHandler.Set(ConfigurationKeys.PHRASE_SLOP, value); } @@ -369,7 +369,7 @@ public virtual float FuzzyMinSim /// /// Gets or Sets the field to boost map used to set boost for each field. /// - public virtual IDictionary FieldsBoost + public virtual IDictionary FieldsBoost { get => QueryConfigHandler.Get(ConfigurationKeys.FIELD_BOOST_MAP); set => QueryConfigHandler.Set(ConfigurationKeys.FIELD_BOOST_MAP, value); @@ -390,22 +390,23 @@ public virtual void SetDateResolution(DateResolution dateResolution) /// Gets the default used for certain field when /// no is defined for this field. /// - public virtual DateResolution DateResolution => QueryConfigHandler.Get(ConfigurationKeys.DATE_RESOLUTION); + [ExceptionToNullableEnumConvention] + public virtual DateResolution? DateResolution => QueryConfigHandler.TryGetValue(ConfigurationKeys.DATE_RESOLUTION, out DateResolution value) ? value : null; /// /// Sets the used for each field /// /// a collection that maps a field to its [Obsolete("Use DateResolutionMap property instead.")] - public virtual void SetDateResolution(IDictionary dateRes) + public virtual void SetDateResolution(IDictionary dateRes) { DateResolutionMap = dateRes; } /// - /// Gets or Sets the field to map used to normalize each date field. + /// Gets or Sets the field to map used to normalize each date field. /// - public virtual IDictionary DateResolutionMap + public virtual IDictionary DateResolutionMap { get => QueryConfigHandler.Get(ConfigurationKeys.FIELD_DATE_RESOLUTION_MAP); set => QueryConfigHandler.Set(ConfigurationKeys.FIELD_DATE_RESOLUTION_MAP, value); diff --git a/src/Lucene.Net.TestFramework/Analysis/BaseTokenStreamTestCase.cs b/src/Lucene.Net.TestFramework/Analysis/BaseTokenStreamTestCase.cs index 67e0fc0eb0..0311b7fcbd 100644 --- a/src/Lucene.Net.TestFramework/Analysis/BaseTokenStreamTestCase.cs +++ b/src/Lucene.Net.TestFramework/Analysis/BaseTokenStreamTestCase.cs @@ -199,8 +199,8 @@ public static void AssertTokenStreamContents(TokenStream ts, string[] output, in // *********** End From Lucene 8.2.0 ************** // Maps position to the start/end offset: - IDictionary posToStartOffset = new Dictionary(); - IDictionary posToEndOffset = new Dictionary(); + IDictionary posToStartOffset = new Dictionary(); + IDictionary posToEndOffset = new Dictionary(); ts.Reset(); int pos = -1; @@ -309,7 +309,7 @@ public static void AssertTokenStreamContents(TokenStream ts, string[] output, in int posLength = posLengthAtt.PositionLength; - if (!posToStartOffset.TryGetValue(pos, out int? oldStartOffset)) + if (!posToStartOffset.TryGetValue(pos, out int oldStartOffset)) { // First time we've seen a token leaving from this position: posToStartOffset[pos] = startOffset; @@ -320,12 +320,12 @@ public static void AssertTokenStreamContents(TokenStream ts, string[] output, in // We've seen a token leaving from this position // before; verify the startOffset is the same: //System.out.println(" + vs " + pos + " -> " + startOffset); - Assert.AreEqual(oldStartOffset.GetValueOrDefault(), startOffset, "pos=" + pos + " posLen=" + posLength + " token=" + termAtt); + Assert.AreEqual(oldStartOffset, startOffset, "pos=" + pos + " posLen=" + posLength + " token=" + termAtt); } int endPos = pos + posLength; - if (!posToEndOffset.TryGetValue(endPos, out int? oldEndOffset)) + if (!posToEndOffset.TryGetValue(endPos, out int oldEndOffset)) { // First time we've seen a token arriving to this position: posToEndOffset[endPos] = endOffset; @@ -336,7 +336,7 @@ public static void AssertTokenStreamContents(TokenStream ts, string[] output, in // We've seen a token arriving to this position // before; verify the endOffset is the same: //System.out.println(" + ve " + endPos + " -> " + endOffset); - Assert.AreEqual(oldEndOffset.GetValueOrDefault(), endOffset, "pos=" + pos + " posLen=" + posLength + " token=" + termAtt); + Assert.AreEqual(oldEndOffset, endOffset, "pos=" + pos + " posLen=" + posLength + " token=" + termAtt); } } } diff --git a/src/Lucene.Net.TestFramework/Codecs/RAMOnly/RAMOnlyPostingsFormat.cs b/src/Lucene.Net.TestFramework/Codecs/RAMOnly/RAMOnlyPostingsFormat.cs index 4f83a6fb39..9465e23642 100644 --- a/src/Lucene.Net.TestFramework/Codecs/RAMOnly/RAMOnlyPostingsFormat.cs +++ b/src/Lucene.Net.TestFramework/Codecs/RAMOnly/RAMOnlyPostingsFormat.cs @@ -569,7 +569,7 @@ public override long GetCost() } // Holds all indexes created, keyed by the ID assigned in fieldsConsumer - private readonly IDictionary state = new Dictionary(); + private readonly IDictionary state = new Dictionary(); private readonly AtomicInt64 nextID = new AtomicInt64(); @@ -650,7 +650,7 @@ public override FieldsProducer FieldsProducer(SegmentReadState readState) UninterruptableMonitor.Enter(state); try { - return state[id]; + return state.TryGetValue(id, out RAMPostings value) ? value : null; } finally { diff --git a/src/Lucene.Net.TestFramework/Index/BaseTermVectorsFormatTestCase.cs b/src/Lucene.Net.TestFramework/Index/BaseTermVectorsFormatTestCase.cs index 46f928cbe0..7bd5613b7e 100644 --- a/src/Lucene.Net.TestFramework/Index/BaseTermVectorsFormatTestCase.cs +++ b/src/Lucene.Net.TestFramework/Index/BaseTermVectorsFormatTestCase.cs @@ -828,7 +828,7 @@ public virtual void TestMerge() RandomDocumentFactory docFactory = new RandomDocumentFactory(this, 5, 20); int numDocs = AtLeast(100); int numDeletes = Random.Next(numDocs); - ISet deletes = new JCG.HashSet(); + ISet deletes = new JCG.HashSet(); while (deletes.Count < numDeletes) { deletes.Add(Random.Next(numDocs)); diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/CharFilters/TestMappingCharFilter.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/CharFilters/TestMappingCharFilter.cs index b6b6ceaaae..fd0a5aeae4 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/CharFilters/TestMappingCharFilter.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/CharFilters/TestMappingCharFilter.cs @@ -344,7 +344,7 @@ public virtual void TestRandomMaps2() StringBuilder output = new StringBuilder(); // Maps output offset to input offset: - IList inputOffsets = new JCG.List(); + IList inputOffsets = new JCG.List(); int cumDiff = 0; int charIdx = 0; @@ -446,7 +446,7 @@ public virtual void TestRandomMaps2() MappingCharFilter mapFilter = new MappingCharFilter(charMap, new StringReader(content)); StringBuilder actualBuilder = new StringBuilder(); - IList actualInputOffsets = new JCG.List(); + IList actualInputOffsets = new JCG.List(); // Now consume the actual mapFilter, somewhat randomly: while (true) diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/TestCharArraySet.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/TestCharArraySet.cs index 8492e10190..0101842c47 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/TestCharArraySet.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/TestCharArraySet.cs @@ -70,16 +70,16 @@ public virtual void TestNonZeroOffset() public virtual void TestObjectContains() { CharArraySet set = new CharArraySet(TEST_VERSION_CURRENT, 10, true); - int? val = Convert.ToInt32(1); + J2N.Numerics.Int32 val = J2N.Numerics.Int32.GetInstance(1); set.Add(val); assertTrue(set.Contains(val)); - assertTrue(set.Contains(new int?(1))); // another integer + assertTrue(set.Contains(J2N.Numerics.Int32.GetInstance(1))); // another integer assertTrue(set.Contains("1")); assertTrue(set.Contains(new char[] { '1' })); // test unmodifiable set = CharArraySet.UnmodifiableSet(set); assertTrue(set.Contains(val)); - assertTrue(set.Contains(new int?(1))); // another integer + assertTrue(set.Contains(J2N.Numerics.Int32.GetInstance(1))); // another integer assertTrue(set.Contains("1")); assertTrue(set.Contains(new char[] { '1' })); } diff --git a/src/Lucene.Net.Tests.Facet/SortedSet/TestSortedSetDocValuesFacets.cs b/src/Lucene.Net.Tests.Facet/SortedSet/TestSortedSetDocValuesFacets.cs index 1e546ee037..430db02792 100644 --- a/src/Lucene.Net.Tests.Facet/SortedSet/TestSortedSetDocValuesFacets.cs +++ b/src/Lucene.Net.Tests.Facet/SortedSet/TestSortedSetDocValuesFacets.cs @@ -354,10 +354,10 @@ public virtual void TestRandom() Facets facets = new SortedSetDocValuesFacetCounts(state, fc); // Slow, yet hopefully bug-free, faceting: - var expectedCounts = new JCG.List>(); + var expectedCounts = new JCG.List>(); for (int i = 0; i < numDims; i++) { - expectedCounts.Add(new Dictionary()); + expectedCounts.Add(new Dictionary()); } foreach (TestDoc doc in testDocs) @@ -368,7 +368,7 @@ public virtual void TestRandom() { if (doc.dims[j] != null) { - if (!expectedCounts[j].TryGetValue(doc.dims[j], out int? v)) + if (!expectedCounts[j].TryGetValue(doc.dims[j], out int v)) { expectedCounts[j][doc.dims[j]] = 1; } @@ -386,10 +386,10 @@ public virtual void TestRandom() { JCG.List labelValues = new JCG.List(); int totCount = 0; - foreach (KeyValuePair ent in expectedCounts[i]) + foreach (KeyValuePair ent in expectedCounts[i]) { - labelValues.Add(new LabelAndValue(ent.Key, ent.Value.Value)); - totCount += ent.Value.Value; + labelValues.Add(new LabelAndValue(ent.Key, ent.Value)); + totCount += ent.Value; } SortLabelValues(labelValues); if (totCount > 0) diff --git a/src/Lucene.Net.Tests.Facet/Taxonomy/TestTaxonomyCombined.cs b/src/Lucene.Net.Tests.Facet/Taxonomy/TestTaxonomyCombined.cs index 87cfab2738..d66a473cac 100644 --- a/src/Lucene.Net.Tests.Facet/Taxonomy/TestTaxonomyCombined.cs +++ b/src/Lucene.Net.Tests.Facet/Taxonomy/TestTaxonomyCombined.cs @@ -592,7 +592,7 @@ public virtual void TestChildrenArrays() { // find expected children by looking at all expectedCategories // for children - JCG.List expectedChildren = new JCG.List(); + JCG.List expectedChildren = new JCG.List(); for (int j = ExpectedCategories.Length - 1; j >= 0; j--) { if (ExpectedCategories[j].Length != ExpectedCategories[i].Length + 1) @@ -622,11 +622,11 @@ public virtual void TestChildrenArrays() else { int child = youngestChildArray[i]; - Assert.AreEqual((int)expectedChildren[0], child); + Assert.AreEqual(expectedChildren[0], child); for (int j = 1; j < expectedChildren.Count; j++) { child = olderSiblingArray[child]; - Assert.AreEqual((int)expectedChildren[j], child); + Assert.AreEqual(expectedChildren[j], child); // if child is INVALID_ORDINAL we should stop, but // AssertEquals would fail in this case anyway. } diff --git a/src/Lucene.Net.Tests.Facet/Taxonomy/TestTaxonomyFacetCounts.cs b/src/Lucene.Net.Tests.Facet/Taxonomy/TestTaxonomyFacetCounts.cs index c13e000996..b9caef7804 100644 --- a/src/Lucene.Net.Tests.Facet/Taxonomy/TestTaxonomyFacetCounts.cs +++ b/src/Lucene.Net.Tests.Facet/Taxonomy/TestTaxonomyFacetCounts.cs @@ -833,10 +833,10 @@ public virtual void TestRandom() Facets facets = GetTaxonomyFacetCounts(tr, config, fc); // Slow, yet hopefully bug-free, faceting: - var expectedCounts = new JCG.List>(); + var expectedCounts = new JCG.List>(); for (int i = 0; i < numDims; i++) { - expectedCounts.Add(new Dictionary()); + expectedCounts.Add(new Dictionary()); } foreach (TestDoc doc in testDocs) @@ -847,7 +847,7 @@ public virtual void TestRandom() { if (doc.dims[j] != null) { - if (!expectedCounts[j].TryGetValue(doc.dims[j], out int? v) || v == null) + if (!expectedCounts[j].TryGetValue(doc.dims[j], out int v)) { expectedCounts[j][doc.dims[j]] = 1; } @@ -865,10 +865,10 @@ public virtual void TestRandom() { JCG.List labelValues = new JCG.List(); int totCount = 0; - foreach (KeyValuePair ent in expectedCounts[i]) + foreach (KeyValuePair ent in expectedCounts[i]) { - labelValues.Add(new LabelAndValue(ent.Key, ent.Value.Value)); - totCount += ent.Value.Value; + labelValues.Add(new LabelAndValue(ent.Key, ent.Value)); + totCount += ent.Value; } SortLabelValues(labelValues); if (totCount > 0) diff --git a/src/Lucene.Net.Tests.Facet/Taxonomy/TestTaxonomyFacetCounts2.cs b/src/Lucene.Net.Tests.Facet/Taxonomy/TestTaxonomyFacetCounts2.cs index 035c20c53c..c7d1c5aa8c 100644 --- a/src/Lucene.Net.Tests.Facet/Taxonomy/TestTaxonomyFacetCounts2.cs +++ b/src/Lucene.Net.Tests.Facet/Taxonomy/TestTaxonomyFacetCounts2.cs @@ -85,7 +85,7 @@ static TestTaxonomyFacetCounts2() } private static Net.Store.Directory indexDir, taxoDir; - private static IDictionary allExpectedCounts, termExpectedCounts; + private static IDictionary allExpectedCounts, termExpectedCounts; [OneTimeTearDown] public override void AfterClass() // LUCENENET specific - renamed from AfterClassCountingFacetsAggregatorTest() to ensure calling order @@ -170,7 +170,7 @@ private static void IndexDocsNoFacets(IndexWriter indexWriter) indexWriter.Commit(); // flush a segment } - private static void IndexDocsWithFacetsNoTerms(IndexWriter indexWriter, ITaxonomyWriter taxoWriter, IDictionary expectedCounts) + private static void IndexDocsWithFacetsNoTerms(IndexWriter indexWriter, ITaxonomyWriter taxoWriter, IDictionary expectedCounts) { Random random = Random; int numDocs = AtLeast(random, 2); @@ -184,7 +184,7 @@ private static void IndexDocsWithFacetsNoTerms(IndexWriter indexWriter, ITaxonom indexWriter.Commit(); // flush a segment } - private static void IndexDocsWithFacetsAndTerms(IndexWriter indexWriter, ITaxonomyWriter taxoWriter, IDictionary expectedCounts) + private static void IndexDocsWithFacetsAndTerms(IndexWriter indexWriter, ITaxonomyWriter taxoWriter, IDictionary expectedCounts) { Random random = Random; int numDocs = AtLeast(random, 2); @@ -199,7 +199,7 @@ private static void IndexDocsWithFacetsAndTerms(IndexWriter indexWriter, ITaxono indexWriter.Commit(); // flush a segment } - private static void IndexDocsWithFacetsAndSomeTerms(IndexWriter indexWriter, ITaxonomyWriter taxoWriter, IDictionary expectedCounts) + private static void IndexDocsWithFacetsAndSomeTerms(IndexWriter indexWriter, ITaxonomyWriter taxoWriter, IDictionary expectedCounts) { Random random = Random; int numDocs = AtLeast(random, 2); @@ -219,9 +219,9 @@ private static void IndexDocsWithFacetsAndSomeTerms(IndexWriter indexWriter, ITa } // initialize expectedCounts w/ 0 for all categories - private static IDictionary newCounts() + private static IDictionary newCounts() { - IDictionary counts = new Dictionary(); + IDictionary counts = new Dictionary(); counts[CP_A] = 0; counts[CP_B] = 0; counts[CP_C] = 0; @@ -298,13 +298,13 @@ public virtual void TestDifferentNumResults() Assert.AreEqual(-1, (int)result.Value); foreach (LabelAndValue labelValue in result.LabelValues) { - Assert.AreEqual(termExpectedCounts[CP_A + "/" + labelValue.Label].GetValueOrDefault(), labelValue.Value); + Assert.AreEqual(termExpectedCounts[CP_A + "/" + labelValue.Label], labelValue.Value); } result = facets.GetTopChildren(NUM_CHILDREN_CP_B, CP_B); - Assert.AreEqual(termExpectedCounts[CP_B].GetValueOrDefault(), result.Value); + Assert.AreEqual(termExpectedCounts[CP_B], result.Value); foreach (LabelAndValue labelValue in result.LabelValues) { - Assert.AreEqual(termExpectedCounts[CP_B + "/" + labelValue.Label].GetValueOrDefault(), labelValue.Value); + Assert.AreEqual(termExpectedCounts[CP_B + "/" + labelValue.Label], labelValue.Value); } IOUtils.Dispose(indexReader, taxoReader); @@ -327,17 +327,17 @@ public virtual void TestAllCounts() int prevValue = int.MaxValue; foreach (LabelAndValue labelValue in result.LabelValues) { - Assert.AreEqual(allExpectedCounts[CP_A + "/" + labelValue.Label].GetValueOrDefault(), labelValue.Value); + Assert.AreEqual(allExpectedCounts[CP_A + "/" + labelValue.Label], labelValue.Value); Assert.IsTrue((int)labelValue.Value <= prevValue, "wrong sort order of sub results: labelValue.value=" + labelValue.Value + " prevValue=" + prevValue); prevValue = (int)labelValue.Value; } result = facets.GetTopChildren(NUM_CHILDREN_CP_B, CP_B); - Assert.AreEqual(allExpectedCounts[CP_B].GetValueOrDefault(), result.Value); + Assert.AreEqual(allExpectedCounts[CP_B], result.Value); prevValue = int.MaxValue; foreach (LabelAndValue labelValue in result.LabelValues) { - Assert.AreEqual(allExpectedCounts[CP_B + "/" + labelValue.Label].GetValueOrDefault(), labelValue.Value); + Assert.AreEqual(allExpectedCounts[CP_B + "/" + labelValue.Label], labelValue.Value); Assert.IsTrue((int)labelValue.Value <= prevValue, "wrong sort order of sub results: labelValue.value=" + labelValue.Value + " prevValue=" + prevValue); prevValue = (int)labelValue.Value; } @@ -361,13 +361,13 @@ public virtual void TestBigNumResults() Assert.AreEqual(-1, (int)result.Value); foreach (LabelAndValue labelValue in result.LabelValues) { - Assert.AreEqual(allExpectedCounts[CP_A + "/" + labelValue.Label].GetValueOrDefault(), labelValue.Value); + Assert.AreEqual(allExpectedCounts[CP_A + "/" + labelValue.Label], labelValue.Value); } result = facets.GetTopChildren(int.MaxValue, CP_B); - Assert.AreEqual(allExpectedCounts[CP_B].GetValueOrDefault(), result.Value); + Assert.AreEqual(allExpectedCounts[CP_B], result.Value); foreach (LabelAndValue labelValue in result.LabelValues) { - Assert.AreEqual(allExpectedCounts[CP_B + "/" + labelValue.Label].GetValueOrDefault(), labelValue.Value); + Assert.AreEqual(allExpectedCounts[CP_B + "/" + labelValue.Label], labelValue.Value); } IOUtils.Dispose(indexReader, taxoReader); @@ -386,16 +386,16 @@ public virtual void TestNoParents() Facets facets = GetTaxonomyFacetCounts(taxoReader, GetConfig(), sfc); FacetResult result = facets.GetTopChildren(NUM_CHILDREN_CP_C, CP_C); - Assert.AreEqual(allExpectedCounts[CP_C].GetValueOrDefault(), result.Value); + Assert.AreEqual(allExpectedCounts[CP_C], result.Value); foreach (LabelAndValue labelValue in result.LabelValues) { - Assert.AreEqual(allExpectedCounts[CP_C + "/" + labelValue.Label].GetValueOrDefault(), labelValue.Value); + Assert.AreEqual(allExpectedCounts[CP_C + "/" + labelValue.Label], labelValue.Value); } result = facets.GetTopChildren(NUM_CHILDREN_CP_D, CP_D); - Assert.AreEqual(allExpectedCounts[CP_C].GetValueOrDefault(), result.Value); + Assert.AreEqual(allExpectedCounts[CP_C], result.Value); foreach (LabelAndValue labelValue in result.LabelValues) { - Assert.AreEqual(allExpectedCounts[CP_D + "/" + labelValue.Label].GetValueOrDefault(), labelValue.Value); + Assert.AreEqual(allExpectedCounts[CP_D + "/" + labelValue.Label], labelValue.Value); } IOUtils.Dispose(indexReader, taxoReader); diff --git a/src/Lucene.Net.Tests.Facet/Taxonomy/TestTaxonomyFacetSumValueSource.cs b/src/Lucene.Net.Tests.Facet/Taxonomy/TestTaxonomyFacetSumValueSource.cs index 82021613c6..e0b44a7316 100644 --- a/src/Lucene.Net.Tests.Facet/Taxonomy/TestTaxonomyFacetSumValueSource.cs +++ b/src/Lucene.Net.Tests.Facet/Taxonomy/TestTaxonomyFacetSumValueSource.cs @@ -555,10 +555,10 @@ public virtual void TestRandom() Facets facets = new TaxonomyFacetSumValueSource(tr, config, fc, values); // Slow, yet hopefully bug-free, faceting: - var expectedValues = new JCG.List>(numDims); + var expectedValues = new JCG.List>(numDims); for (int i = 0; i < numDims; i++) { - expectedValues.Add(new Dictionary()); + expectedValues.Add(new Dictionary()); } foreach (TestDoc doc in testDocs) @@ -569,7 +569,7 @@ public virtual void TestRandom() { if (doc.dims[j] != null) { - if (!expectedValues[j].TryGetValue(doc.dims[j], out float? v) || v == null) + if (!expectedValues[j].TryGetValue(doc.dims[j], out float v)) { expectedValues[j][doc.dims[j]] = doc.value; } @@ -587,10 +587,10 @@ public virtual void TestRandom() { JCG.List labelValues = new JCG.List(); float totValue = 0; - foreach (KeyValuePair ent in expectedValues[i]) + foreach (KeyValuePair ent in expectedValues[i]) { - labelValues.Add(new LabelAndValue(ent.Key, ent.Value.Value)); - totValue += ent.Value.Value; + labelValues.Add(new LabelAndValue(ent.Key, ent.Value)); + totValue += ent.Value; } SortLabelValues(labelValues); if (totValue > 0) diff --git a/src/Lucene.Net.Tests.Facet/TestDrillSideways.cs b/src/Lucene.Net.Tests.Facet/TestDrillSideways.cs index f82ef09a92..b9f436bf86 100644 --- a/src/Lucene.Net.Tests.Facet/TestDrillSideways.cs +++ b/src/Lucene.Net.Tests.Facet/TestDrillSideways.cs @@ -796,7 +796,7 @@ public virtual void TestRandom() DrillSidewaysResult actual = ds.Search(ddq, filter, null, numDocs, sort, true, true); TopDocs hits = s.Search(baseQuery, numDocs); - IDictionary scores = new Dictionary(); + IDictionary scores = new Dictionary(); foreach (ScoreDoc sd in hits.ScoreDocs) { scores[s.Doc(sd.Doc).Get("id")] = sd.Score; @@ -1135,7 +1135,7 @@ private TestFacetResult slowDrillSidewaysSearch(IndexSearcher s, IList docs } //nextDocBreak:// Not referenced - IDictionary idToDocID = new Dictionary(); + IDictionary idToDocID = new Dictionary(); for (int i = 0; i < s.IndexReader.MaxDoc; i++) { idToDocID[s.Doc(i).Get("id")] = i; @@ -1171,7 +1171,7 @@ private TestFacetResult slowDrillSidewaysSearch(IndexSearcher s, IList docs return res; } - internal virtual void VerifyEquals(string[][] dimValues, IndexSearcher s, TestFacetResult expected, DrillSidewaysResult actual, IDictionary scores, bool isSortedSetDV) + internal virtual void VerifyEquals(string[][] dimValues, IndexSearcher s, TestFacetResult expected, DrillSidewaysResult actual, IDictionary scores, bool isSortedSetDV) { if (Verbose) { @@ -1187,7 +1187,7 @@ internal virtual void VerifyEquals(string[][] dimValues, IndexSearcher s, TestFa } Assert.AreEqual(expected.Hits[i].id, s.Doc(actual.Hits.ScoreDocs[i].Doc).Get("id")); // Score should be IDENTICAL: - Assert.AreEqual(scores[expected.Hits[i].id].GetValueOrDefault(), actual.Hits.ScoreDocs[i].Score, 0.0f); + Assert.AreEqual(scores[expected.Hits[i].id], actual.Hits.ScoreDocs[i].Score, 0.0f); } for (int dim = 0; dim < expected.Counts.Length; dim++) @@ -1201,7 +1201,7 @@ internal virtual void VerifyEquals(string[][] dimValues, IndexSearcher s, TestFa } int idx = 0; - IDictionary actualValues = new Dictionary(); + IDictionary actualValues = new Dictionary(); if (fr != null) { diff --git a/src/Lucene.Net.Tests.Queries/Mlt/TestMoreLikeThis.cs b/src/Lucene.Net.Tests.Queries/Mlt/TestMoreLikeThis.cs index 159443dfe8..fcc5482e46 100644 --- a/src/Lucene.Net.Tests.Queries/Mlt/TestMoreLikeThis.cs +++ b/src/Lucene.Net.Tests.Queries/Mlt/TestMoreLikeThis.cs @@ -73,7 +73,7 @@ private void AddDoc(RandomIndexWriter writer, string text) [Test] public void TestBoostFactor() { - IDictionary originalValues = OriginalValues; + IDictionary originalValues = GetOriginalValues(); MoreLikeThis mlt = new MoreLikeThis(reader); mlt.Analyzer = new MockAnalyzer(Random, MockTokenizer.WHITESPACE, false); @@ -96,7 +96,7 @@ public void TestBoostFactor() foreach (BooleanClause clause in clauses) { TermQuery tq = (TermQuery)clause.Query; - float? termBoost = originalValues[tq.Term.Text]; + float termBoost = originalValues[tq.Term.Text]; assertNotNull("Expected term " + tq.Term.Text, termBoost); float totalBoost = (float) (termBoost * boostFactor); @@ -105,28 +105,25 @@ public void TestBoostFactor() } } - private IDictionary OriginalValues + private IDictionary GetOriginalValues() { - get - { - IDictionary originalValues = new Dictionary(); - MoreLikeThis mlt = new MoreLikeThis(reader); - mlt.Analyzer = new MockAnalyzer(Random, MockTokenizer.WHITESPACE, false); - mlt.MinDocFreq = 1; - mlt.MinTermFreq = 1; - mlt.MinWordLen = 1; - mlt.FieldNames = new[] { "text" }; - mlt.ApplyBoost = true; - BooleanQuery query = (BooleanQuery)mlt.Like(new StringReader("lucene release"), "text"); - IList clauses = query.Clauses; + IDictionary originalValues = new Dictionary(); + MoreLikeThis mlt = new MoreLikeThis(reader); + mlt.Analyzer = new MockAnalyzer(Random, MockTokenizer.WHITESPACE, false); + mlt.MinDocFreq = 1; + mlt.MinTermFreq = 1; + mlt.MinWordLen = 1; + mlt.FieldNames = new[] { "text" }; + mlt.ApplyBoost = true; + BooleanQuery query = (BooleanQuery)mlt.Like(new StringReader("lucene release"), "text"); + IList clauses = query.Clauses; - foreach (BooleanClause clause in clauses) - { - TermQuery tq = (TermQuery)clause.Query; - originalValues[tq.Term.Text] = tq.Boost; - } - return originalValues; + foreach (BooleanClause clause in clauses) + { + TermQuery tq = (TermQuery)clause.Query; + originalValues[tq.Term.Text] = tq.Boost; } + return originalValues; } // LUCENE-3326 diff --git a/src/Lucene.Net.Tests.Queries/TestCustomScoreQuery.cs b/src/Lucene.Net.Tests.Queries/TestCustomScoreQuery.cs index 7c60bc0b1c..c5c4765ad2 100644 --- a/src/Lucene.Net.Tests.Queries/TestCustomScoreQuery.cs +++ b/src/Lucene.Net.Tests.Queries/TestCustomScoreQuery.cs @@ -395,7 +395,7 @@ private void VerifyResults(float boost, IndexSearcher s, } } - private void LogResult(string msg, IndexSearcher s, Query q, int doc, float? score1) + private void LogResult(string msg, IndexSearcher s, Query q, int doc, float score1) { Log(msg + " " + score1); Log("Explain by: " + q); diff --git a/src/Lucene.Net.Tests.QueryParser/Flexible/Precedence/TestPrecedenceQueryParser.cs b/src/Lucene.Net.Tests.QueryParser/Flexible/Precedence/TestPrecedenceQueryParser.cs index fc7a51da27..e1373083c4 100644 --- a/src/Lucene.Net.Tests.QueryParser/Flexible/Precedence/TestPrecedenceQueryParser.cs +++ b/src/Lucene.Net.Tests.QueryParser/Flexible/Precedence/TestPrecedenceQueryParser.cs @@ -483,7 +483,7 @@ public void TestDateRange() String hourField = "hour"; PrecedenceQueryParser qp = new PrecedenceQueryParser(new MockAnalyzer(Random)); - IDictionary fieldMap = new JCG.Dictionary(); + IDictionary fieldMap = new JCG.Dictionary(); // set a field specific date resolution fieldMap.Put(monthField, DateResolution.MONTH); #pragma warning disable 612, 618 diff --git a/src/Lucene.Net.Tests.QueryParser/Flexible/Standard/TestMultiFieldQPHelper.cs b/src/Lucene.Net.Tests.QueryParser/Flexible/Standard/TestMultiFieldQPHelper.cs index fd2573a683..9a31c2c5c8 100644 --- a/src/Lucene.Net.Tests.QueryParser/Flexible/Standard/TestMultiFieldQPHelper.cs +++ b/src/Lucene.Net.Tests.QueryParser/Flexible/Standard/TestMultiFieldQPHelper.cs @@ -143,7 +143,7 @@ public void TestSimple() [Test] public void TestBoostsSimple() { - IDictionary boosts = new Dictionary(); + IDictionary boosts = new Dictionary(); boosts.Put("b", 5); boosts.Put("t", 10); String[] fields = { "b", "t" }; diff --git a/src/Lucene.Net.Tests.QueryParser/Flexible/Standard/TestQPHelper.cs b/src/Lucene.Net.Tests.QueryParser/Flexible/Standard/TestQPHelper.cs index e4ba9a25db..78ad0ea1bd 100644 --- a/src/Lucene.Net.Tests.QueryParser/Flexible/Standard/TestQPHelper.cs +++ b/src/Lucene.Net.Tests.QueryParser/Flexible/Standard/TestQPHelper.cs @@ -799,7 +799,7 @@ public void TestDateRange() String hourField = "hour"; StandardQueryParser qp = new StandardQueryParser(); - IDictionary dateRes = new Dictionary(); + IDictionary dateRes = new Dictionary(); // set a field specific date resolution dateRes.Put(monthField, DateResolution.MONTH); diff --git a/src/Lucene.Net.Tests.Spatial/PortedSolr3Test.cs b/src/Lucene.Net.Tests.Spatial/PortedSolr3Test.cs index 5ee7789614..5706bc5e46 100644 --- a/src/Lucene.Net.Tests.Spatial/PortedSolr3Test.cs +++ b/src/Lucene.Net.Tests.Spatial/PortedSolr3Test.cs @@ -187,14 +187,14 @@ private void _CheckHits(bool bbox, IPoint pt, double distKM, int assertNumFound, assertEquals("" + shape, assertNumFound, results.numFound); if (assertIds != null) { - ISet resultIds = new JCG.HashSet(); + ISet resultIds = new JCG.HashSet(); foreach (SearchResult result in results.results) { - resultIds.add(int.Parse(result.document.Get("id"), CultureInfo.InvariantCulture)); + resultIds.Add(int.Parse(result.document.Get("id"), CultureInfo.InvariantCulture)); } foreach (int assertId in assertIds) { - assertTrue("has " + assertId, resultIds.contains(assertId)); + assertTrue("has " + assertId, resultIds.Contains(assertId)); } } } diff --git a/src/Lucene.Net.Tests.Spatial/Prefix/TestRecursivePrefixTreeStrategy.cs b/src/Lucene.Net.Tests.Spatial/Prefix/TestRecursivePrefixTreeStrategy.cs index c3be98e3f1..2db1688d9c 100644 --- a/src/Lucene.Net.Tests.Spatial/Prefix/TestRecursivePrefixTreeStrategy.cs +++ b/src/Lucene.Net.Tests.Spatial/Prefix/TestRecursivePrefixTreeStrategy.cs @@ -113,14 +113,14 @@ private void checkHits(SpatialArgs args, int assertNumFound, int[] assertIds) assertEquals("" + args, assertNumFound, got.numFound); if (assertIds != null) { - ISet gotIds = new JCG.HashSet(); + ISet gotIds = new JCG.HashSet(); foreach (SearchResult result in got.results) { - gotIds.add(int.Parse(result.document.Get("id"), CultureInfo.InvariantCulture)); + gotIds.Add(int.Parse(result.document.Get("id"), CultureInfo.InvariantCulture)); } foreach (int assertId in assertIds) { - assertTrue("has " + assertId, gotIds.contains(assertId)); + assertTrue("has " + assertId, gotIds.Contains(assertId)); } } } diff --git a/src/Lucene.Net.Tests.Suggest/Suggest/Analyzing/TestFreeTextSuggester.cs b/src/Lucene.Net.Tests.Suggest/Suggest/Analyzing/TestFreeTextSuggester.cs index 8c5fb98dfa..a4e6682680 100644 --- a/src/Lucene.Net.Tests.Suggest/Suggest/Analyzing/TestFreeTextSuggester.cs +++ b/src/Lucene.Net.Tests.Suggest/Suggest/Analyzing/TestFreeTextSuggester.cs @@ -420,14 +420,14 @@ public void TestRandom() sug.Build(new TestRandomInputEnumerator(docs)); // Build inefficient but hopefully correct model: - IList> gramCounts = new JCG.List>(grams); + IList> gramCounts = new JCG.List>(grams); for (int gram = 0; gram < grams; gram++) { if (Verbose) { Console.WriteLine("TEST: build model for gram=" + gram); } - IDictionary model = new JCG.Dictionary(); + IDictionary model = new JCG.Dictionary(); gramCounts.Add(model); foreach (string[] doc in docs) { @@ -443,7 +443,7 @@ public void TestRandom() b.append(doc[j]); } string token = b.toString(); - if (!model.TryGetValue(token, out int? curCount) || curCount == null) + if (!model.TryGetValue(token, out int curCount)) { model.Put(token, 1); } @@ -453,7 +453,7 @@ public void TestRandom() } if (Verbose) { - Console.WriteLine(" add '" + token + "' -> count=" + (model.TryGetValue(token, out int? count) ? (count.HasValue ? count.ToString() : "null") : "")); + Console.WriteLine(" add '" + token + "' -> count=" + (model.TryGetValue(token, out int count) ? count.ToString() : "")); } } } @@ -558,7 +558,7 @@ public void TestRandom() { //int? count = gramCounts.get(i - 1).get(context); var gramCount = gramCounts[i - 1]; - if (!gramCount.TryGetValue(context, out int? count) || count == null) + if (!gramCount.TryGetValue(context, out int count)) { // We never saw this context: backoff *= FreeTextSuggester.ALPHA; @@ -568,13 +568,13 @@ public void TestRandom() } continue; } - contextCount = count.GetValueOrDefault(); + contextCount = count; } if (Verbose) { Console.WriteLine(" contextCount=" + contextCount); } - IDictionary model = gramCounts[i]; + IDictionary model = gramCounts[i]; // First pass, gather all predictions for this model: if (Verbose) @@ -600,7 +600,7 @@ public void TestRandom() } string ngram = (context + " " + term).Trim(); //Integer count = model.get(ngram); - if (model.TryGetValue(ngram, out int? count) && count != null) + if (model.TryGetValue(ngram, out int count)) { // LUCENENET NOTE: We need to calculate this as decimal because when using double it can sometimes // return numbers that are greater than long.MaxValue, which results in a negative long number. diff --git a/src/Lucene.Net.Tests/Index/TestDocTermOrds.cs b/src/Lucene.Net.Tests/Index/TestDocTermOrds.cs index 22b3371fc1..7c6138b9e0 100644 --- a/src/Lucene.Net.Tests/Index/TestDocTermOrds.cs +++ b/src/Lucene.Net.Tests/Index/TestDocTermOrds.cs @@ -131,7 +131,7 @@ public virtual void TestRandom() RandomIndexWriter w = new RandomIndexWriter(Random, dir, conf); int[][] idToOrds = new int[NUM_DOCS][]; - ISet ordsForDocSet = new JCG.HashSet(); + ISet ordsForDocSet = new JCG.HashSet(); for (int id = 0; id < NUM_DOCS; id++) { @@ -244,7 +244,7 @@ public virtual void TestRandomWithPrefix() RandomIndexWriter w = new RandomIndexWriter(Random, dir, conf); int[][] idToOrds = new int[NUM_DOCS][]; - ISet ordsForDocSet = new JCG.HashSet(); + ISet ordsForDocSet = new JCG.HashSet(); for (int id = 0; id < NUM_DOCS; id++) { @@ -296,7 +296,7 @@ public virtual void TestRandomWithPrefix() for (int id = 0; id < NUM_DOCS; id++) { int[] docOrds = idToOrds[id]; - IList newOrds = new JCG.List(); + IList newOrds = new JCG.List(); foreach (int ord in idToOrds[id]) { if (StringHelper.StartsWith(termsArray[ord], prefixRef)) diff --git a/src/Lucene.Net.Tests/Index/TestDocValuesWithThreads.cs b/src/Lucene.Net.Tests/Index/TestDocValuesWithThreads.cs index f1b65ab05d..587f4117fc 100644 --- a/src/Lucene.Net.Tests/Index/TestDocValuesWithThreads.cs +++ b/src/Lucene.Net.Tests/Index/TestDocValuesWithThreads.cs @@ -51,7 +51,7 @@ public virtual void Test() Directory dir = NewDirectory(); IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMergePolicy(NewLogMergePolicy())); - IList numbers = new JCG.List(); + IList numbers = new JCG.List(); IList binary = new JCG.List(); IList sorted = new JCG.List(); int numDocs = AtLeast(100); @@ -103,7 +103,7 @@ private class ThreadAnonymousClass : ThreadJob { private readonly TestDocValuesWithThreads outerInstance; - private readonly IList numbers; + private readonly IList numbers; private readonly IList binary; private readonly IList sorted; private readonly int numDocs; @@ -111,7 +111,7 @@ private class ThreadAnonymousClass : ThreadJob private readonly CountdownEvent startingGun; private readonly Random threadRandom; - public ThreadAnonymousClass(TestDocValuesWithThreads outerInstance, IList numbers, IList binary, IList sorted, int numDocs, AtomicReader ar, CountdownEvent startingGun, Random threadRandom) + public ThreadAnonymousClass(TestDocValuesWithThreads outerInstance, IList numbers, IList binary, IList sorted, int numDocs, AtomicReader ar, CountdownEvent startingGun, Random threadRandom) { this.outerInstance = outerInstance; this.numbers = numbers; @@ -143,16 +143,16 @@ public override void Run() { #pragma warning disable 612, 618 case 0: - Assert.AreEqual((long)(sbyte)numbers[docID], (sbyte)FieldCache.DEFAULT.GetBytes(ar, "number", false).Get(docID)); + Assert.AreEqual((sbyte)numbers[docID], (sbyte)FieldCache.DEFAULT.GetBytes(ar, "number", false).Get(docID)); break; case 1: - Assert.AreEqual((long)(short)numbers[docID], FieldCache.DEFAULT.GetInt16s(ar, "number", false).Get(docID)); + Assert.AreEqual((short)numbers[docID], FieldCache.DEFAULT.GetInt16s(ar, "number", false).Get(docID)); break; #pragma warning restore 612, 618 case 2: - Assert.AreEqual((long)(int)numbers[docID], FieldCache.DEFAULT.GetInt32s(ar, "number", false).Get(docID)); + Assert.AreEqual((int)numbers[docID], FieldCache.DEFAULT.GetInt32s(ar, "number", false).Get(docID)); break; case 3: diff --git a/src/Lucene.Net.Tests/Index/TestDocsAndPositions.cs b/src/Lucene.Net.Tests/Index/TestDocsAndPositions.cs index b854216ec8..7ac3501d40 100644 --- a/src/Lucene.Net.Tests/Index/TestDocsAndPositions.cs +++ b/src/Lucene.Net.Tests/Index/TestDocsAndPositions.cs @@ -129,13 +129,13 @@ public virtual void TestRandomPositions() int numDocs = AtLeast(47); int max = 1051; int term = Random.Next(max); - int?[][] positionsInDoc = new int?[numDocs][]; + int[][] positionsInDoc = new int[numDocs][]; FieldType customType = new FieldType(TextField.TYPE_NOT_STORED); customType.OmitNorms = true; for (int i = 0; i < numDocs; i++) { Document doc = new Document(); - JCG.List positions = new JCG.List(); + JCG.List positions = new JCG.List(); StringBuilder builder = new StringBuilder(); int num = AtLeast(131); for (int j = 0; j < num; j++) @@ -188,7 +188,7 @@ public virtual void TestRandomPositions() { break; } - int?[] pos = positionsInDoc[atomicReaderContext.DocBase + docID]; + int[] pos = positionsInDoc[atomicReaderContext.DocBase + docID]; Assert.AreEqual(pos.Length, docsAndPosEnum.Freq); // number of positions read should be random - don't read all of them // allways diff --git a/src/Lucene.Net.Tests/Index/TestDocumentsWriterDeleteQueue.cs b/src/Lucene.Net.Tests/Index/TestDocumentsWriterDeleteQueue.cs index 593a618ddb..a83254d11c 100644 --- a/src/Lucene.Net.Tests/Index/TestDocumentsWriterDeleteQueue.cs +++ b/src/Lucene.Net.Tests/Index/TestDocumentsWriterDeleteQueue.cs @@ -45,7 +45,7 @@ public virtual void TestUpdateDelteSlices() { DocumentsWriterDeleteQueue queue = new DocumentsWriterDeleteQueue(); int size = 200 + Random.Next(500) * RandomMultiplier; - int?[] ids = new int?[size]; + int[] ids = new int[size]; for (int i = 0; i < ids.Length; i++) { ids[i] = Random.Next(); @@ -59,7 +59,7 @@ public virtual void TestUpdateDelteSlices() ISet uniqueValues = new JCG.HashSet(); for (int j = 0; j < ids.Length; j++) { - int? i = ids[j]; + int i = ids[j]; // create an array here since we compare identity below against tailItem Term[] term = new Term[] { new Term("id", i.ToString()) }; uniqueValues.Add(term[0]); @@ -135,7 +135,7 @@ private bool SetEqualsCollection(ISet setA, ICollection setB) return true; } - private void AssertAllBetween(int start, int end, BufferedUpdates deletes, int?[] ids) + private void AssertAllBetween(int start, int end, BufferedUpdates deletes, int[] ids) { for (int i = start; i <= end; i++) { @@ -255,7 +255,7 @@ public virtual void TestStressDeleteQueue() DocumentsWriterDeleteQueue queue = new DocumentsWriterDeleteQueue(); ISet uniqueValues = new JCG.HashSet(); int size = 10000 + Random.Next(500) * RandomMultiplier; - int?[] ids = new int?[size]; + int[] ids = new int[size]; for (int i = 0; i < ids.Length; i++) { ids[i] = Random.Next(); @@ -301,12 +301,12 @@ private class UpdateThread : ThreadJob { internal readonly DocumentsWriterDeleteQueue queue; internal readonly AtomicInt32 index; - internal readonly int?[] ids; + internal readonly int[] ids; internal readonly DeleteSlice slice; internal readonly BufferedUpdates deletes; internal readonly CountdownEvent latch; - protected internal UpdateThread(DocumentsWriterDeleteQueue queue, AtomicInt32 index, int?[] ids, CountdownEvent latch) + protected internal UpdateThread(DocumentsWriterDeleteQueue queue, AtomicInt32 index, int[] ids, CountdownEvent latch) { this.queue = queue; this.index = index; diff --git a/src/Lucene.Net.Tests/Index/TestIndexWriterDelete.cs b/src/Lucene.Net.Tests/Index/TestIndexWriterDelete.cs index dcbd2e3a3f..3800db1ed2 100644 --- a/src/Lucene.Net.Tests/Index/TestIndexWriterDelete.cs +++ b/src/Lucene.Net.Tests/Index/TestIndexWriterDelete.cs @@ -1114,7 +1114,7 @@ public virtual void TestDeleteAllSlowly() #endif Random, dir); int NUM_DOCS = AtLeast(1000); - IList ids = new JCG.List(NUM_DOCS); + IList ids = new JCG.List(NUM_DOCS); for (int id = 0; id < NUM_DOCS; id++) { ids.Add(id); diff --git a/src/Lucene.Net.Tests/Index/TestMaxTermFrequency.cs b/src/Lucene.Net.Tests/Index/TestMaxTermFrequency.cs index 07ea8450c9..80acf04d5a 100644 --- a/src/Lucene.Net.Tests/Index/TestMaxTermFrequency.cs +++ b/src/Lucene.Net.Tests/Index/TestMaxTermFrequency.cs @@ -46,7 +46,7 @@ public class TestMaxTermFrequency : LuceneTestCase private Directory dir; private IndexReader reader; /* expected maxTermFrequency values for our documents */ - private readonly IList expected = new JCG.List(); + private readonly IList expected = new JCG.List(); [SetUp] public override void SetUp() @@ -82,7 +82,7 @@ public virtual void Test() NumericDocValues fooNorms = MultiDocValues.GetNormValues(reader, "foo"); for (int i = 0; i < reader.MaxDoc; i++) { - Assert.AreEqual((int)expected[i], fooNorms.Get(i) & 0xff); + Assert.AreEqual(expected[i], fooNorms.Get(i) & 0xff); } } diff --git a/src/Lucene.Net.Tests/Index/TestMixedCodecs.cs b/src/Lucene.Net.Tests/Index/TestMixedCodecs.cs index 48ccd44fd7..7a65c34296 100644 --- a/src/Lucene.Net.Tests/Index/TestMixedCodecs.cs +++ b/src/Lucene.Net.Tests/Index/TestMixedCodecs.cs @@ -86,10 +86,10 @@ public virtual void Test() } // Random delete half the docs: - ISet deleted = new JCG.HashSet(); + ISet deleted = new JCG.HashSet(); while (deleted.Count < NUM_DOCS / 2) { - int? toDelete = Random.Next(NUM_DOCS); + int toDelete = Random.Next(NUM_DOCS); if (!deleted.Contains(toDelete)) { deleted.Add(toDelete); diff --git a/src/Lucene.Net.Tests/Index/TestMultiDocValues.cs b/src/Lucene.Net.Tests/Index/TestMultiDocValues.cs index f4e639f682..bcf3d10bfa 100644 --- a/src/Lucene.Net.Tests/Index/TestMultiDocValues.cs +++ b/src/Lucene.Net.Tests/Index/TestMultiDocValues.cs @@ -357,7 +357,7 @@ public virtual void TestSortedSetWithDups() for (int i = 0; i < numDocs; i++) { single.SetDocument(i); - IList expectedList = new JCG.List(); + IList expectedList = new JCG.List(); long ord; while ((ord = single.NextOrd()) != SortedSetDocValues.NO_MORE_ORDS) { @@ -368,7 +368,7 @@ public virtual void TestSortedSetWithDups() int upto = 0; while ((ord = multi.NextOrd()) != SortedSetDocValues.NO_MORE_ORDS) { - Assert.AreEqual((long)expectedList[upto], ord); + Assert.AreEqual(expectedList[upto], ord); upto++; } Assert.AreEqual(expectedList.Count, upto); diff --git a/src/Lucene.Net.Tests/Index/TestMultiFields.cs b/src/Lucene.Net.Tests/Index/TestMultiFields.cs index 01ea3e091d..be65897675 100644 --- a/src/Lucene.Net.Tests/Index/TestMultiFields.cs +++ b/src/Lucene.Net.Tests/Index/TestMultiFields.cs @@ -52,7 +52,7 @@ public virtual void TestRandom() // we can do this because we use NoMergePolicy (and dont merge to "nothing") w.KeepFullyDeletedSegments = true; - IDictionary> docs = new Dictionary>(); + IDictionary> docs = new Dictionary>(); ISet deleted = new JCG.HashSet(); IList terms = new JCG.List(); @@ -82,9 +82,9 @@ public virtual void TestRandom() { string s = TestUtil.RandomUnicodeString(Random, 10); BytesRef term = new BytesRef(s); - if (!docs.TryGetValue(term, out IList docsTerm)) + if (!docs.TryGetValue(term, out IList docsTerm)) { - docs[term] = docsTerm = new JCG.List(); + docs[term] = docsTerm = new JCG.List(); } docsTerm.Add(i); terms.Add(term); diff --git a/src/Lucene.Net.Tests/Index/TestPostingsOffsets.cs b/src/Lucene.Net.Tests/Index/TestPostingsOffsets.cs index d56832ffc0..6a36639c16 100644 --- a/src/Lucene.Net.Tests/Index/TestPostingsOffsets.cs +++ b/src/Lucene.Net.Tests/Index/TestPostingsOffsets.cs @@ -242,7 +242,7 @@ public virtual void DoTestNumbers(bool withPayloads) public virtual void TestRandom() { // token -> docID -> tokens - IDictionary>> actualTokens = new Dictionary>>(); + IDictionary>> actualTokens = new Dictionary>>(); Directory dir = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter(Random, dir, iwc); @@ -301,9 +301,9 @@ public virtual void TestRandom() int tokenOffset = Random.Next(5); Token token = MakeToken(text, posIncr, offset + offIncr, offset + offIncr + tokenOffset); - if (!actualTokens.TryGetValue(text, out IDictionary> postingsByDoc)) + if (!actualTokens.TryGetValue(text, out IDictionary> postingsByDoc)) { - actualTokens[text] = postingsByDoc = new Dictionary>(); + actualTokens[text] = postingsByDoc = new Dictionary>(); } if (!postingsByDoc.TryGetValue(docCount, out IList postings)) { diff --git a/src/Lucene.Net.Tests/Index/TestTermsEnum.cs b/src/Lucene.Net.Tests/Index/TestTermsEnum.cs index 7f2712c44e..31a9d057d2 100644 --- a/src/Lucene.Net.Tests/Index/TestTermsEnum.cs +++ b/src/Lucene.Net.Tests/Index/TestTermsEnum.cs @@ -204,7 +204,7 @@ public virtual void Test() docs.Dispose(); } - private void AddDoc(RandomIndexWriter w, ICollection terms, IDictionary termToID, int id) + private void AddDoc(RandomIndexWriter w, ICollection terms, IDictionary termToID, int id) { Document doc = new Document(); doc.Add(new Int32Field("id", id, Field.Store.NO)); @@ -248,7 +248,7 @@ public virtual void TestIntersectRandom() ISet terms = new JCG.HashSet(); ICollection pendingTerms = new JCG.List(); - IDictionary termToID = new Dictionary(); + IDictionary termToID = new Dictionary(); int id = 0; while (terms.Count != numTerms) { diff --git a/src/Lucene.Net.Tests/Search/TestCustomSearcherSort.cs b/src/Lucene.Net.Tests/Search/TestCustomSearcherSort.cs index 24094cd2ab..2661b916fc 100644 --- a/src/Lucene.Net.Tests/Search/TestCustomSearcherSort.cs +++ b/src/Lucene.Net.Tests/Search/TestCustomSearcherSort.cs @@ -126,7 +126,7 @@ private void MatchHits(IndexSearcher searcher, Sort sort) // make a query without sorting first ScoreDoc[] hitsByRank = searcher.Search(query, null, int.MaxValue).ScoreDocs; CheckHits(hitsByRank, "Sort by rank: "); // check for duplicates - IDictionary resultMap = new JCG.SortedDictionary(); + IDictionary resultMap = new JCG.SortedDictionary(); // store hits in TreeMap - TreeMap does not allow duplicates; existing // entries are silently overwritten for (int hitid = 0; hitid < hitsByRank.Length; ++hitid) @@ -142,7 +142,7 @@ private void MatchHits(IndexSearcher searcher, Sort sort) // besides the sorting both sets of hits must be identical for (int hitid = 0; hitid < resultSort.Length; ++hitid) { - int? idHitDate = Convert.ToInt32(resultSort[hitid].Doc); // document ID + int idHitDate = Convert.ToInt32(resultSort[hitid].Doc); // document ID // from sorted // search if (!resultMap.ContainsKey(idHitDate)) @@ -175,13 +175,11 @@ private void CheckHits(ScoreDoc[] hits, string prefix) { if (hits != null) { - IDictionary idMap = new JCG.SortedDictionary(); + IDictionary idMap = new JCG.SortedDictionary(); for (int docnum = 0; docnum < hits.Length; ++docnum) { - int? luceneId = null; - - luceneId = Convert.ToInt32(hits[docnum].Doc); - if (idMap.TryGetValue(luceneId, out int? value)) + int luceneId = Convert.ToInt32(hits[docnum].Doc); + if (idMap.TryGetValue(luceneId, out int value)) { StringBuilder message = new StringBuilder(prefix); message.Append("Duplicate key for hit index = "); diff --git a/src/Lucene.Net.Tests/Search/TestDocIdSet.cs b/src/Lucene.Net.Tests/Search/TestDocIdSet.cs index db57a7ab9a..6b66ebb57b 100644 --- a/src/Lucene.Net.Tests/Search/TestDocIdSet.cs +++ b/src/Lucene.Net.Tests/Search/TestDocIdSet.cs @@ -47,7 +47,7 @@ public virtual void TestFilteredDocIdSet() DocIdSet filteredSet = new FilteredDocIdSetAnonymousClass(this, innerSet); DocIdSetIterator iter = filteredSet.GetIterator(); - IList list = new JCG.List(); + IList list = new JCG.List(); int doc = iter.Advance(3); if (doc != DocIdSetIterator.NO_MORE_DOCS) { @@ -60,10 +60,10 @@ public virtual void TestFilteredDocIdSet() int[] docs = new int[list.Count]; int c = 0; - IEnumerator intIter = list.GetEnumerator(); + using IEnumerator intIter = list.GetEnumerator(); while (intIter.MoveNext()) { - docs[c++] = (int)intIter.Current; + docs[c++] = intIter.Current; } int[] answer = new int[] { 4, 6, 8 }; bool same = Arrays.Equals(answer, docs); diff --git a/src/Lucene.Net.Tests/Search/TestFieldCacheRangeFilter.cs b/src/Lucene.Net.Tests/Search/TestFieldCacheRangeFilter.cs index c4ad8463c1..b79bb05548 100644 --- a/src/Lucene.Net.Tests/Search/TestFieldCacheRangeFilter.cs +++ b/src/Lucene.Net.Tests/Search/TestFieldCacheRangeFilter.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Documents; +using Lucene.Net.Documents; using NUnit.Framework; using System; using System.Globalization; @@ -225,9 +225,9 @@ public virtual void TestFieldCacheRangeFilterShorts() int numDocs = reader.NumDocs; int medId = ((maxId - minId) / 2); - short? minIdO = Convert.ToInt16((short)minId); - short? maxIdO = Convert.ToInt16((short)maxId); - short? medIdO = Convert.ToInt16((short)medId); + short minIdO = Convert.ToInt16((short)minId); + short maxIdO = Convert.ToInt16((short)maxId); + short medIdO = Convert.ToInt16((short)medId); Assert.AreEqual(numDocs, 1 + maxId - minId, "num of docs"); @@ -317,9 +317,9 @@ public virtual void TestFieldCacheRangeFilterInts() int numDocs = reader.NumDocs; int medId = ((maxId - minId) / 2); - int? minIdO = Convert.ToInt32(minId); - int? maxIdO = Convert.ToInt32(maxId); - int? medIdO = Convert.ToInt32(medId); + int minIdO = Convert.ToInt32(minId); + int maxIdO = Convert.ToInt32(maxId); + int medIdO = Convert.ToInt32(medId); Assert.AreEqual(numDocs, 1 + maxId - minId, "num of docs"); @@ -408,9 +408,9 @@ public virtual void TestFieldCacheRangeFilterLongs() int numDocs = reader.NumDocs; int medId = ((maxId - minId) / 2); - long? minIdO = Convert.ToInt64(minId); - long? maxIdO = Convert.ToInt64(maxId); - long? medIdO = Convert.ToInt64(medId); + long minIdO = Convert.ToInt64(minId); + long maxIdO = Convert.ToInt64(maxId); + long medIdO = Convert.ToInt64(medId); Assert.AreEqual(numDocs, 1 + maxId - minId, "num of docs"); @@ -500,8 +500,8 @@ public virtual void TestFieldCacheRangeFilterFloats() IndexSearcher search = NewSearcher(reader); int numDocs = reader.NumDocs; - float? minIdO = Convert.ToSingle(minId + .5f); - float? medIdO = Convert.ToSingle((float)minIdO + ((maxId - minId)) / 2.0f); + float minIdO = Convert.ToSingle(minId + .5f); + float medIdO = Convert.ToSingle((float)minIdO + ((maxId - minId)) / 2.0f); ScoreDoc[] result; Query q = new TermQuery(new Term("body", "body")); @@ -529,8 +529,8 @@ public virtual void TestFieldCacheRangeFilterDoubles() IndexSearcher search = NewSearcher(reader); int numDocs = reader.NumDocs; - double? minIdO = Convert.ToDouble(minId + .5); - double? medIdO = Convert.ToDouble((float)minIdO + ((maxId - minId)) / 2.0); + double minIdO = Convert.ToDouble(minId + .5); + double medIdO = Convert.ToDouble((float)minIdO + ((maxId - minId)) / 2.0); ScoreDoc[] result; Query q = new TermQuery(new Term("body", "body")); diff --git a/src/Lucene.Net.Tests/Search/TestMinShouldMatch2.cs b/src/Lucene.Net.Tests/Search/TestMinShouldMatch2.cs index f621a36060..adc8147dfd 100644 --- a/src/Lucene.Net.Tests/Search/TestMinShouldMatch2.cs +++ b/src/Lucene.Net.Tests/Search/TestMinShouldMatch2.cs @@ -349,7 +349,7 @@ internal class SlowMinShouldMatchScorer : Scorer internal readonly SortedSetDocValues dv; internal readonly int maxDoc; - internal readonly ISet ords = new JCG.HashSet(); + internal readonly ISet ords = new JCG.HashSet(); internal readonly SimScorer[] sims; internal readonly int minNrShouldMatch; diff --git a/src/Lucene.Net.Tests/Search/TestSubScorerFreqs.cs b/src/Lucene.Net.Tests/Search/TestSubScorerFreqs.cs index 8766f0ba6e..dfc981d373 100644 --- a/src/Lucene.Net.Tests/Search/TestSubScorerFreqs.cs +++ b/src/Lucene.Net.Tests/Search/TestSubScorerFreqs.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Documents; +using Lucene.Net.Documents; using Lucene.Net.Index; using Lucene.Net.Index.Extensions; using Lucene.Net.Store; @@ -76,7 +76,7 @@ private class CountingCollector : ICollector private readonly ICollector other; private int docBase; - public IDictionary> DocCounts { get; } = new Dictionary>(); + public IDictionary> DocCounts { get; } = new Dictionary>(); private readonly IDictionary subScorers = new Dictionary(); private readonly ISet relationships; @@ -113,7 +113,7 @@ public virtual void SetSubScorers(Scorer scorer, string relationship) public virtual void Collect(int doc) { - IDictionary freqs = new Dictionary(); + IDictionary freqs = new Dictionary(); foreach (KeyValuePair ent in subScorers) { Scorer value = ent.Value; @@ -145,13 +145,13 @@ public virtual void TestTermQuery() Assert.AreEqual(maxDocs, c.DocCounts.Count); for (int i = 0; i < maxDocs; i++) { - IDictionary doc0 = c.DocCounts[i]; + IDictionary doc0 = c.DocCounts[i]; Assert.AreEqual(1, doc0.Count); - Assert.AreEqual(4.0F, doc0[q].GetValueOrDefault(), FLOAT_TOLERANCE); + Assert.AreEqual(4.0F, doc0[q], FLOAT_TOLERANCE); - IDictionary doc1 = c.DocCounts[++i]; + IDictionary doc1 = c.DocCounts[++i]; Assert.AreEqual(1, doc1.Count); - Assert.AreEqual(1.0F, doc1[q].GetValueOrDefault(), FLOAT_TOLERANCE); + Assert.AreEqual(1.0F, doc1[q], FLOAT_TOLERANCE); } } @@ -185,22 +185,22 @@ public virtual void TestBooleanQuery() bool includeOptional = occur.Contains("SHOULD"); for (int i = 0; i < maxDocs; i++) { - IDictionary doc0 = c.DocCounts[i]; + IDictionary doc0 = c.DocCounts[i]; Assert.AreEqual(includeOptional ? 5 : 4, doc0.Count); - Assert.AreEqual(1.0F, doc0[aQuery].GetValueOrDefault(), FLOAT_TOLERANCE); - Assert.AreEqual(4.0F, doc0[dQuery].GetValueOrDefault(), FLOAT_TOLERANCE); + Assert.AreEqual(1.0F, doc0[aQuery], FLOAT_TOLERANCE); + Assert.AreEqual(4.0F, doc0[dQuery], FLOAT_TOLERANCE); if (includeOptional) { - Assert.AreEqual(3.0F, doc0[cQuery].GetValueOrDefault(), FLOAT_TOLERANCE); + Assert.AreEqual(3.0F, doc0[cQuery], FLOAT_TOLERANCE); } - IDictionary doc1 = c.DocCounts[++i]; + IDictionary doc1 = c.DocCounts[++i]; Assert.AreEqual(includeOptional ? 5 : 4, doc1.Count); - Assert.AreEqual(1.0F, doc1[aQuery].GetValueOrDefault(), FLOAT_TOLERANCE); - Assert.AreEqual(1.0F, doc1[dQuery].GetValueOrDefault(), FLOAT_TOLERANCE); + Assert.AreEqual(1.0F, doc1[aQuery], FLOAT_TOLERANCE); + Assert.AreEqual(1.0F, doc1[dQuery], FLOAT_TOLERANCE); if (includeOptional) { - Assert.AreEqual(1.0F, doc1[cQuery].GetValueOrDefault(), FLOAT_TOLERANCE); + Assert.AreEqual(1.0F, doc1[cQuery], FLOAT_TOLERANCE); } } } @@ -218,13 +218,13 @@ public virtual void TestPhraseQuery() Assert.AreEqual(maxDocs, c.DocCounts.Count); for (int i = 0; i < maxDocs; i++) { - IDictionary doc0 = c.DocCounts[i]; + IDictionary doc0 = c.DocCounts[i]; Assert.AreEqual(1, doc0.Count); - Assert.AreEqual(2.0F, doc0[q].GetValueOrDefault(), FLOAT_TOLERANCE); + Assert.AreEqual(2.0F, doc0[q], FLOAT_TOLERANCE); - IDictionary doc1 = c.DocCounts[++i]; + IDictionary doc1 = c.DocCounts[++i]; Assert.AreEqual(1, doc1.Count); - Assert.AreEqual(1.0F, doc1[q].GetValueOrDefault(), FLOAT_TOLERANCE); + Assert.AreEqual(1.0F, doc1[q], FLOAT_TOLERANCE); } } } diff --git a/src/Lucene.Net.Tests/Util/TestBytesRefHash.cs b/src/Lucene.Net.Tests/Util/TestBytesRefHash.cs index 53cae515e3..8233b52364 100644 --- a/src/Lucene.Net.Tests/Util/TestBytesRefHash.cs +++ b/src/Lucene.Net.Tests/Util/TestBytesRefHash.cs @@ -104,7 +104,7 @@ public virtual void TestGet() int num = AtLeast(2); for (int j = 0; j < num; j++) { - IDictionary strings = new Dictionary(); + IDictionary strings = new Dictionary(); int uniqueCount = 0; for (int i = 0; i < 797; i++) { @@ -130,7 +130,7 @@ public virtual void TestGet() Assert.AreEqual(hash.Count, count); } } - foreach (KeyValuePair entry in strings) + foreach (KeyValuePair entry in strings) { @ref.CopyChars(entry.Key); Assert.AreEqual(@ref, hash.Get((int)entry.Value, scratch)); diff --git a/src/Lucene.Net.Tests/Util/TestDoubleBarrelLRUCache.cs b/src/Lucene.Net.Tests/Util/TestDoubleBarrelLRUCache.cs index a819d4f8f3..52fb43205c 100644 --- a/src/Lucene.Net.Tests/Util/TestDoubleBarrelLRUCache.cs +++ b/src/Lucene.Net.Tests/Util/TestDoubleBarrelLRUCache.cs @@ -201,9 +201,9 @@ public override object Clone() protected internal class CloneableInteger : DoubleBarrelLRUCache.CloneableKey { - internal int? value; + internal int value; - public CloneableInteger(int? value) + public CloneableInteger(int value) { this.value = value; } diff --git a/src/Lucene.Net.Tests/Util/TestMergedIterator.cs b/src/Lucene.Net.Tests/Util/TestMergedIterator.cs index 55e9c06907..3242f3944e 100644 --- a/src/Lucene.Net.Tests/Util/TestMergedIterator.cs +++ b/src/Lucene.Net.Tests/Util/TestMergedIterator.cs @@ -123,7 +123,7 @@ public virtual void TestBothDupsWithRandomDupsKeepDups() private void TestCase(int itrsWithVal, int specifiedValsOnItr, bool removeDups) { // Build a random number of lists - IList expected = new JCG.List(); + IList expected = new JCG.List(); Random random = new J2N.Randomizer(Random.NextInt64()); int numLists = itrsWithVal + random.Next(1000 - itrsWithVal); IList[] lists = new IList[numLists]; @@ -166,7 +166,7 @@ private void TestCase(int itrsWithVal, int specifiedValsOnItr, bool removeDups) try { MergedEnumerator mergedItr = new MergedEnumerator(removeDups, itrs); - IEnumerator expectedItr = expected.GetEnumerator(); + using IEnumerator expectedItr = expected.GetEnumerator(); while (expectedItr.MoveNext()) { Assert.IsTrue(mergedItr.MoveNext()); @@ -292,7 +292,7 @@ public virtual void TestBothDupsWithRandomDupsKeepDupsIterator() private void TestCaseIterator(int itrsWithVal, int specifiedValsOnItr, bool removeDups) { // Build a random number of lists - IList expected = new JCG.List(); + IList expected = new JCG.List(); Random random = new J2N.Randomizer(Random.NextInt64()); int numLists = itrsWithVal + random.Next(1000 - itrsWithVal); IList[] lists = new IList[numLists]; @@ -334,7 +334,7 @@ private void TestCaseIterator(int itrsWithVal, int specifiedValsOnItr, bool remo } MergedIterator mergedItr = new MergedIterator(removeDups, itrs); - IEnumerator expectedItr = expected.GetEnumerator(); + using IEnumerator expectedItr = expected.GetEnumerator(); while (expectedItr.MoveNext()) { Assert.IsTrue(mergedItr.MoveNext());