repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
palerdot/BlingFire
blingfireclient.library/inc/FATaggedTextCA.h
<reponame>palerdot/BlingFire /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_TAGGEDTEXTCA_H_ #define _FA_TAGGEDTEXTCA_H_ #include "FAConfig.h" namespace BlingFire { class FATaggedTextCA { public: // returns number of words virtual const int GetWordCount () const = 0; // returns word text virtual const int GetWord (const int Num, const int ** pWord) const = 0; // returns POS tag virtual const int GetTag (const int Num) const = 0; // returns offset in the original text, -1 if not specified virtual const int GetOffset (const int Num) const = 0; }; } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FARegexpLexer_char.h
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_REGEXPLEXER_CHAR_H_ #define _FA_REGEXPLEXER_CHAR_H_ #include "FAConfig.h" #include "FARegexpLexer_triv.h" namespace BlingFire { /// /// Understands UTF-8 and any 8-bit encoded character regular expressions. /// Uses 1-byte encoding by default. /// class FARegexpLexer_char : public FARegexpLexer_triv { public: FARegexpLexer_char (); public: void SetUseUtf8 (const bool UseUtf8); private: const int FindToken (const int Pos, int * pLength) const; /// returns true if any of '\\', '\t', '\n', '\r' is encountered inline const bool IsSpace (const char C) const; private: bool m_is_space [AsciiSize]; bool m_UseUtf8; }; } #endif
palerdot/BlingFire
blingfireclient.library/inc/FATrsConfKeeper_t.h
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_TRSCONFKEEPER_T_H_ #define _FA_TRSCONFKEEPER_T_H_ #include "FAConfig.h" #include "FATransform_hyph_redup_t.h" #include "FATransform_hyph_redup_rev_t.h" #include "FATransform_prefix_t.h" #include "FATransform_prefix_rev_t.h" #include "FATransform_capital_t.h" #include "FATransform_capital_rev_t.h" #include "FATransform_cascade_t.h" #include "FARSDfa_pack_triv.h" #include "FASecurity.h" namespace BlingFire { template < class Ty > class FATrsConfKeeper_t { public: FATrsConfKeeper_t (); virtual ~FATrsConfKeeper_t (); public: /// this LDB will be used to get the data from void SetLDB (const FALDB * pLDB); /// initialization vector void Init (const int * pValues, const int Size); /// returns object into the initial state void Clear (); public: const FATransformCA_t < Ty > * GetInTr () const; const FATransformCA_t < Ty > * GetOutTr () const; const bool GetIgnoreCase () const; private: const FATransformCA_t < Ty > * SelectTr (const int TrType); private: /// input LDB const FALDB * m_pLDB; /// transformations objects, if any FATransform_hyph_redup_t < Ty > * m_pTr_hyph_redup; FATransform_hyph_redup_rev_t < Ty > * m_pTr_hyph_redup_rev; FATransform_prefix_t < Ty > * m_pTr_prefix; FATransform_prefix_rev_t < Ty > * m_pTr_prefix_rev; FATransform_capital_t < Ty > * m_pTr_capital; FATransform_capital_rev_t < Ty > * m_pTr_capital_rev; FATransform_cascade_t < Ty > * m_pInTrCascade; FATransform_cascade_t < Ty > * m_pOutTrCascade; /// const interface pointer to input and output transformations const FATransformCA_t < Ty > * m_pInTrA; const FATransformCA_t < Ty > * m_pOutTrA; /// automaton of prefixes for prefix transformation, if any FARSDfa_pack_triv * m_pPrefDfa; /// a global ignore case flag bool m_ignore_case; }; template < class Ty > FATrsConfKeeper_t< Ty >::FATrsConfKeeper_t () : m_pLDB (NULL), m_pTr_hyph_redup (NULL), m_pTr_hyph_redup_rev (NULL), m_pTr_prefix (NULL), m_pTr_prefix_rev (NULL), m_pTr_capital (NULL), m_pTr_capital_rev (NULL), m_pInTrCascade (NULL), m_pOutTrCascade (NULL), m_pInTrA (NULL), m_pOutTrA (NULL), m_pPrefDfa (NULL), m_ignore_case (false) {} template < class Ty > FATrsConfKeeper_t< Ty >::~FATrsConfKeeper_t () { FATrsConfKeeper_t< Ty >::Clear (); } template < class Ty > void FATrsConfKeeper_t< Ty >::Clear () { m_ignore_case = false; m_pInTrA = NULL; m_pOutTrA = NULL; if (m_pPrefDfa) { delete m_pPrefDfa; m_pPrefDfa = NULL; } if (m_pTr_hyph_redup) { delete m_pTr_hyph_redup; m_pTr_hyph_redup = NULL; } if (m_pTr_hyph_redup_rev) { delete m_pTr_hyph_redup_rev; m_pTr_hyph_redup_rev = NULL; } if (m_pTr_prefix) { delete m_pTr_prefix; m_pTr_prefix = NULL; } if (m_pTr_prefix_rev) { delete m_pTr_prefix_rev; m_pTr_prefix_rev = NULL; } if (m_pTr_capital) { delete m_pTr_capital; m_pTr_capital = NULL; } if (m_pTr_capital_rev) { delete m_pTr_capital_rev; m_pTr_capital_rev = NULL; } if (m_pInTrCascade) { delete m_pInTrCascade; m_pInTrCascade = NULL; } if (m_pOutTrCascade) { delete m_pOutTrCascade; m_pOutTrCascade = NULL; } } template < class Ty > void FATrsConfKeeper_t< Ty >::SetLDB (const FALDB * pLDB) { m_pLDB = pLDB; } template < class Ty > const FATransformCA_t < Ty > * FATrsConfKeeper_t< Ty >:: SelectTr (const int TrType) { const FATransformCA_t < Ty > * pSelectedTr = NULL; switch (TrType) { case FAFsmConst::TR_HYPH_REDUP: { if (!m_pTr_hyph_redup) { m_pTr_hyph_redup = new FATransform_hyph_redup_t < Ty >; LogAssert (m_pTr_hyph_redup); } pSelectedTr = m_pTr_hyph_redup; break; } case FAFsmConst::TR_HYPH_REDUP_REV: { if (!m_pTr_hyph_redup_rev) { m_pTr_hyph_redup_rev = new FATransform_hyph_redup_rev_t < Ty >; LogAssert (m_pTr_hyph_redup_rev); } pSelectedTr = m_pTr_hyph_redup_rev; break; } case FAFsmConst::TR_PREFIX: { if (!m_pTr_prefix) { m_pTr_prefix = new FATransform_prefix_t < Ty >; LogAssert (m_pTr_prefix); } pSelectedTr = m_pTr_prefix; break; } case FAFsmConst::TR_PREFIX_REV: { if (!m_pTr_prefix_rev) { m_pTr_prefix_rev = new FATransform_prefix_rev_t < Ty >; LogAssert (m_pTr_prefix_rev); } pSelectedTr = m_pTr_prefix_rev; break; } case FAFsmConst::TR_UCF: { if (!m_pTr_capital) { m_pTr_capital = new FATransform_capital_t < Ty >; LogAssert (m_pTr_capital); } pSelectedTr = m_pTr_capital; break; } case FAFsmConst::TR_UCF_REV: { if (!m_pTr_capital_rev) { m_pTr_capital_rev = new FATransform_capital_rev_t < Ty >; LogAssert (m_pTr_capital_rev); } pSelectedTr = m_pTr_capital_rev; break; } default: // unknown transformaion type LogAssert (false); } // of switch (TrType) ... return pSelectedTr; } template < class Ty > void FATrsConfKeeper_t< Ty >::Init (const int * pValues, const int Size) { LogAssert (m_pLDB && (pValues || 0 >= Size)); int RedupDelim = -1; int PrefDelim = -1; int UcfDelim = -1; m_pInTrA = NULL; m_pOutTrA = NULL; m_ignore_case = false; for (int i = 0; i < Size; ++i) { const int Param = pValues [i]; switch (Param) { case FAFsmConst::PARAM_IGNORE_CASE: { m_ignore_case = true; break; } case FAFsmConst::PARAM_REDUP_DELIM: { RedupDelim = pValues [++i]; break; } case FAFsmConst::PARAM_PREF_DELIM: { PrefDelim = pValues [++i]; break; } case FAFsmConst::PARAM_UCF_DELIM: { UcfDelim = pValues [++i]; break; } case FAFsmConst::PARAM_PREF_FSM: { const int DumpNum = pValues [++i]; const unsigned char * pDump = m_pLDB->GetDump (DumpNum); LogAssert (pDump); if (!m_pPrefDfa) { m_pPrefDfa = new FARSDfa_pack_triv; LogAssert (m_pPrefDfa); } m_pPrefDfa->SetImage (pDump); break; } case FAFsmConst::PARAM_IN_TR: { const int TrType = pValues [++i]; if (!m_pInTrA) { m_pInTrA = SelectTr (TrType); DebugLogAssert (m_pInTrA); } else { // see whether super-position has not been created yet if (!m_pInTrCascade) { m_pInTrCascade = new FATransform_cascade_t < Ty > (); LogAssert (m_pInTrCascade); m_pInTrCascade->AddTransformation (m_pInTrA); m_pInTrA = m_pInTrCascade; } const FATransformCA_t < Ty > * pTr = SelectTr (TrType); DebugLogAssert (pTr); m_pInTrCascade->AddTransformation (pTr); } // of if (!m_pInTrA) break; } case FAFsmConst::PARAM_OUT_TR: { const int TrType = pValues [++i]; if (!m_pOutTrA) { m_pOutTrA = SelectTr (TrType); DebugLogAssert (m_pOutTrA); } else { // see whether super-position has not been created yet if (!m_pOutTrCascade) { m_pOutTrCascade = new FATransform_cascade_t < Ty > (); LogAssert (m_pOutTrCascade); m_pOutTrCascade->AddTransformation (m_pOutTrA); m_pOutTrA = m_pOutTrCascade; } const FATransformCA_t < Ty > * pTr = SelectTr (TrType); DebugLogAssert (pTr); m_pOutTrCascade->AddTransformation (pTr); } // of if (!m_pOutTrA) ... break; } default: // unknown parameter LogAssert (false); } // of switch ... } // of for (int i = 0; ... if (-1 != RedupDelim) { if (m_pTr_hyph_redup) { m_pTr_hyph_redup->SetDelim (Ty (RedupDelim)); } if (m_pTr_hyph_redup_rev) { m_pTr_hyph_redup_rev->SetDelim (Ty (RedupDelim)); } } if (-1 != PrefDelim) { if (m_pTr_prefix) { m_pTr_prefix->SetDelim (Ty (PrefDelim)); } if (m_pTr_prefix_rev) { m_pTr_prefix_rev->SetDelim (Ty (PrefDelim)); } } if (-1 != UcfDelim) { if (m_pTr_capital) { m_pTr_capital->SetDelim (Ty (UcfDelim)); } if (m_pTr_capital_rev) { m_pTr_capital_rev->SetDelim (Ty (UcfDelim)); } } if (m_pPrefDfa){ if (m_pTr_prefix) { m_pTr_prefix->SetRsDfa (m_pPrefDfa); } } } template < class Ty > const FATransformCA_t < Ty > * FATrsConfKeeper_t< Ty >::GetInTr () const { return m_pInTrA; } template < class Ty > const FATransformCA_t < Ty > * FATrsConfKeeper_t< Ty >::GetOutTr () const { return m_pOutTrA; } template < class Ty > const bool FATrsConfKeeper_t< Ty >::GetIgnoreCase () const { return m_ignore_case; } } #endif
palerdot/BlingFire
blingfireclient.library/inc/FARegexpTags_t.h
<filename>blingfireclient.library/inc/FARegexpTags_t.h /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_REGEXPTAGS_T_H_ #define _FA_REGEXPTAGS_T_H_ #include "FAConfig.h" #include "FAFsmConst.h" #include "FAUtf32Utils.h" #include "FARSDfaCA.h" #include "FAState2OwsCA.h" #include "FAMultiMapCA.h" #include "FAWbdConfKeeper.h" #include "FALimits.h" namespace BlingFire { /// /// For the given input string, this processor returns a set of tags with /// scores. The tags and scores are calculated by matching fa_lex-style regular /// expressions, unlike fa_lex interpreter this processor uses *all* matches. /// /// Notes: /// 1. see doc/design.txt for typical abbreviations /// 2. The typical class usage is as follows: /// 1. one time SetConf /// 2. many times Process /// 3. SetConf, if needed /// 4. many times Process, again /// ... /// template < class Ty > class FARegexpTags_t { public: FARegexpTags_t (); ~FARegexpTags_t (); public: /// sets up the data containers, NULL will just clear this object void Initialize (const FAWbdConfKeeper * pWbdConf); /// The input is a string, e.g. word, sentence, url, etc. /// The function returns size and two arrays the first keeps a set of tags /// the second keeps corresponding scores for each tag. /// The results are valid only between Process calls. const int Process ( const Ty * pIn, const int InSize, const int ** ppTags, const int ** ppScores ); private: inline void AddTags (const int FinalState); void Clear (); private: /// input objects const FARSDfaCA * m_pDfa; const FAState2OwsCA * m_pState2Ows; const FAMultiMapCA * m_pActs; bool m_fIgnoreCase; /// temporary Ows buffer int * m_pOws; int m_MaxOwsCount; /// constants enum { MaxTokenLength = FALimits::MaxWordLen, MinActSize = 4, MaxActSize = 4, DefSubIw = FAFsmConst::IW_EPSILON, }; /// runtime buffers, of a 0..MaxTag size /// Note: the memory is allocated ones at Initialize method int * m_pTag2Score; int * m_pTags; int * m_pScores; int m_MaxTagCount; int m_TagCount; }; template < class Ty > FARegexpTags_t< Ty >::FARegexpTags_t () : m_pDfa (NULL), m_pState2Ows (NULL), m_pActs (NULL), m_fIgnoreCase (false), m_pOws (NULL), m_MaxOwsCount (0), m_pTag2Score (NULL), m_pTags (NULL), m_pScores (NULL), m_MaxTagCount (0), m_TagCount (0) {} template < class Ty > FARegexpTags_t< Ty >::~FARegexpTags_t () { FARegexpTags_t< Ty >::Clear (); } template < class Ty > void FARegexpTags_t< Ty >::Clear () { if (m_pOws) { delete m_pOws; m_pOws = NULL; } if (m_pTag2Score) { delete m_pTag2Score; m_pTag2Score = NULL; } if (m_pTags) { delete m_pTags; m_pTags = NULL; } if (m_pScores) { delete m_pScores; m_pScores = NULL; } m_pDfa = NULL; m_pState2Ows = NULL; m_pActs = NULL; m_fIgnoreCase = false; m_MaxOwsCount = 0; m_MaxTagCount = 0; m_TagCount = 0; } template < class Ty > void FARegexpTags_t< Ty >::Initialize (const FAWbdConfKeeper * pWbdConf) { FARegexpTags_t< Ty >::Clear (); if (!pWbdConf) { return; } m_pDfa = pWbdConf->GetRsDfa (); m_pState2Ows = pWbdConf->GetState2Ows (); m_pActs = pWbdConf->GetMMap (); LogAssert (m_pDfa && m_pState2Ows && m_pActs); m_fIgnoreCase = pWbdConf->GetIgnoreCase (); m_MaxOwsCount = m_pState2Ows->GetMaxOwsCount (); LogAssert (0 < m_MaxOwsCount); LogAssert (!m_pOws); m_pOws = new int [m_MaxOwsCount]; LogAssert (m_pOws); m_MaxTagCount = 1 + pWbdConf->GetMaxTag (); LogAssert (0 < m_MaxTagCount); LogAssert (!m_pTag2Score); m_pTag2Score = new int [m_MaxTagCount]; LogAssert (m_pTag2Score); LogAssert (!m_pTags); m_pTags = new int [m_MaxTagCount]; LogAssert (m_pTags); LogAssert (!m_pScores); m_pScores = new int [m_MaxTagCount]; LogAssert (m_pScores); for (int i = 0; i < m_MaxTagCount; ++i) { m_pTag2Score [i] = -1; m_pScores [i] = 0; m_pTags [i] = 0; } /// we need to validate all the actions so we may ignore all checks later: /// actions size, tag values, scores should be correct const int * pAct; int ActSize; int ActId = 0; while (-1 != (ActSize = m_pActs->Get (ActId++, &pAct))) { // invalid action LogAssert (pAct && MaxActSize >= ActSize && MinActSize <= ActSize); const int Score = pAct [2]; const int Tag = pAct [3]; // invalid score or tag value LogAssert (0 <= Score && 0 <= Tag && m_MaxTagCount > Tag); } } template < class Ty > inline void FARegexpTags_t< Ty >::AddTags (const int FinalState) { DebugLogAssert (m_pActs && m_pState2Ows); const int OwCount = m_pState2Ows->GetOws (FinalState, m_pOws, m_MaxOwsCount); DebugLogAssert (OwCount <= m_MaxOwsCount); for (int i = 0; i < OwCount; ++i) { const int Ow = m_pOws [i]; const int * pAct; #ifndef NDEBUG const int ActSize = #endif m_pActs->Get (Ow, &pAct); DebugLogAssert (MinActSize <= ActSize && pAct); const int Score = pAct [2]; DebugLogAssert (0 <= Score); const int Tag = pAct [3]; DebugLogAssert (0 <= Tag && m_MaxTagCount > Tag); const int OldScore = m_pTag2Score [Tag]; // store the score if (OldScore < Score) { m_pTag2Score [Tag] = Score; } // add the tag if it was not there if (-1 == OldScore) { DebugLogAssert (m_TagCount < m_MaxTagCount); m_pTags [m_TagCount++] = Tag; } } } template < class Ty > const int FARegexpTags_t< Ty >:: Process ( const Ty * pIn, const int InSize, const int ** ppTags, const int ** ppScores ) { LogAssert (m_pActs && m_pDfa && m_pState2Ows); LogAssert (ppTags && ppScores); int i, Iw, Dst; /// return scores into the initial state for (i = 0; i < m_TagCount; ++i) { const int Tag = m_pTags [i]; DebugLogAssert (0 <= Tag && m_MaxTagCount > Tag); m_pTag2Score [Tag] = -1; } m_TagCount = 0; /// we keep track of the previous final state by optimization reasons int PrevFinal = -1; const int Initial = m_pDfa->GetInitial (); /// iterate thru all possible start positions for (int FromPos = -1; FromPos < InSize; ++FromPos) { int State = Initial; int j = FromPos; // maximum token length bounds j int LengthBound = FromPos + MaxTokenLength; if (InSize < LengthBound) { LengthBound = InSize; } /// feed the left anchor, if appropriate if (-1 == j) { State = m_pDfa->GetDest (Initial, FAFsmConst::IW_L_ANCHOR); if (-1 == State) { State = m_pDfa->GetDest (Initial, FAFsmConst::IW_ANY); if (-1 == State) { continue; } } j++; } /// feed the letters for (; j < LengthBound; ++j) { Iw = pIn [j]; // prevent regular input weights to match control input weights if (FAFsmConst::IW_EPSILON > Iw) { Iw = DefSubIw; } if (m_fIgnoreCase) { Iw = FAUtf32ToLower (Iw); } Dst = m_pDfa->GetDest (State, Iw); if (-1 == Dst) { Dst = m_pDfa->GetDest (State, FAFsmConst::IW_ANY); if (-1 == Dst) { break; } } if (m_pDfa->IsFinal (Dst) && PrevFinal != Dst) { PrevFinal = Dst; AddTags (Dst); } State = Dst; } // of for (; j < InSize; ... /// feed the right anchor, if appropriate if (InSize == j) { DebugLogAssert (-1 != State); Dst = m_pDfa->GetDest (State, FAFsmConst::IW_R_ANCHOR); if (-1 == Dst) { Dst = m_pDfa->GetDest (State, FAFsmConst::IW_ANY); } if (-1 != Dst && PrevFinal != Dst && m_pDfa->IsFinal (Dst)) { PrevFinal = Dst; AddTags (Dst); } } } // of for (FromPos = -1; ... /// update the scores' array for (i = 0; i < m_TagCount; ++i) { const int Tag = m_pTags [i]; DebugLogAssert (0 <= Tag && m_MaxTagCount > Tag); const int Score = m_pTag2Score [Tag]; DebugLogAssert (0 <= Score); m_pScores [i] = Score; } *ppTags = m_pTags; *ppScores = m_pScores; return m_TagCount; } } #endif
palerdot/BlingFire
blingfireclient.library/inc/FAW2PConfKeeper.h
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_W2PCONFKEEPER_H_ #define _FA_W2PCONFKEEPER_H_ #include "FAConfig.h" namespace BlingFire { class FALDB; class FARSDfa_pack_triv; class FAState2Ow_pack_triv; class FAMultiMap_pack_fixed; class FARSDfaCA; class FAState2OwCA; class FAMultiMapCA; /// /// Keeps configuration for word-guesser module. /// /// Note: Resource pointers may not be initialized and be NULL. /// class FAW2PConfKeeper { public: FAW2PConfKeeper (); ~FAW2PConfKeeper (); public: /// LDB is used to get the data, initialization vector indicates which /// W2P data to use void Initialize (const FALDB * pLDB, const int * pValues, const int Size); /// returns object into the initial state void Clear (); public: const FARSDfaCA * GetRsDfa () const; const FAState2OwCA * GetState2Ow () const; const bool GetIgnoreCase () const; // the numrical value corresponding to 1 of the prob, prob guesser only const int GetMaxProb () const; const FAMultiMapCA * GetCharMap () const; const float GetMinProbVal () const; const float GetMaxProbVal () const; private: const FALDB * m_pLDB; FARSDfa_pack_triv * m_pDfa; FAState2Ow_pack_triv * m_pState2Ow; bool m_IgnoreCase; int m_MaxProb; FAMultiMap_pack_fixed * m_pCharMap; float m_MinProbVal; float m_MaxProbVal; }; } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FAMealyNfa.h
<reponame>palerdot/BlingFire<filename>blingfirecompile.library/inc/FAMealyNfa.h<gh_stars>1000+ /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_MEALYNFA_H_ #define _FA_MEALYNFA_H_ #include "FAConfig.h" #include "FAMealyNfaA.h" #include "FAEncoder_pref.h" #include "FAChain2Num_hash.h" namespace BlingFire { /// /// FSM-compile-time interafece for Mealy NFA sigma function. /// class FAMealyNfa : public FAMealyNfaA { public: FAMealyNfa (FAAllocatorA * pAlloc); virtual ~FAMealyNfa (); public: const int GetOw (const int Src, const int Iw, const int Dst) const; void SetOw (const int Src, const int Iw, const int Dst, const int Ow); void Prepare (); void Clear (); private: FAEncoder_pref m_enc; FAChain2Num_hash m_arc2ow; }; } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FAAutInterpretTools_pos_t.h
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_INTERPRETTOOLS_POS_T_H_ #define _FA_INTERPRETTOOLS_POS_T_H_ #include "FAConfig.h" #include "FARSDfaCA.h" #include "FAState2OwsCA.h" #include "FARSNfaCA.h" #include "FABitArray.h" #include "FAUtils_cl.h" #include "FASecurity.h" namespace BlingFire { /// /// This class calculates the match between intput text positions and /// positions in regular expression. /// template < class Ty > class FAAutInterpretTools_pos_t { public: FAAutInterpretTools_pos_t (FAAllocatorA * pAlloc); public: /// sets up AnyIw, 0 by default void SetAnyIw (const int AnyIw); /// sets RS Dfa interface void SetRsDfa (const FARSDfaCA * pDfa); /// sets State -> Ows map void SetState2Ows (const FAState2OwsCA * pState2Ows); /// sets pos -> {pos} follow pos function void SetFollow (const FARSNfaCA * pFollow); public: /// converts a chain of input weights into a chain of /// regular expression positions /// returns false if not matched const bool Chain2PosChain ( const Ty * pInChain, __out_ecount(Size) int * pPosChain, const int Size ); /// the same as above but should be used for DFA with localy /// expanded Any symbol const bool Chain2PosChain_local ( const Ty * pInChain, __out_ecount(Size) int * pPosChain, const int Size ); private: /// returns m_AnyIw if symbol is not within the DFA's alphabet /// otherwise symbol itself inline const int Symbol2DfaIw (const int Symbol) const; /// returns next matched position inline const int GetNextPos ( const int * pStateSet, const int StateSetSize ) const; /// stores state sequence along the path, returns the last state /// returns false if breaks inline const bool Chain2States ( const Ty * pInChain, __out_ecount(Size) int * pStates, const int Size ) const; /// the same as above but for locally expanded DFAs inline const bool Chain2States_local ( const Ty * pInChain, __out_ecount(Size) int * pStates, const int Size ) const; /// having DFA's states and input reconstructs match positions inline void States2Pos ( const Ty * pInChain, const int * pStates, __out_ecount(Size) int * pPosChain, const int Size ); /// fills in m_follow array, updates m_pFollowSet and m_FollowSetMaxSize inline void BuildFollowSet (const int CurrPos, const int Symbol); protected: const FARSDfaCA * m_pDfa; const FAState2OwsCA * m_pState2Ows; const FARSNfaCA * m_pFollow; private: int m_AnyIw; int m_LastPos; FABitArray m_known_dfa_iw; FAArray_cont_t < int > m_ows; int * m_pOws; int m_MaxOwsSize; FAArray_cont_t < int > m_follow; int * m_pFollowSet; int m_FollowSetSize; int m_FollowSetMaxSize; FAArray_cont_t < int > m_Iws; }; template < class Ty > FAAutInterpretTools_pos_t< Ty >:: FAAutInterpretTools_pos_t (FAAllocatorA * pAlloc) : m_pDfa (NULL), m_pState2Ows (NULL), m_pFollow (NULL), m_AnyIw (0), m_LastPos (-1), m_pOws (NULL), m_MaxOwsSize (0) { m_known_dfa_iw.SetAllocator (pAlloc); m_known_dfa_iw.Create (); m_ows.SetAllocator (pAlloc); m_ows.Create (); m_follow.SetAllocator (pAlloc); m_follow.Create (); const int InitialFollowSetSize = 100; m_follow.resize (InitialFollowSetSize); m_FollowSetSize = 0; m_FollowSetMaxSize = InitialFollowSetSize; m_pFollowSet = m_follow.begin (); m_Iws.SetAllocator (pAlloc); } template < class Ty > void FAAutInterpretTools_pos_t< Ty >::SetAnyIw (const int AnyIw) { m_AnyIw = AnyIw; } template < class Ty > void FAAutInterpretTools_pos_t< Ty >::SetRsDfa (const FARSDfaCA * pDfa) { m_pDfa = pDfa; if (NULL != pDfa) { const int Size = m_pDfa->GetIWs (NULL, 0); DebugLogAssert (0 < Size); m_Iws.Create (Size); m_Iws.resize (Size); m_pDfa->GetIWs (m_Iws.begin (), Size); const int * pIws = m_Iws.begin (); DebugLogAssert (pIws && FAIsSortUniqed (pIws, Size)); const int MaxIw = pIws [Size - 1]; m_known_dfa_iw.resize (MaxIw + 1); m_known_dfa_iw.set_bits (0, MaxIw, false); for (int i = 0; i < Size; ++i) { const int Iw = pIws [i]; m_known_dfa_iw.set_bit (Iw, true); } m_Iws.Clear (); } // of if (NULL != pDfa) ... } template < class Ty > void FAAutInterpretTools_pos_t< Ty >:: SetState2Ows (const FAState2OwsCA * pState2Ows) { m_pState2Ows = pState2Ows; if (NULL != m_pState2Ows) { const int MaxOwsSize = m_pState2Ows->GetMaxOwsCount (); m_ows.resize (MaxOwsSize); m_pOws = m_ows.begin (); m_MaxOwsSize = MaxOwsSize; } } template < class Ty > void FAAutInterpretTools_pos_t< Ty >::SetFollow (const FARSNfaCA * pFollow) { m_pFollow = pFollow; if (m_pFollow) { // get initial states const int * pInitials; #ifndef NDEBUG const int InitialCount = #endif m_pFollow->GetInitials (&pInitials); // there should be only one, which is LastPos DebugLogAssert (1 == InitialCount && pInitials); m_LastPos = *pInitials; } } template < class Ty > inline const int FAAutInterpretTools_pos_t< Ty >:: Symbol2DfaIw (const int Symbol) const { DebugLogAssert (0 <= Symbol); if ((unsigned int) Symbol >= m_known_dfa_iw.size ()) { return m_AnyIw; } else if (m_known_dfa_iw.get_bit (Symbol)) { return Symbol; } else { return m_AnyIw; } } template < class Ty > inline const int FAAutInterpretTools_pos_t< Ty >:: GetNextPos ( const int * pStateSet, const int StateSetSize ) const { DebugLogAssert (1 < m_FollowSetSize && m_pFollowSet); DebugLogAssert (FAIsSortUniqed (m_pFollowSet, m_FollowSetSize)); DebugLogAssert (0 < StateSetSize && pStateSet); DebugLogAssert (FAIsSortUniqed (pStateSet, StateSetSize)); // O (Min*log(Max)) if (10 >= m_FollowSetSize || 10 >= StateSetSize) { if (StateSetSize > m_FollowSetSize) { int i = m_FollowSetSize - 1; for (; i >= 0; --i) { const int Pos = m_pFollowSet [i]; if (-1 != FAFind_log (pStateSet, StateSetSize, Pos)) return Pos; } } else { int i = StateSetSize - 1; for (; i >= 0; --i) { const int Pos = pStateSet [i]; if (-1 != FAFind_log (m_pFollowSet, m_FollowSetSize, Pos)) return Pos; } } // fatal error, intersection must exist DebugLogAssert (0); return -1; // O (Min+Max) } else { int i = m_FollowSetSize - 1; int j = StateSetSize - 1; while (m_pFollowSet [i] != pStateSet [j]) { if (m_pFollowSet [i] > pStateSet [j]) i--; else j--; if (0 > i || 0 > j) { // fatal error, intersection must exist DebugLogAssert (0); return -1; } } return m_pFollowSet [i]; } } template < class Ty > inline const bool FAAutInterpretTools_pos_t< Ty >:: Chain2States ( const Ty * pInChain, __out_ecount(Size) int * pStates, const int Size ) const { DebugLogAssert (m_pDfa && m_pState2Ows && m_pFollow); DebugLogAssert (0 < Size && pInChain && pStates); int State = m_pDfa->GetInitial (); for (int i = 0; i < Size; ++i) { const int Symbol = pInChain [i]; const int Iw = Symbol2DfaIw (Symbol); pStates [i] = State; State = m_pDfa->GetDest (State, Iw); if (-1 == State) { return false; } } if (!m_pDfa->IsFinal (State)) { return false; } return true; } template < class Ty > inline const bool FAAutInterpretTools_pos_t< Ty >:: Chain2States_local ( const Ty * pInChain, __out_ecount(Size) int * pStates, const int Size ) const { DebugLogAssert (m_pDfa && m_pState2Ows && m_pFollow); DebugLogAssert (0 < Size && pInChain && pStates); int DstState; int State = m_pDfa->GetInitial (); for (int i = 0; i < Size; ++i) { pStates [i] = State; const int Symbol = pInChain [i]; DstState = m_pDfa->GetDest (State, Symbol); if (-1 == DstState) { State = m_pDfa->GetDest (State, m_AnyIw); if (-1 == State) return false; } else { State = DstState; } } if (!m_pDfa->IsFinal (State)) { return false; } return true; } template < class Ty > inline void FAAutInterpretTools_pos_t< Ty >:: BuildFollowSet (const int CurrPos, const int Symbol) { DebugLogAssert (m_pDfa && m_pState2Ows && m_pFollow); int Iw = Symbol; // try to find transition by Symbol m_FollowSetSize = \ m_pFollow->GetDest (CurrPos, Iw, m_pFollowSet, m_FollowSetMaxSize); // if not found, try to find transition by m_AnyIw if (-1 == m_FollowSetSize) { Iw = m_AnyIw; m_FollowSetSize = \ m_pFollow->GetDest (CurrPos, Iw, m_pFollowSet, m_FollowSetMaxSize); } // see whether buffer was not enough to copy follow set values if (m_FollowSetMaxSize < m_FollowSetSize) { m_follow.resize (m_FollowSetSize); m_FollowSetMaxSize = m_FollowSetSize; m_pFollowSet = m_follow.begin (); m_FollowSetSize = \ m_pFollow->GetDest (CurrPos, Iw, m_pFollowSet, m_FollowSetMaxSize); DebugLogAssert (m_FollowSetMaxSize == m_FollowSetSize); } } template < class Ty > inline void FAAutInterpretTools_pos_t< Ty >:: States2Pos ( const Ty * pInChain, const int * pStates, __out_ecount(Size) int * pPosChain, const int Size ) { DebugLogAssert (-1 != m_LastPos); DebugLogAssert (m_pDfa && m_pState2Ows && m_pFollow); DebugLogAssert (0 < Size && pInChain && pPosChain && pStates); int OwsCount; int CurrPos = m_LastPos; int State; for (int i = Size - 1; i >= 0; --i) { const int Symbol = pInChain [i]; // get follow set BuildFollowSet (CurrPos, Symbol); DebugLogAssert (0 < m_FollowSetSize && m_pFollowSet); // see whether there is one element in if (1 == m_FollowSetSize) { CurrPos = *m_pFollowSet; } else { State = pStates [i]; OwsCount = m_pState2Ows->GetOws (State, m_pOws, m_MaxOwsSize); DebugLogAssert (m_MaxOwsSize >= OwsCount); DebugLogAssert (0 < OwsCount); CurrPos = GetNextPos (m_pOws, OwsCount); } pPosChain [i] = CurrPos; } // of for (i = Size - 1; ... } template < class Ty > const bool FAAutInterpretTools_pos_t< Ty >:: Chain2PosChain ( const Ty * pInChain, __out_ecount(Size) int * pPosChain, const int Size ) { DebugLogAssert (-1 != m_LastPos); DebugLogAssert (m_pDfa && m_pState2Ows && m_pFollow); DebugLogAssert (0 < Size && pInChain && pPosChain); int * pStates = pPosChain; // get states along the match path if (false == Chain2States (pInChain, pStates, Size)) return false; // reconstruct match positions States2Pos (pInChain, pStates, pPosChain, Size); return true; } template < class Ty > const bool FAAutInterpretTools_pos_t< Ty >:: Chain2PosChain_local ( const Ty * pInChain, __out_ecount(Size) int * pPosChain, const int Size ) { DebugLogAssert (-1 != m_LastPos); DebugLogAssert (m_pDfa && m_pState2Ows && m_pFollow); DebugLogAssert (0 < Size && pInChain && pPosChain); int * pStates = pPosChain; // get states along the match path if (false == Chain2States_local (pInChain, pStates, Size)) return false; // reconstruct match positions States2Pos (pInChain, pStates, pPosChain, Size); return true; } } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FATaggedTextA.h
<reponame>palerdot/BlingFire /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_TAGGEDTEXTA_H_ #define _FA_TAGGEDTEXTA_H_ #include "FAConfig.h" #include "FATaggedTextCA.h" namespace BlingFire { class FATaggedTextA : public FATaggedTextCA { public: // adds a new word (no offset) virtual void AddWord ( const int * pWord, const int Length, const int Tag ) = 0; // adds a new word with offset virtual void AddWord ( const int * pWord, const int Length, const int Tag, const int Offset ) = 0; // makes object empty virtual void Clear () = 0; }; } #endif
palerdot/BlingFire
blingfireclient.library/inc/FATransform_hyph_redup_t.h
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_TRANSFORM_HYPH_REDUP_T_H_ #define _FA_TRANSFORM_HYPH_REDUP_T_H_ #include "FAConfig.h" #include "FATransformCA_t.h" #include "FASecurity.h" namespace BlingFire { /// /// This class transforms hyphenated reduplication in the beginning of /// the input sequence into a reduplicant followed by a selected delimiter /// and the rest of the sequence. /// /// For example: /// "aaab-aaabce" -> "aaab\x02ce" /// Where 0x02 was selected as a delimiter /// /// Note: /// 1. If the transformation is not applicable then Process method return -1. /// 2. if pIn == pOut then transformation is made in-place. /// template < class Ty > class FATransform_hyph_redup_t : public FATransformCA_t < Ty > { public: FATransform_hyph_redup_t (); public: /// sets up delimiter value void SetDelim (const Ty Delim); /// makes transformation /// Note: this function has to be *within* the class definition, because otherwise compiler makes an error /// and generates some warnings about "unreferenced local function has been removed". const int Process ( const Ty * pIn, const int InCount, __out_ecount(MaxOutSize) Ty * pOut, const int MaxOutSize ) const { // as __in_range(0, FALimits::MaxWordSize) const int InCount does not work __analysis_assume (0 < InCount && FALimits::MaxWordSize >= InCount && pIn); DebugLogAssert (0 < InCount && FALimits::MaxWordSize >= InCount && pIn); // we are only interested to find hyphen in the first half of an input const int HalfCount = (InCount + 1) >> 1; int HyphPos = GetHyphPos (0, pIn, HalfCount); while (-1 != HyphPos) { // see whether hyphenated reduplication exists if (true == IsHyphRedup (pIn, InCount, HyphPos)) { break; } HyphPos = GetHyphPos (HyphPos + 1, pIn, HalfCount); } // see whether hyphen exists if (-1 == HyphPos) { return -1; } // see FATransform_hyph_redup_t< Ty >::GetHyphPos implementation __analysis_assume (0 < InCount && 0 <= HyphPos && HalfCount > HyphPos); DebugLogAssert (0 < InCount && 0 <= HyphPos && HalfCount > HyphPos); // calc output size const int OutSize = InCount - HyphPos; // as InCount > (2 * HyphPos) which is at most InCount - 1 __analysis_assume (HyphPos < OutSize); DebugLogAssert (HyphPos < OutSize); if (MaxOutSize >= OutSize) { int pos; // check whether transformation is not made in-place if (pOut != pIn) { // copy everything before hyphen for (pos = 0; pos < HyphPos; ++pos) { pOut [pos] = pIn [pos]; } } else { // start from HyphPos pos = HyphPos; } // put delimiter pOut [pos] = m_Delim; pos++; // skip the hyphen and the right duplicant pIn += ((HyphPos << 1) + 1); // copy the rest, if any for (; pos < OutSize; ++pos) { pOut [pos] = *pIn++; } } return OutSize; } private: // returns hyphen position, returns -1 if not found inline const int GetHyphPos ( const int FromPos, const Ty * pIn, const int InCount ) const; // returns true if hyphenated reduplication exist inline const bool IsHyphRedup ( const Ty * pIn, const int InCount, const int HyphPos ) const; private: // delimiter Ty m_Delim; // constants enum { DefDelim = 2, DefHyphen = '-', }; }; template < class Ty > FATransform_hyph_redup_t< Ty >:: FATransform_hyph_redup_t () : m_Delim (DefDelim) { } template < class Ty > void FATransform_hyph_redup_t< Ty >:: SetDelim (const Ty Delim) { m_Delim = Delim; } template < class Ty > inline const int FATransform_hyph_redup_t< Ty >:: GetHyphPos (const int FromPos, const Ty * pIn, const int InCount) const { DebugLogAssert (0 <= InCount); for (int i = FromPos; i < InCount; ++i) { DebugLogAssert (pIn); if (DefHyphen == pIn [i]) { return i; } } return -1; } template < class Ty > inline const bool FATransform_hyph_redup_t< Ty >:: #ifndef NDEBUG IsHyphRedup (const Ty * pIn, const int InCount, const int HyphPos) const #else IsHyphRedup (const Ty * pIn, const int, const int HyphPos) const #endif { DebugLogAssert (pIn && 0 < InCount && InCount >= (HyphPos << 1)); const Ty * pLeft = pIn; const Ty * pRight = pIn + HyphPos + 1; for (int pos = 0; pos < HyphPos; ++pos) { if (pLeft [pos] != pRight [pos]) { return false; } } return true; } } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FALessA.h
<filename>blingfirecompile.library/inc/FALessA.h<gh_stars>1000+ /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_LESSA_H_ #define _FA_LESSA_H_ #include "FAConfig.h" namespace BlingFire { class FALessA { public: virtual const bool Less (const int Val1, const int Val2) const = 0; }; } #endif
palerdot/BlingFire
blingfireclient.library/inc/FAWREConfCA.h
<gh_stars>1000+ /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_WRECONFCA_H_ #define _FA_WRECONFCA_H_ #include "FAConfig.h" namespace BlingFire { class FAArrayCA; class FAState2OwCA; class FAState2OwsCA; class FAMealyDfaCA; class FAMultiMapCA; class FARSDfaCA; /// /// An run-time interface to the compiled WRE data. /// class FAWREConfCA { public: /// returns WRE rule type virtual const int GetType () const = 0; /// returns token type virtual const int GetTokenType () const = 0; /// returns base tag Ow value virtual const int GetTagOwBase () const = 0; /// returns Txt digitizer's DFA, or NULL virtual const FARSDfaCA * GetTxtDigDfa () const = 0; /// returns Txt digitizer's Ows map, or NULL virtual const FAState2OwCA * GetTxtDigOws () const = 0; /// returns Dict digitizer, true if exists virtual const FAArrayCA * GetDictDig () const = 0; /// returns rules Dfa1, NULL if does not exist virtual const FARSDfaCA * GetDfa1 () const = 0; /// returns rules Dfa2, NULL if does not exist virtual const FARSDfaCA * GetDfa2 () const = 0; /// returns Moore automaton reaction, NULL if does not exist virtual const FAState2OwsCA * GetState2Ows () const = 0; /// returns Sigma1, NULL if does not exist virtual const FAMealyDfaCA * GetSigma1 () const = 0; /// returns Sigma2, NULL if does not exist virtual const FAMealyDfaCA * GetSigma2 () const = 0; /// returns TrBr map, NULL if does not exist virtual const FAMultiMapCA * GetTrBrMap () const = 0; }; } #endif
palerdot/BlingFire
blingfireclient.library/inc/FADigitizer_t.h
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_DIGITIZER_T_H_ #define _FA_DIGITIZER_T_H_ #include "FAConfig.h" #include "FARSDfaCA.h" #include "FAState2OwCA.h" #include "FAUtf32Utils.h" namespace BlingFire { class FAAllocatorA; /// /// Assigns a digitial value to the input chain acording to the input Moore /// automaton or assigns m_AnyOw. /// template < class Ty > class FADigitizer_t { public: FADigitizer_t (); ~FADigitizer_t (); public: /// sets up digitizer automaton void SetRsDfa (const FARSDfaCA * pDfa); /// sets up state reaction void SetState2Ow (const FAState2OwCA * pState2Ow); /// sets up AnyOtherIw, 0 by default void SetAnyIw (const int AnyIw); /// sets up AnyOtherOw, 0 by default void SetAnyOw (const int AnyOw); /// converts input symbols into lower case void SetIgnoreCase (const bool IgnoreCase); /// this method must be called once after all automata set up void Prepare (); /// returns Ow corresponding to the Chain const int Process (const Ty * pChain, const int Size) const; private: void Clear(); /// returns m_AnyIw if Iw not in m_pSymbol2Iw inline const int Symbol2Iw (int Symbol) const; private: int m_AnyIw; int m_AnyOw; const FAState2OwCA * m_pState2Ow; const FARSDfaCA * m_pDfa; int m_MaxIw; int * m_pSymbol2Iw; bool m_IgnoreCase; }; template < class Ty > FADigitizer_t< Ty >::FADigitizer_t () : m_AnyIw (0), m_AnyOw (0), m_pState2Ow (NULL), m_pDfa (NULL), m_MaxIw (0), m_pSymbol2Iw (NULL), m_IgnoreCase (false) {} template < class Ty > FADigitizer_t< Ty >::~FADigitizer_t () { FADigitizer_t< Ty >::Clear (); } template < class Ty > void FADigitizer_t< Ty >::Clear () { if (m_pSymbol2Iw) { delete [] m_pSymbol2Iw; m_pSymbol2Iw = NULL; } } template < class Ty > void FADigitizer_t< Ty >::SetRsDfa (const FARSDfaCA * pDfa) { m_pDfa = pDfa; } template < class Ty > void FADigitizer_t< Ty >::SetState2Ow (const FAState2OwCA * pState2Ow) { m_pState2Ow = pState2Ow; } template < class Ty > void FADigitizer_t< Ty >::SetAnyIw (const int AnyIw) { m_AnyIw = AnyIw; } template < class Ty > void FADigitizer_t< Ty >::SetAnyOw (const int AnyOw) { m_AnyOw = AnyOw; } template < class Ty > void FADigitizer_t< Ty >::SetIgnoreCase (const bool IgnoreCase) { m_IgnoreCase = IgnoreCase; } template < class Ty > void FADigitizer_t< Ty >::Prepare () { LogAssert (m_pDfa); const int IwsCount = m_pDfa->GetIWs (NULL, 0); LogAssert (0 < IwsCount); int * pIws = new int [IwsCount]; LogAssert (pIws); m_pDfa->GetIWs (pIws, IwsCount); DebugLogAssert (pIws && FAIsSortUniqed (pIws, IwsCount)); m_MaxIw = pIws [IwsCount - 1]; if (m_pSymbol2Iw) { delete [] m_pSymbol2Iw; m_pSymbol2Iw = NULL; } m_pSymbol2Iw = new int [m_MaxIw + 1]; LogAssert (m_pSymbol2Iw); for (int Iw = 0; Iw <= m_MaxIw; ++Iw) { m_pSymbol2Iw [Iw] = m_AnyIw; } for (int iw_idx = 0; iw_idx < IwsCount; ++iw_idx) { const int Iw = pIws [iw_idx]; m_pSymbol2Iw [Iw] = Iw; } delete [] pIws; pIws = NULL; } template < class Ty > inline const int FADigitizer_t< Ty >::Symbol2Iw (int Symbol) const { DebugLogAssert (0 <= Symbol); if (m_IgnoreCase) { Symbol = FAUtf32ToLower (Symbol); } if (0 <= Symbol && Symbol <= m_MaxIw) { const int Iw = m_pSymbol2Iw [Symbol]; return Iw; } else { return m_AnyIw; } } template < class Ty > const int FADigitizer_t< Ty >::Process (const Ty * pChain, const int Size) const { DebugLogAssert (m_pDfa); DebugLogAssert (m_pState2Ow); int State = m_pDfa->GetInitial (); for (int i = 0; i < Size; ++i) { DebugLogAssert (pChain); // convert input symbol into integer symbol const int Symbol = pChain [i]; // convert input integer symbol into Iw const int Iw = Symbol2Iw (Symbol); // get go to the following state State = m_pDfa->GetDest (State, Iw); if (-1 == State) { return m_AnyOw; } } // get the Ow const int Ow = m_pState2Ow->GetOw (State); if (-1 != Ow) return Ow; else return m_AnyOw; } } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FAWRETokens2Dicts.h
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_WRETOKENS2DICTS_H_ #define _FA_WRETOKENS2DICTS_H_ #include "FAConfig.h" #include "FAChain2Num_hash.h" #include "FAWRETokenParser.h" #include "FAWREToken.h" #include "FAArray_cont_t.h" #include <iostream> namespace BlingFire { class FAAllocatorA; class FAChain2NumA; class FAMultiMapA; class FATagSet; /// /// Reads WRE tokens and creates Digitizer\TokenNum -> CNF mapping and /// a list of commands for text-digitizer /// /// 1. Stream of commands for building text-digitizer /// 2. FAChain2NumA Map from Digitizer\TokenNum into CNF of TypeNums /// 3. TypeNum depend on digitizer type /// /// Sample text-digitizer commands: /// /// dict\n /// <dictname>\n /// \n ; reads dictionary from the outer resources /// regexp\n /// <regexp>\n /// \n ; compiles dynamic dictionary from the regexp /// wordlist\n /// word_1 /// word_2 /// ... /// word_n /// \n ; compiles dynamic dictionary from the words /// ... /// /// Sample map from Digitizer\TokenNum into CNF of elementary types: /// /// 0x00000008 -> 3 7 -8 -3 ; Txt\Token8 = Ty7 | !Ty8 | !Ty3 /// 0x00000006 -> 5 7 0 -8 0 -3 ; Txt\Token6 = Ty7 & !Ty8 & !Ty3 /// 0x00000005 -> 1 6 ; Txt\Token5 = Ty6 /// 0x01000005 -> 1 6 ; Tag\Token5 = Ty6 /// 0x02000005 -> 1 6 ; Dct\Token5 = Ty6 /// ... /// class FAWRETokens2Dicts { public: FAWRETokens2Dicts (FAAllocatorA * pAlloc); virtual ~FAWRETokens2Dicts (); public: /// sets up POS tagger's tagset (not used by default) void SetTagSet (const FATagSet * pTagSet); /// sets up bits lexicon's tagset (not used by default) void SetTagSet2 (const FATagSet * pTagSet2); /// sets up ordered wre tokens list void SetTokens (const FAChain2NumA * pToken2Num); /// Stream for commands for building text digitizer void SetDictOs (std::ostream * pDictOs); /// storage for token num 2 cnf map /// Token0 = (Ty1 | T2 | !T3) & (Ty4 | T5 | !T6) & T8 & !T9 /// 0 -> 1 2 -3 0 4 5 -6 0 8 0 -9 void SetToken2CNF (FAMultiMapA * pTokenNum2CNF); /// Makes processing void Process (); /// returns object into initial state (called automatically) virtual void Clear (); private: /// makes consequent parsing for tokens from m_pToken2Num map void ParseTokens (); /// makes processing for newly reinitialized m_curr_token void ProcessCurrToken (const int TokenNum); void ProcessCurrWords (const int TokenNum); void ProcessCurrRegexps (const int TokenNum); void ProcessCurrDicts (const int TokenNum); void ProcessCurrTags (const int TokenNum); /// returns all the types to build text-digitzer void PutTxtTypes (); /// puts all words from m_curr_token into m_arr inline void words2arr (); /// puts regexp_i into the m_arr /// Note: regexp '.' and word "." will have the different representation inline void regexp2arr (const int i); /// puts dict_i into the m_arr inline void dict2arr (const int i); /// returns type num by words inline const int arr2typenum (); /// starts a new disjunction associated with the TokenNum inline void StartDisjunct (const int TokenNum); /// adds to the last disjunct associated with the TokenNum inline void AddToDisjunct (const int TokenNum, const int TypeNum, const bool IsNegative); protected: // returns unescaped string const int UnEscape ( const char * pStr, const int StrLen, const char ** ppOutStr ); /// returns next wordlist for text-digitizer virtual void PutTxtWords (const char * pBegin, const int Length); /// returns next regexp for text-digitizer virtual void PutTxtRegexp (const char * pBegin, const int Length); /// returns next dict name for text-digitizer virtual void PutTxtDictName (const char * pBegin, const int Length); /// returns a set of tags for tag digitizer virtual void PutPosTags (const int * pTags, const int Count); /// returns a set of tags for dict digitizer virtual void PutDictTags (const int * pTags, const int Count); /// should be called when all tokens have been processed virtual void PutDone (); private: /// input : WRE tokens const FAChain2NumA * m_pToken2Num; /// output stream : token -> type ops FAMultiMapA * m_pTokenNum2CNF; /// output stream : dictionaries, required by the rules std::ostream * m_pDictOs; /// WRE token parser FAWRETokenParser m_token_parser; /// currently processing WRE token FAWREToken m_curr_token; /// allocator FAAllocatorA * m_pAlloc; /// tmp array FAArray_cont_t < int > m_arr; /// first unused value of TypeNum, 1-based int m_min_type; // keeps unescaped text, if needed FAArray_cont_t < char > m_UnEsc; // needed for text digitizer /// maps already seen words, dictionary names and regexps into type num FAChain2Num_hash m_token2type; /// key types in m_token2type enum { KEY_WORDLIST = 0, KEY_REGEXP = 1, KEY_DICT_NAME = 2 }; // needed for tag test or dict digitizers FAArray_cont_t < int > m_dict_tags; // keeps POS tagger tags FAArray_cont_t < int > m_pos_tags; protected: /// tagsets const FATagSet * m_pTagSet; const FATagSet * m_pTagSet2; }; } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FAWREToken.h
<filename>blingfirecompile.library/inc/FAWREToken.h /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_WRE_TOKEN_H_ #define _FA_WRE_TOKEN_H_ #include "FAConfig.h" #include "FAArray_t.h" #include "FAToken.h" namespace BlingFire { class FAAllocatorA; class FAWREToken { public: /// Token Types enum { TT_POSITIVE_WORD = 0, TT_NEGATIVE_WORD = 1, TT_POSITIVE_REGEXP = 2, TT_NEGATIVE_REGEXP = 3, TT_POSITIVE_DICT = 4, TT_NEGATIVE_DICT = 5, TT_POSITIVE_TAG = 6, TT_NEGATIVE_TAG = 7, }; public: /// an empty token constructor FAWREToken (FAAllocatorA * pAlloc); public: /// sets up and returns the pointer to the unparsed token void SetStr (const char * pStr); const char * GetStr () const; /// returns the number of tokens in each group const int GetWordCount () const; const int GetRegexpCount () const; const int GetDictCount () const; const int GetTagCount () const; /// returns token by index, 0-based const FAToken * GetWordToken (const int Idx) const; const FAToken * GetRegexpToken (const int Idx) const; const FAToken * GetDictToken (const int Idx) const; const FAToken * GetTagToken (const int Idx) const; /// adds a new token void AddWordToken (const int Type, const int Offset, const int Length); void AddRegexpToken (const int Type, const int Offset, const int Length); void AddDictToken (const int Type, const int Offset, const int Length); void AddTagToken (const int Type, const int Offset, const int Length); /// returns true if the corresponding list is disjunctive const bool GetWordsDisj () const; const bool GetRegexpsDisj () const; const bool GetDictsDisj () const; const bool GetTagsDisj () const; /// returns true if the corresponding list is disjunctive void SetWordsDisj (const bool WordsDisj); void SetRegexpsDisj (const bool RegexpsDisj); void SetDictsDisj (const bool DictsDisj); void SetTagsDisj (const bool TagsDisj); /// returns into the initial state void Clear (); private: /// a list of word tokens FAArray_t < FAToken > m_word_list; /// true if m_word_list is disjunctive bool m_disj_words; /// a list of regexp tokens FAArray_t < FAToken > m_regexp_list; /// true if m_regexp_list is disjunctive bool m_disj_regexps; /// a list of dictionary tokens FAArray_t < FAToken > m_dict_list; /// true if m_dict_list is disjunctive bool m_disj_dicts; /// a list of tag tokens FAArray_t < FAToken > m_tag_list; /// true if m_tag_list is disjunctive bool m_disj_tags; /// does not actualy store the string, just keeps the pointer const char * m_pStr; }; } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FAEncoderA.h
<reponame>palerdot/BlingFire<filename>blingfirecompile.library/inc/FAEncoderA.h /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_ENCODERA_H_ #define _FA_ENCODERA_H_ #include "FAConfig.h" namespace BlingFire { class FAEncoderA { public: /// returns the maximum possible number of bytes needed to encode one int virtual const int GetMaxBytes () const = 0; /// makes the encoding, returns the size of the encoded sequence virtual const int Encode (const int * pChain, const int Size, unsigned char * pOutBuffer) const = 0; }; } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FAOffsetTablePack.h
<filename>blingfirecompile.library/inc/FAOffsetTablePack.h<gh_stars>1000+ /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_OFFSETTABLEPACK_H_ #define _FA_OFFSETTABLEPACK_H_ #include "FAConfig.h" #include "FAArray_cont_t.h" namespace BlingFire { class FAAllocatorA; /// /// Packs offset tables, e.g. a growing array of non-negative numbers. /// /// Current implementation works approximatelly as follows: /// Offset = m_base [Idx >> m_SkipValue] + m_delta [Idx]. /// class FAOffsetTablePack { public: FAOffsetTablePack (FAAllocatorA * pAlloc); public: // sets up an array of offsets void SetOffsets (const unsigned int * pOffsets, const int OffsetCount); // builds memory dump void Process (); // returns built dump const int GetDump (const unsigned char ** ppDump) const; private: // returns object into the initial state void Clear (); // calculates SizeOfBase inline const int CalcSizeOfBase () const; // calculates SkipValue inline const int CalcSkipValue () const; // stores offsets as a single base array void StoreUncompressed (); // calculates m_base and m_delta arrays void BuildArrays (); // stores offsets as a pair base + deltas void StoreCompressed (); // encodes offset void EncodeOffset (const int Offset); private: // input offsets const unsigned int * m_pOffsets; int m_OffsetCount; // array of bases FAArray_cont_t < unsigned int > m_base; // array of deltas FAArray_cont_t < unsigned char > m_delta; // number of bytes to encode one base int m_SizeOfBase; // number of bits to cut to get index in m_base int m_SkipValue; // the resulting dump FAArray_cont_t < unsigned char > m_dump; unsigned char * m_pDump; unsigned int m_Offset; }; } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FAWREIO.h
<gh_stars>1000+ /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_WREIO_H_ #define _FA_WREIO_H_ #include "FAConfig.h" #include <iostream> namespace BlingFire { class FAWREConfA; /// /// Saves compiled WRE in a textual format /// void FAPrintWre (std::ostream & os, const FAWREConfA * pWRE); /// /// Reads compiled WRE from a textual format /// void FAReadWre (std::istream & is, FAWREConfA * pWRE); /// /// Builds and saves WRE memory dump /// void FASaveWre (std::ostream & os, const FAWREConfA * pWRE); } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FALexBreaker.h
<gh_stars>1000+ /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_FALEXBREAKER_H_ #define _FA_FALEXBREAKER_H_ #include "FALexTools_t.h" #include "FAArray_cont_t.h" #include "FATagSet.h" #include "FALimits.h" namespace BlingFire { /// /// fa_lex based word-breaker /// /// Notes: /// /// 1. The word breaker allocates from the pool a buffer of size 20*cbUTF8Text /// bytes, if the cbUTF8Text < MaxBuffSize else it uses a constant size /// buffer of 20*MaxBuffSize bytes. /// 2. Output words are limited to have no more than MaxWordLen symbols. /// class FALexBreaker { public: FALexBreaker (); ~FALexBreaker (); /// Initialize the wordbreaker before using it. /// Provide an initialized configuration object. /// Extra initializations are ignored, returns ERROR_SUCCESS upon success bool Initialize (const FAWbdConfKeeper * pConfig); // De-Initializes the wordbreaker // De-initializing an un-initialized object is ignored // Call this method if you want to reinitialize the word-breaker void DeInitialize (); /// specifies the input should be treated as a sequence of bytes, /// by default the input is a UTF-8 string void SetUseBytes (const bool fUseBytes); /// if set, the word tags are returned void SetTagSet (const FATagSet * pTagSet); /// if set, the surface word-forms are returned void SetOutText (FAArray_cont_t < char > * pOutText); /// if set, the normalized word-forms are returned void SetOutNormText (FAArray_cont_t < char > * pOutNormText); /// Breaks up the given buffer of text into words according to the compiled /// fa_lex grammar. Each discovered word is copied to the output object, /// together with offsets in the input buffer. The output object will be /// initialized inside the method, old entries will be retained returns /// ERROR_SUCCESS upon success bool BreakText (const UInt8 *pbUTF8Text, size_t cbUTF8Text); private: // internal bool BreakText_int (const UInt8 *pbUTF8Text, size_t cbUTF8Text) ; // returns object into the initial state void Clear (); // m_Txt buffer filled in, the function fills in m_Tokens buffer void ProcessTxt (); // m_Tokens buffer filled in the function iterates thru the tokens // in the right order and feeds them to the PutToken void ProcessTokens () const; // helper inline void AddWord ( FAArray_cont_t < char > * pOutText, const UInt8 * pWord, const size_t Length, const int Tag ) const; // adds a token with a proper normalization into the FAArray_cont_t < char > inline void PutToken ( const int Tag, // token tag const int TxtFrom, // UTF-32LE token offset from int TxtTo, // UTF-32LE token offset to const int * pTxt = NULL, // UTF-32LE normalized token text int TxtLen = 0 // UTF-32LE normalized token length ) const; private: /// predefined constants enum { MaxWordLen = FALimits::MaxWordLen, MaxBuffSize = 0x100000, }; /// indicates whether this object was initialized bool m_fInitialized; bool m_fUseBytes; int m_iXWordTag; int m_iSegTag; int m_iIgnoreTag; /// input const UInt8 * m_pbUTF8Text; size_t m_cbUTF8Text; const FATagSet * m_pTagSet; /// output FAArray_cont_t < char > * m_pOutText; FAArray_cont_t < char > * m_pOutNormText; /// the tokenizer FALexTools_t < int > m_wbd; /// UTF-32LE normalization map, changes length for some characters const FAMultiMapCA * m_pNorm; /// current Offset in the input string size_t m_uUtf8Offset; /// current offset in the m_Txt array unsigned int m_uTxtOffset; /// temporary fixed buffer: one piece of text in UTF-32 int m_pTxt [MaxBuffSize]; int m_pOffsets [MaxBuffSize]; unsigned int m_uTxtLen; /// temporary fixed buffer: a set of tokens extracted from one line int m_pTokens [MaxBuffSize * 3]; int m_iTokensSize; // amount of characters which can be processed at once unsigned int m_uMaxCharsAtOnce; // amount of tokens which can be processed at once unsigned int m_uMaxTokensSize; }; } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FATokenNfa2Nfa_t.h
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_TOKENNFA2NFA_H_ #define _FA_TOKENNFA2NFA_H_ #include "FAConfig.h" #include "FAAllocatorA.h" #include "FAMultiMapA.h" #include "FAMultiMap_judy.h" #include "FASetUtils.h" #include "FAFsmConst.h" namespace BlingFire { /// /// This class substitutes TokenNums (Iws) of input automaton with /// Ows of corresponding digitizer. /// template < class NFA > class FATokenNfa2Nfa_t { public: FATokenNfa2Nfa_t (FAAllocatorA * pAlloc); public: /// sets up digitizer type, if multiple digitizers are used void SetDigitizer (const int Digitizer); /// additional iw which will be added to alphabet, same as AnyOw for digitizer void SetAnyIw (const int AnyIw); /// the base for TokenNums, other Iws should not be modified void SetTnBaseIw (const int TnBaseIw); /// the maximum value for TokenNums, other Iws should not be modified void SetTnMaxIw (const int TnMaxIw); /// input nfa with TokenNum as input weights void SetTokenNfa (const NFA * pTokenNfa); /// input map from TokenNum to CNF on TypeNum(s) void SetTokenNum2CNF (const FAMultiMapA * pToken2CNF); /// input map from TypeNum to set of output weights of the digitizer void SetTypeNum2Ows (const FAMultiMapA * pTypeNum2OwSet); /// output nfa where the Iws are Ows of the digitizer void SetOutNfa (NFA * pOutNfa); /// makes the processing itself void Process (); /// returns object into the initial state void Clear (); private: /// void Prepare (); /// calcs m_token_ows, it contains Ow's from digitizer only + m_AnyIw /// it does not contain special symbols such as LeftAnchor and RightAnchor void CalcOwsAlphabet (); /// calculates m_Token2OwSet from m_pToken2CNF and m_pTypeNum2OwSet map void CalcMap (); /// calculates Ows set by the given CNF on TypeNums const int CNF2OwsSet ( const int * pCNF, const int CNFSize, const int ** ppOwsSet ); /// sets up transitions for the given state void ProcessState (const int State); private: /// input int m_Digitizer; int m_AnyIw; int m_TnBaseIw; int m_TnMaxIw; const NFA * m_pTokenNfa; const FAMultiMapA * m_pToken2CNF; const FAMultiMapA * m_pTypeNum2OwSet; /// output NFA * m_pOutNfa; /// maximum ow, among both token ows and non-token ows int m_MaxOw; /// Ows alphabet for Tokens FAArray_cont_t < int > m_token_ows; /// temporary n-sets container FAArray_cont_t < const int * > m_tmp_sets; FAArray_cont_t < int > m_tmp_sizes; /// map from TokenNum into Set of Ows FAMultiMap_judy m_Token2OwSet; /// set utility FASetUtils m_set_utils; }; template < class NFA > FATokenNfa2Nfa_t < NFA >::FATokenNfa2Nfa_t (FAAllocatorA * pAlloc) : m_Digitizer (FAFsmConst::DIGITIZER_TEXT), m_AnyIw (0), m_TnBaseIw (0), m_TnMaxIw (0), m_pTokenNfa (NULL), m_pToken2CNF (NULL), m_pTypeNum2OwSet (NULL), m_pOutNfa (NULL), m_MaxOw (0), m_set_utils (pAlloc) { m_set_utils.SetResCount (4); m_token_ows.SetAllocator (pAlloc); m_token_ows.Create (); m_tmp_sets.SetAllocator (pAlloc); m_tmp_sets.Create (); m_tmp_sizes.SetAllocator (pAlloc); m_tmp_sizes.Create (); m_Token2OwSet.SetAllocator (pAlloc); } template < class NFA > void FATokenNfa2Nfa_t < NFA >::Clear () { m_token_ows.Clear (); m_token_ows.Create (); m_tmp_sets.Clear (); m_tmp_sets.Create (); m_tmp_sizes.Clear (); m_tmp_sizes.Create (); m_Token2OwSet.Clear (); } template < class NFA > void FATokenNfa2Nfa_t < NFA >:: SetDigitizer (const int Digitizer) { m_Digitizer = Digitizer; } template < class NFA > void FATokenNfa2Nfa_t < NFA >::SetAnyIw (const int AnyIw) { m_AnyIw = AnyIw; } template < class NFA > void FATokenNfa2Nfa_t < NFA >::SetTnBaseIw (const int TnBaseIw) { m_TnBaseIw = TnBaseIw; } template < class NFA > void FATokenNfa2Nfa_t < NFA >::SetTnMaxIw (const int TnMaxIw) { m_TnMaxIw = TnMaxIw; } template < class NFA > void FATokenNfa2Nfa_t < NFA >::SetTokenNfa (const NFA * pTokenNfa) { m_pTokenNfa = pTokenNfa; } template < class NFA > void FATokenNfa2Nfa_t < NFA >::SetTokenNum2CNF (const FAMultiMapA * pToken2CNF) { m_pToken2CNF = pToken2CNF; } template < class NFA > void FATokenNfa2Nfa_t < NFA >::SetTypeNum2Ows (const FAMultiMapA * pTypeNum2OwSet) { m_pTypeNum2OwSet = pTypeNum2OwSet; } template < class NFA > void FATokenNfa2Nfa_t < NFA >::SetOutNfa (NFA * pOutNfa) { m_pOutNfa = pOutNfa; } template < class NFA > void FATokenNfa2Nfa_t< NFA >::CalcOwsAlphabet () { DebugLogAssert (m_pTypeNum2OwSet); m_tmp_sets.resize (0); m_tmp_sizes.resize (0); /// add all OwsSets for union const int * pOwsSet; int TypeNum = -1; int OwsSetSize = m_pTypeNum2OwSet->Prev (&TypeNum, &pOwsSet); // the map can be empty, if multiple digitizers are used while (-1 != OwsSetSize) { DebugLogAssert (0 <= TypeNum); if (m_Digitizer == TypeNum >> 24) { m_tmp_sets.push_back (pOwsSet); m_tmp_sizes.push_back (OwsSetSize); } /// get next OwsSet OwsSetSize = m_pTypeNum2OwSet->Prev (&TypeNum, &pOwsSet); } /// add Any symbol m_tmp_sets.push_back (&m_AnyIw); m_tmp_sizes.push_back (1); /// calc the union const int ** pSetArray = m_tmp_sets.begin (); const int * pSizeArray = m_tmp_sizes.begin (); m_set_utils.UnionN (pSetArray, pSizeArray, m_tmp_sizes.size (), 0); /// generate alphabet const int * pUnion; const int UnionSize = m_set_utils.GetRes (&pUnion, 0); m_token_ows.resize (UnionSize); memcpy (m_token_ows.begin (), pUnion, UnionSize * sizeof (int)); } template < class NFA > const int FATokenNfa2Nfa_t< NFA >:: CNF2OwsSet (const int * pCNF, const int CNFSize, const int ** ppOwsSet) { DebugLogAssert (ppOwsSet); // CNF may not exist, if multiple digitizers are used if (-1 == CNFSize) { // proecss as if it was '.' *ppOwsSet = m_token_ows.begin (); const int OwsCount = m_token_ows.size (); return OwsCount; } DebugLogAssert (0 < CNFSize && pCNF); // res0 contain the resulting OwSet bool Initialized = false; /// res1 := {} m_set_utils.SetRes (NULL, 0, 1); // make iteration thru the CNF for (int i = 0; i < CNFSize; ++i) { DebugLogAssert (pCNF); const int TypeNum = pCNF [i]; if (0 < TypeNum) { /// get OwsSet const int * pOwsSet; const int TypeNum2 = (m_Digitizer << 24) | TypeNum; const int OwsSetSize = m_pTypeNum2OwSet->Get (TypeNum2, &pOwsSet); m_set_utils.SelfUnion (pOwsSet, OwsSetSize, 1); } else if (0 > TypeNum) { /// get OwsSet const int * pOwsSet; const int TypeNum2 = ((m_Digitizer << 24) | (-TypeNum)); const int OwsSetSize = m_pTypeNum2OwSet->Get (TypeNum2, &pOwsSet); /// res2 = m_token_ows - OwsSet m_set_utils.Difference (m_token_ows.begin (), m_token_ows.size (), 2, pOwsSet, OwsSetSize, 3); const int * pDiffSet; const int DiffSize = m_set_utils.GetRes (&pDiffSet, 2); /// add the difference to the disjunction set m_set_utils.SelfUnion (pDiffSet, DiffSize, 1); } else { DebugLogAssert (0 == TypeNum); /// see whether resulting set (res0) was not initialized already if (false == Initialized) { /// res0 = res1 const int * pOwsSet; const int OwsSetSize = m_set_utils.GetRes (&pOwsSet, 1); m_set_utils.SetRes (pOwsSet, OwsSetSize, 0); Initialized = true; } else { /// res0 = res0 & res1 const int * pOwsSet; const int OwsSetSize = m_set_utils.GetRes (&pOwsSet, 1); m_set_utils.SelfIntersect (pOwsSet, OwsSetSize, 0); } // of if (false == Intersect)... /// res1 := {} m_set_utils.SetRes (NULL, 0, 1); } // of if (0 < TypeNum) ... } // of for (int i = 0; ... if (Initialized) { // final intersection const int * pRes1; const int Res1Size = m_set_utils.GetRes (&pRes1, 1); if (0 < Res1Size) { m_set_utils.SelfIntersect (pRes1, Res1Size, 0); } const int OwsSetSize = m_set_utils.GetRes (ppOwsSet, 0); return OwsSetSize; } else { // no intersection needed const int OwsSetSize = m_set_utils.GetRes (ppOwsSet, 1); return OwsSetSize; } } template < class NFA > void FATokenNfa2Nfa_t< NFA >::CalcMap () { DebugLogAssert (m_pToken2CNF); m_MaxOw = 0; /// return the map into the initial state m_Token2OwSet.Clear (); /// assumed TokenNums are continuous const int MaxIw = m_pTokenNfa->GetMaxIw (); for (int Iw = 0; Iw <= MaxIw; ++Iw) { /// see whether Iw is outside the interval of TokenNums if (m_TnBaseIw > Iw || Iw > m_TnMaxIw) { /// add : Iw -> { Iw } m_Token2OwSet.Set (Iw, &Iw, 1); if (m_MaxOw < Iw) m_MaxOw = Iw; } else { DebugLogAssert (0 <= Iw - m_TnBaseIw); const int TokenNum = (m_Digitizer << 24) | (Iw - m_TnBaseIw); /// get next CNF const int * pCNF; const int CNFSize = m_pToken2CNF->Get (TokenNum, &pCNF); /// using CNF calculate OwsSet corresponding to the TokenNum const int * pOwsSet; const int OwsSetSize = CNF2OwsSet (pCNF, CNFSize, &pOwsSet); if (0 < OwsSetSize) { DebugLogAssert (pOwsSet); /// add : Iw -> OwsSet m_Token2OwSet.Set (Iw, pOwsSet, OwsSetSize); if (m_MaxOw < pOwsSet [OwsSetSize - 1]) m_MaxOw = pOwsSet [OwsSetSize - 1]; } else { /// the token represents empty set throw FAException ("The token is empty.", __FILE__, __LINE__); } } } // of for } template < class NFA > void FATokenNfa2Nfa_t< NFA >::Prepare () { DebugLogAssert (m_pToken2CNF); CalcOwsAlphabet (); /// calculates map from Iw to Ow, updates m_MaxOw CalcMap (); m_set_utils.SetResCount (m_MaxOw + 1); /// keep set utils' results containers empty m_set_utils.SetRes (NULL, 0, 0); m_set_utils.SetRes (NULL, 0, 1); m_set_utils.SetRes (NULL, 0, 2); m_set_utils.SetRes (NULL, 0, 3); } template < class NFA > void FATokenNfa2Nfa_t< NFA >::ProcessState (const int State) { DebugLogAssert (m_pTokenNfa); const int * pIWs; const int IwCount = m_pTokenNfa->GetIWs (State, &pIWs); // make iteration thru the input weights (TokenNums) for (int i = 0; i < IwCount; ++i) { DebugLogAssert (pIWs); const int TokenNum = pIWs [i]; const int * pOwsSet; const int OwsSetSize = m_Token2OwSet.Get (TokenNum, &pOwsSet); // get destination set const int * pDstSet; const int DstSetSize = m_pTokenNfa->GetDest (State, TokenNum, &pDstSet); // add this DstSet to all ows from OwsSet for (int j = 0; j < OwsSetSize; ++j) { DebugLogAssert (pOwsSet); const int Ow = pOwsSet [j]; // calc Res[ow] = Res[ow] U DstSet m_set_utils.SelfUnion (pDstSet, DstSetSize, Ow); } } // make iteration thru the _entire_ Ows alphabet, even thru the anchors for (int Ow = 0; Ow <= m_MaxOw; ++Ow) { /// get new destination set const int * pDstSet; const int DstSetSize = m_set_utils.GetRes (&pDstSet, Ow); /// see whether there are any transitions by the Ow if (0 < DstSetSize) { /// set up the transitions m_pOutNfa->SetTransition (State, Ow, pDstSet, DstSetSize); /// return result set into the initial state m_set_utils.SetRes (NULL, 0, Ow); } } } template < class NFA > void FATokenNfa2Nfa_t< NFA >::Process () { DebugLogAssert (m_pTokenNfa); DebugLogAssert (m_pToken2CNF); DebugLogAssert (m_pTypeNum2OwSet); DebugLogAssert (m_pOutNfa); /// builds weight maps and updates m_MaxOw Prepare (); /// get max ow m_pOutNfa->SetMaxIw (m_MaxOw); /// get max state const int MaxState = m_pTokenNfa->GetMaxState (); m_pOutNfa->SetMaxState (MaxState); m_pOutNfa->Create (); const int * pStates; int StateCount; /// copy initial states StateCount = m_pTokenNfa->GetInitials (&pStates); m_pOutNfa->SetInitials (pStates, StateCount); /// copy final states StateCount = m_pTokenNfa->GetFinals (&pStates); m_pOutNfa->SetFinals (pStates, StateCount); /// set up transitions for (int State = 0; State <= MaxState; ++State) { ProcessState (State); } /// make the output automaton ready m_pOutNfa->Prepare (); } } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FATypesNfaList2TypeNfa.h
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_TYPESNFALIST2TYPENFA_H_ #define _FA_TYPESNFALIST2TYPENFA_H_ #include "FAConfig.h" #include "FARSNfa_ar_judy.h" #include "FANfas2CommonENfa.h" #include "FAEpsilonRemoval.h" #include "FAChain2Num_judy.h" #include "FAArray_cont_t.h" namespace BlingFire { class FARSDfaA; class FAAllocatorA; /// /// Reads a list of RS automata from stream preceeding by the type information. /// Converts them into a single epsilon-free Nfa with type sets associated with /// each final state. /// /// Note: /// /// The algorithm makes additional treatment for AnyIw only if /// it has been explicitly set up. /// class FATypesNfaList2TypeNfa { public: FATypesNfaList2TypeNfa (FAAllocatorA * pAlloc); public: /// sets up epsilon input weight void SetEpsilonIw (const int EpsilonIw); /// sets up spacial AnyOther input weight void SetAnyIw (const int AnyIw); /// sets up the initial type iw void SetInitialTypeIw (const int InitialTypeIw); /// adds < TypeName, Nfa > pair void AddTyNfa (const char * pTypeStr, const FARSNfaA * pNfa); /// adds < TypeName, Dfa > pair void AddTyDfa (const char * pTypeStr, const FARSDfaA * pDfa); /// builds common Nfa void Process (); /// returns digitizer Nfa interface const FARSNfaA * GetNfa () const; /// returns object into initial state void Clear (); private: /// adds type info into the current dictionary nfa void AddTypeInfo (const int TypeIw); /// returns type associated with the string, or creates a new one const int GetType (const char * pTypeStr); /// frees all intermediate containers inline void Clear_a (); private: /// current type Iw int m_CurrTypeIw; /// initial type Iw int m_InitialTypeIw; /// dictionary nfa FARSNfa_ar_judy m_nfa; /// common nfa FANfas2CommonENfa m_common; /// epsilon removal algorithm FAEpsilonRemoval m_eremoval; /// mapping from string to type id FAChain2Num_judy m_type2id; /// temporary states/chain container FAArray_cont_t < int > m_arr; }; } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FAEncoder_mask.h
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_ENCODER_MASK_H_ #define _FA_ENCODER_MASK_H_ #include "FAConfig.h" #include "FAEncoderA.h" namespace BlingFire { /// Does the following: /// 1. Recodes zero-bytes with two non-zero byte sequences class FAEncoder_mask : public FAEncoderA { public: const int GetMaxBytes () const; const int Encode (const int * pChain, const int Size, unsigned char * pOutBuffer) const; private: enum { MAX_BYTES_PER_INT = sizeof (int) * 2 }; }; } #endif
palerdot/BlingFire
blingfireclient.library/inc/FASuffixInterpretToolsConst_t.h
<reponame>palerdot/BlingFire<filename>blingfireclient.library/inc/FASuffixInterpretToolsConst_t.h /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_SUFFIXINTERPRETTOOLSCONST_T_H_ #define _FA_SUFFIXINTERPRETTOOLSCONST_T_H_ #include "FAConfig.h" #include "FARSDfaCA.h" #include "FAState2OwsCA.h" #include "FAMultiMapCA.h" #include "FATransformCA_t.h" #include "FAUtf8Utils.h" #include "FAWftConfKeeper.h" #include "FASecurity.h" #include "FAArray_cont_t.h" namespace BlingFire { /// /// Suffix rules interpreter. Converts Word, Word/Tag or Word/TagFrom/TagTo /// to whatever rules for. See FASuffixRules2Chains.h for syntax description. /// /// Notes: /// /// 1. All Process methods return 0-separated word list. If the output /// buffer is not large enough then it just returns the minimum required size. /// 2. Input transformation, if supplied, makes output to a temporary buffer. /// Output transformation, if supplied, makes transformation in-place. /// template < class Ty > class FASuffixInterpretToolsConst_t { public: FASuffixInterpretToolsConst_t (); ~FASuffixInterpretToolsConst_t (); public: /// sets up the configuration void SetConf (const FAWftConfKeeper * pConf, FAAllocatorA * pMemMgr); /// sets up input transformation, can be NULL void SetInTr (const FATransformCA_t < Ty > * pInTr); /// sets up output transformation, can be NULL void SetOutTr (const FATransformCA_t < Ty > * pOutTr); /// returns output string for tagless rules /// returns -1 if no transformation exist const int Process ( const Ty * pIn, const int InSize, __out_ecount_opt(MaxOutSize) Ty * pOut, const int MaxOutSize ) const; /// returns output string for one-tags transformation rules /// returns -1 if no transformation exist const int Process ( const Ty * pIn, const int InSize, const int Tag, __out_ecount_opt(MaxOutSize) Ty * pOut, const int MaxOutSize ) const; /// returns output string for two-tags transformation rules /// returns -1 if no transformation exist const int Process ( const Ty * pIn, const int InSize, const int FromTag, const int ToTag, __out_ecount_opt(MaxOutSize) Ty * pOut, const int MaxOutSize ) const; private: struct Scratch { /// input sequence const Ty * m_pIn; int m_InSize; /// temporary buffer keeps rule to apply in case of implicit representation int * m_pActBuff; /// action to be applied const int * m_pAct; int m_ActLen; /// rule ids to be applied int * m_pOutOws; int m_OwCount; /// a memlfp action buffer FAArray_cont_t < int > m_act; /// a memlfp ows buffer FAArray_cont_t < int > m_ows; }; private: /// initializes a new Scratch object inline void InitializeScratch (Scratch * pTmp) const; /// if necessary normalizes the input, when input is copied into /// a temporary buffer, all normalizations are done in-place inline void Normalize ( Scratch * pTmp, __out_ecount(MaxOutSize) Ty * pOut, const int MaxOutSize ) const; // returns the deepest final state starting from StartState inline const int GetLastFinal (const Scratch * pTmp, const int StartState) const; // initializes m_pAct and m_ActLen inline void GetAction (Scratch * pTmp, const int ActNum) const; // fills in output buffer, returns output size inline const int BuildResults ( Scratch * pTmp, const int LastFinal, __out_ecount_opt(MaxOutSize) Ty * pOut, const int MaxOutSize ) const; // returns the output size inline const int ApplyAction ( const Scratch * pTmp, __out_ecount_opt(MaxOutSize) Ty * pOut, const int MaxOutSize ) const; private: /// input objects const FARSDfaCA * m_pDfa; const FAState2OwsCA * m_pState2Ows; const FAMultiMapCA * m_pActs; const FATransformCA_t < Ty > * m_pInTr; const FATransformCA_t < Ty > * m_pOutTr; /// configuration related variables int m_InitialState; bool m_IgnoreCase; int m_MaxActBuffSize; int m_MaxOwCount; bool m_DictMode; /// charmap const FAMultiMapCA * m_pCharMap; /// memory manager FAAllocatorA * m_pMemMgr; enum { DefDelimIw = 0, DefTmpBuffSize = 1024, }; }; template < class Ty > FASuffixInterpretToolsConst_t< Ty >:: FASuffixInterpretToolsConst_t () : m_pDfa (NULL), m_pState2Ows (NULL), m_pActs (NULL), m_pInTr (NULL), m_pOutTr (NULL), m_InitialState (-1), m_IgnoreCase (false), m_MaxActBuffSize (0), m_MaxOwCount (0), m_DictMode (false), m_pCharMap (NULL), m_pMemMgr (NULL) { } template < class Ty > FASuffixInterpretToolsConst_t< Ty >::~FASuffixInterpretToolsConst_t () { } template < class Ty > void FASuffixInterpretToolsConst_t< Ty >:: SetConf (const FAWftConfKeeper * pConf, FAAllocatorA * pMemMgr) { LogAssert (pConf && pMemMgr); m_pMemMgr = pMemMgr; m_pDfa = NULL; m_pState2Ows = NULL; m_pActs = NULL; m_InitialState = -1; m_IgnoreCase = false; m_DictMode = false; m_pCharMap = NULL; m_pDfa = pConf->GetRsDfa (); m_pState2Ows = pConf->GetState2Ows (); m_pActs = pConf->GetActs (); // can't be NULL LogAssert (m_pDfa && m_pState2Ows && m_pActs); m_pCharMap = pConf->GetCharMap (); m_DictMode = pConf->GetDictMode (); m_IgnoreCase = pConf->GetIgnoreCase (); const bool UseNfst = pConf->GetUseNfst (); // can't be set here LogAssert (!UseNfst); // get the initial state m_InitialState = m_pDfa->GetInitial (); LogAssert (-1 != m_InitialState); // get the maximum possible amount of Ows m_MaxOwCount = m_pState2Ows->GetMaxOwsCount (); LogAssert (0 < m_MaxOwCount); // get maximum possible action size m_MaxActBuffSize = m_pActs->GetMaxCount (); LogAssert (0 < m_MaxActBuffSize); } template < class Ty > void FASuffixInterpretToolsConst_t< Ty >:: SetInTr (const FATransformCA_t < Ty > * pInTr) { m_pInTr = pInTr; } template < class Ty > void FASuffixInterpretToolsConst_t< Ty >:: SetOutTr (const FATransformCA_t < Ty > * pOutTr) { m_pOutTr = pOutTr; } template < class Ty > inline void FASuffixInterpretToolsConst_t< Ty >:: InitializeScratch (Scratch * pTmp) const { DebugLogAssert (pTmp); DebugLogAssert (0 < m_MaxOwCount); DebugLogAssert (0 < m_MaxActBuffSize); pTmp->m_ows.SetAllocator (m_pMemMgr); pTmp->m_ows.Clear (); pTmp->m_ows.resize (m_MaxOwCount); pTmp->m_pOutOws = pTmp->m_ows.begin (); LogAssert (pTmp->m_pOutOws); pTmp->m_act.SetAllocator (m_pMemMgr); pTmp->m_act.Clear (); pTmp->m_act.resize (m_MaxActBuffSize); pTmp->m_pActBuff = pTmp->m_act.begin (); LogAssert (pTmp->m_pActBuff); } template < class Ty > inline const int FASuffixInterpretToolsConst_t< Ty >:: GetLastFinal (const Scratch * pTmp, const int StartState) const { const Ty * pIn = pTmp->m_pIn; const int InSize = pTmp->m_InSize; DebugLogAssert (0 < InSize && pIn); int LastFinal = -1; int State = StartState; if (false == m_DictMode) { /// find the longest match for (int Pos = InSize - 1; Pos >= 0; --Pos) { const int Iw = (unsigned int) (pIn [Pos]); State = m_pDfa->GetDest (State, Iw); if (-1 == State) { break; } if (m_pDfa->IsFinal (State)) { LastFinal = State; } } /// try to make one more step by a delimiter if (-1 != State) { State = m_pDfa->GetDest (State, DefDelimIw); if (-1 != State && m_pDfa->IsFinal (State)) { LastFinal = State; } } } else { /// match the whole input for (int Pos = InSize - 1; Pos >= 0; --Pos) { const int Iw = (unsigned int) (pIn [Pos]); State = m_pDfa->GetDest (State, Iw); if (-1 == State) { break; } } if (-1 != State && m_pDfa->IsFinal (State)) { LastFinal = State; } } // of if (false == m_DictMode) ... return LastFinal; } template < class Ty > inline void FASuffixInterpretToolsConst_t< Ty >:: GetAction (Scratch * pTmp, const int ActNum) const { DebugLogAssert (m_pActs); // see whether there are some explicitly stored data pTmp->m_ActLen = m_pActs->Get (ActNum, &pTmp->m_pAct); // get implicitly stored data if (-1 == pTmp->m_ActLen) { pTmp->m_ActLen = m_pActs->Get (ActNum, pTmp->m_pActBuff, m_MaxActBuffSize); DebugLogAssert (-1 != pTmp->m_ActLen && pTmp->m_ActLen <= m_MaxActBuffSize); pTmp->m_pAct = pTmp->m_pActBuff; } } template < class Ty > inline const int FASuffixInterpretToolsConst_t< Ty >:: ApplyAction ( const Scratch * pTmp, __out_ecount_opt(MaxOutSize) Ty * pOut, const int MaxOutSize ) const { DebugLogAssert (pTmp); // get the action to be applied const int * pAct = pTmp->m_pAct; const int ActLen = pTmp->m_ActLen; DebugLogAssert (0 < ActLen && pAct); // get the input const Ty * pIn = pTmp->m_pIn; const int InSize = pTmp->m_InSize; DebugLogAssert (0 < InSize && pIn); int i, PrefLen, SuffLen, PrefCut, SuffCut; const int * pPref; const int * pSuff; /// decode the action if (FALimits::MaxWordSize >= *pAct) { // no prefix data pPref = NULL; PrefLen = 0; PrefCut = 0; // get suffix data pSuff = pAct + 1; SuffCut = *pAct; SuffLen = ActLen - 1; } else { // get skip value const int Skip = *pAct - FALimits::MaxWordSize; DebugLogAssert (1 < Skip && Skip <= FALimits::MaxWordSize); // get prefix data pPref = pAct + 2; PrefCut = pAct [1]; PrefLen = Skip - 2; // get suffix data pSuff = pAct + Skip + 1; SuffCut = pAct [Skip]; SuffLen = ActLen - Skip - 1; } DebugLogAssert (0 <= PrefLen && PrefLen <= FALimits::MaxWordSize); DebugLogAssert (0 <= SuffLen && SuffLen <= FALimits::MaxWordSize); DebugLogAssert (0 <= PrefCut && PrefCut <= FALimits::MaxWordSize); DebugLogAssert (0 <= SuffCut && SuffCut <= FALimits::MaxWordSize); /// calc the common length const int CommonLen = InSize - SuffCut - PrefCut; if (0 > CommonLen || 0 > SuffLen || 0 > PrefLen || \ (0 == CommonLen && 0 == SuffLen && 0 == PrefLen)) { return 0; } /// calc the output size + terminating 0 int OutSize = CommonLen + SuffLen + PrefLen + 1; if (OutSize > MaxOutSize) { return OutSize; } DebugLogAssert (pOut); Ty * pCurrOut = pOut; /// add a new prefix, if needed for (i = 0; i < PrefLen; ++i) { pCurrOut [i] = (Ty) pPref [i]; } pCurrOut += PrefLen; /// copy a common part as-is if (0 < CommonLen) { memcpy (pCurrOut, pIn + PrefCut, CommonLen * sizeof (Ty)); pCurrOut += CommonLen; } /// add a new suffix, if needed for (i = 0; i < SuffLen; ++i) { pCurrOut [i] = (Ty) pSuff [i]; } pCurrOut += SuffLen; /// apply out-transformation in-place if (m_pOutTr) { // uses MaxOutSize - 1 as we'll need the last position for 0 const int NewLen = \ m_pOutTr->Process (pOut, OutSize - 1, pOut, MaxOutSize - 1); if (-1 != NewLen && NewLen < MaxOutSize) { OutSize = NewLen + 1; pCurrOut = pOut + NewLen; } } /// add terminating zero, generated word cannot be empty here *pCurrOut = 0; return OutSize; } template < class Ty > inline const int FASuffixInterpretToolsConst_t< Ty >:: BuildResults ( Scratch * pTmp, const int LastFinal, __out_ecount_opt(MaxOutSize) Ty * pOut, const int MaxOutSize ) const { DebugLogAssert (-1 != LastFinal); pTmp->m_OwCount = m_pState2Ows->GetOws (LastFinal, pTmp->m_pOutOws, m_MaxOwCount); DebugLogAssert (pTmp->m_OwCount <= m_MaxOwCount); if (0 < pTmp->m_OwCount) { int OutSize = 0; for (int i = 0; i < pTmp->m_OwCount; ++i) { const int ActNum = pTmp->m_pOutOws [i]; Ty * pCurrOut = pOut + OutSize; const int CurrMaxSize = MaxOutSize - OutSize; GetAction (pTmp, ActNum); OutSize += ApplyAction (pTmp, pCurrOut, CurrMaxSize); } // of for (int i = 0; ... return OutSize; } // of if (0 < pTmp->m_OwCount) ... return -1; } template < class Ty > inline void FASuffixInterpretToolsConst_t< Ty >:: Normalize (Scratch * pTmp, __out_ecount(MaxOutSize) Ty * pOut, const int MaxOutSize) const { DebugLogAssert (pTmp->m_pIn && 0 < pTmp->m_InSize && pTmp->m_InSize <= FALimits::MaxWordLen); __analysis_assume (pTmp->m_pIn && 0 < pTmp->m_InSize && pTmp->m_InSize <= FALimits::MaxWordLen); DebugLogAssert (pOut && 0 < MaxOutSize); __analysis_assume (pOut && 0 < MaxOutSize); DebugLogAssert (MaxOutSize >= pTmp->m_InSize); __analysis_assume (MaxOutSize >= pTmp->m_InSize); // normalize the case, if needed if (m_IgnoreCase) { for (int i = 0 ; i < pTmp->m_InSize; ++i) { const int InSymbol = (int) pTmp->m_pIn [i] ; const int OutSymbol = FAUtf32ToLower (InSymbol) ; pOut [i] = (Ty) OutSymbol ; } pTmp->m_pIn = pOut; } // normalize characters if (m_pCharMap) { // in-place is fine pTmp->m_InSize = FANormalizeWord (pTmp->m_pIn, pTmp->m_InSize, \ pOut, MaxOutSize, m_pCharMap); pTmp->m_pIn = pOut; } // apply the transformation, if needed if (m_pInTr) { // in-place is fine const int OutSize = \ m_pInTr->Process (pTmp->m_pIn, pTmp->m_InSize, pOut, MaxOutSize); // see whether there was some transformation made if (0 < OutSize && OutSize <= MaxOutSize) { pTmp->m_pIn = pOut; pTmp->m_InSize = OutSize; } } } template < class Ty > const int FASuffixInterpretToolsConst_t< Ty >:: Process (const Ty * pIn, const int InSize, __out_ecount_opt(MaxOutSize) Ty * pOut, const int MaxOutSize) const { const int TmpBuffSize = 2 * FALimits::MaxWordLen; Ty TmpBuff [TmpBuffSize]; Scratch tmp; InitializeScratch (&tmp); tmp.m_pIn = pIn; tmp.m_InSize = InSize; DebugLogAssert (m_pDfa && m_pState2Ows && m_pActs && -1 != m_InitialState); __analysis_assume (m_pDfa && m_pState2Ows && m_pActs && -1 != m_InitialState); DebugLogAssert (pIn && 0 < InSize && InSize <= FALimits::MaxWordLen); __analysis_assume (pIn && 0 < InSize && InSize <= FALimits::MaxWordLen); Normalize (&tmp, TmpBuff, TmpBuffSize); const int LastFinal = GetLastFinal (&tmp, m_InitialState); if (-1 != LastFinal) { const int OutSize = BuildResults (&tmp, LastFinal, pOut, MaxOutSize); return OutSize; } return -1; } template < class Ty > const int FASuffixInterpretToolsConst_t< Ty >:: Process (const Ty * pIn, const int InSize, const int Tag, __out_ecount_opt(MaxOutSize) Ty * pOut, const int MaxOutSize) const { const int TmpBuffSize = 2 * FALimits::MaxWordLen; Ty TmpBuff [TmpBuffSize]; Scratch tmp; InitializeScratch (&tmp); tmp.m_pIn = pIn; tmp.m_InSize = InSize; DebugLogAssert (m_pDfa && m_pState2Ows && m_pActs && -1 != m_InitialState); __analysis_assume (m_pDfa && m_pState2Ows && m_pActs && -1 != m_InitialState); DebugLogAssert (pIn && 0 < InSize && InSize <= FALimits::MaxWordLen); __analysis_assume (pIn && 0 < InSize && InSize <= FALimits::MaxWordLen); Normalize (&tmp, TmpBuff, TmpBuffSize); // process Tag int State = m_pDfa->GetDest (m_InitialState, Tag); if (-1 == State) { return -1; } // calc the last final state int LastFinal = GetLastFinal (&tmp, State); if (-1 == LastFinal && m_pDfa->IsFinal (State)) { LastFinal = State; } // get actions and apply them if (-1 != LastFinal) { const int OutSize = BuildResults (&tmp, LastFinal, pOut, MaxOutSize); return OutSize; } return -1; } template < class Ty > const int FASuffixInterpretToolsConst_t< Ty >:: Process (const Ty * pIn, const int InSize, const int FromTag, const int ToTag, __out_ecount_opt(MaxOutSize) Ty * pOut, const int MaxOutSize) const { const int TmpBuffSize = 2 * FALimits::MaxWordLen; Ty TmpBuff [TmpBuffSize]; Scratch tmp; InitializeScratch (&tmp); tmp.m_pIn = pIn; tmp.m_InSize = InSize; DebugLogAssert (m_pDfa && m_pState2Ows && m_pActs && -1 != m_InitialState); __analysis_assume (m_pDfa && m_pState2Ows && m_pActs && -1 != m_InitialState); DebugLogAssert (pIn && 0 < InSize && InSize <= FALimits::MaxWordLen); __analysis_assume (pIn && 0 < InSize && InSize <= FALimits::MaxWordLen); Normalize (&tmp, TmpBuff, TmpBuffSize); int LastFinal = -1; // process FromTag int State = m_pDfa->GetDest (m_InitialState, FromTag); if (-1 == State) { return -1; } if (m_pDfa->IsFinal (State)) { LastFinal = State; } // process ToTag State = m_pDfa->GetDest (State, ToTag); if (-1 != State) { const int NewLastFinal = GetLastFinal (&tmp, State); if (-1 != NewLastFinal) { LastFinal = NewLastFinal; } else if (m_pDfa->IsFinal (State)) { LastFinal = State; } } // get actions and apply them if (-1 != LastFinal) { const int OutSize = BuildResults (&tmp, LastFinal, pOut, MaxOutSize); return OutSize; } return -1; } } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FARegexpLexer_wre.h
<filename>blingfirecompile.library/inc/FARegexpLexer_wre.h /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_REGEXPLEXER_WRE_H_ #define _FA_REGEXPLEXER_WRE_H_ #include "FAConfig.h" #include "FARegexpLexer_triv.h" namespace BlingFire { /// /// The lexer assumes that the input is the combination of the following: /// /// <token> ::= <word-list>[/<regexp-list>][/<dict-list>][/<pos-list>] /// <token> ::= [<word-list>/]<regexp-list>[/<dict-list>][/<pos-list>] /// <token> ::= [<word-list>/][<regexp-list>/]<dict-list>[/<pos-list>] /// <token> ::= [<word-list>/][<regexp-list>/][<dict-list>/]<pos-list> /// /// <word-list> ::= <word-or-list> /// <word-list> ::= <word-not-list> /// <word-or-list> ::= "text" /// <word-or-list> ::= "text"|<word-or-list> /// <word-not-list> ::= !"text" /// <word-not-list> ::= !"text"<word-not-list> /// /// <tag-list> ::= <tag-or-list> /// <tag-list> ::= <tag-not-list> /// <tag-or-list> ::= TAG /// <tag-or-list> ::= TAG|<tag-or-list> /// <tag-not-list> ::= !TAG /// <tag-not-list> ::= !TAG<tag-not-list> /// /// TAG ::= /[A-Za-z][A-Za-z0-9_]*/ /// /// <regexp-list> ::= <regexp-or-list> /// <regexp-list> ::= <regexp-and-list> /// <regexp-or-list> ::= [!]'regexp' /// <regexp-or-list> ::= [!]'regexp'|<regexp-or-list> /// <regexp-and-list> ::= [!]'regexp' /// <regexp-and-list> ::= [!]'regexp'<regexp-and-list> /// /// <dict-list> ::= <dict-or-list> /// <dict-list> ::= <dict-and-list> /// <dict-or-list> ::= @[!]<dictname>|<dict-or-list> /// <dict-and-list> ::= @[!]<dictname><dict-and-list> /// /// <dictname> ::= /[A-Za-z][A-Za-z0-9_]*/ /// /// Notes: /// 1. No empty tokens allowed /// 2. The spaces in tokens are only allowed withing quotations /// class FARegexpLexer_wre : public FARegexpLexer_triv { public: FARegexpLexer_wre (); private: /// overriden const int FindToken (const int Pos, int * pLength) const; /// returns true is any of ' ', '\t', '\n', '\r' is encountered at Pos inline const bool IsSpace (const int Pos) const; /// returns true if symbol at Pos can be a part of WRE token inline const bool IsToken (const int Pos) const; /// returns true if symbol at Pos can be a start of WRE token inline const bool IsTokenStart (const int Pos) const; private: enum { InfoMaskSpace = 1, InfoMaskToken = 2, InfoMaskTokenStart = 4, }; /// mapping from character into unsigned int m_char2info [AsciiSize]; }; } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FATokenNfa2TupleNfa.h
<filename>blingfirecompile.library/inc/FATokenNfa2TupleNfa.h /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_TOKENNFA2TUPLENFA_H_ #define _FA_TOKENNFA2TUPLENFA_H_ #include "FAConfig.h" #include "FAAny2AnyOther_global_t.h" #include "FATokenNfa2Nfa_t.h" #include "FANfas2TupleNfa.h" #include "FAIsDotNfa.h" #include "FAArray_cont_t.h" #include "FARSNfa_ro.h" #include "FARSNfa_wo_ro.h" namespace BlingFire { class FAAllocatorA; class FAMultiMapA; class FATagSet; /// /// This class builds Tuple Ows NFA from the Token Nfa and Token -> Ows maps. /// class FATokenNfa2TupleNfa { public: FATokenNfa2TupleNfa (FAAllocatorA * pAlloc); ~FATokenNfa2TupleNfa (); public: /// token NFA void SetTokenNfa (const FARSNfaA * pTokenNfa); /// output Tuple NFA void SetOutNfa (FARSNfaA * pOutNfa); /// tagset, optional void SetTagSet (const FATagSet * pTagSet); /// Dgt,Token --> TypeNum CNF void SetCNF (const FAMultiMapA * pToken2CNF); /// Dgt,TypeNum --> { Ows } map void SetType2Ows (const FAMultiMapA * pType2Ows); /// base token Iw void SetTnBaseIw (const int TnBaseIw); /// base of interval which should not be grouped into tuples, optional void SetIgnoreBase (const int IgnoreBase); /// max of interval which should not be grouped into tuples, optional void SetIgnoreMax (const int IgnoreMax); void Process (); const int GetTokenType () const; private: void Prepare (); void Clear (); const bool IsDotNfa (const FARSNfaA * pNfa, const int Digitizer); private: const FATagSet * m_pTagSet; int m_TnBaseIw; const FAMultiMapA * m_pToken2CNF; const FAMultiMapA * m_pType2Ows; int m_TokenType; FARSNfaA * m_pOutNfa; // '.' - expansion FAAny2AnyOther_global_t < FARSNfaA, FARSNfa_wo_ro > m_dot_exp; /// builds one NFA for each digitizer type FATokenNfa2Nfa_t < FARSNfaA > m_tnnfa2nfa; /// merges n-NFAs into a single one FANfas2TupleNfa m_nfas2nfa; /// identifies "."-NFAs FAIsDotNfa m_is_dot; /// temporary "."-alphabet storage FAArray_cont_t < int > m_ows; /// temporary "."-expanded token NFA FARSNfa_wo_ro m_ExpNfa; /// singleton NFAs FARSNfa_ro m_TxtNfa; FARSNfa_ro m_TagNfa; FARSNfa_ro m_DctNfa; }; } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FAChain2Num_hash.h
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_CHAIN2NUM_HASH_H_ #define _FA_CHAIN2NUM_HASH_H_ #include "FAConfig.h" #include "FAChain2NumA.h" #include "FAMap_judy.h" #include "FAArray_t.h" #include "FAArray_cont_t.h" #include "FAHeap_t.h" namespace BlingFire { class FAAllocatorA; class FAChain2Num_hash : public FAChain2NumA { public: FAChain2Num_hash (); virtual ~FAChain2Num_hash (); public: /// see FAChain2NumA interface description for details void SetEncoder (const FAEncoderA * pEncoder); void SetCopyChains (const bool CopyChains); const int * Get (const int * pChain, const int Size) const; const int Add (const int * pChain, const int Size, const int Value); const int GetChainCount () const; const int GetChain (const int Idx, const int ** ppChain) const; const int GetValue (const int Idx) const; /// returns pair's index by the Chain, or -1 if does not exist const int GetIdx (const int * pChain, const int Size) const; /// sets up allocator void SetAllocator (FAAllocatorA * pAlloc); // removes Chain -> Value pair from the map void Remove (const int * pChain, const int Size); /// returns the map in the state as it was just constructed void Clear (); private: // generates hash-key for a given chain inline static const int Chain2Key (const int * pChain, const int Size); // identifies whether chains are equal inline static const bool Equal ( const int * pChain1, const int * pChain2, const int Size ); // finds index by the given chains or returns -1 inline const int Chain2Idx (const int * pChain, const int Size) const; // associates < chain, value > pair with a new idx, returns new idx inline const int AddNewChain ( const int * pChain, const int Size, const int Value ); // adds new collition set with two initial values inline const int AddNewCSet (const int i1, const int i2); private: // Hash key to index mapping: // if idx > 0 then // i = idx - 1; // else if idx < 0 then // j = (-idx) - 1; // else // DebugLogAssert (0); FAMap_judy m_key2idx; // Storage of collision sets: // j --> { i_0, i_2, ... , i_n } FAArray_t < FAArray_cont_t < int > > m_csets; // Two parallel arrays (chains and coresponding values): // i --> chain, array of the following format: [ N, a_1, a_2, ..., a_N ] FAArray_t < int * > m_i2chain; // i --> value FAArray_t < int > m_i2value; // tracks empty deleted i-s due to deleted chains FAHeap_t < int > m_i_gaps; // tracks empty deleted j-s due to deleted collision sets FAHeap_t < int > m_j_gaps; // allocator FAAllocatorA * m_pAlloc; }; } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FACalcMealy1.h
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_CALCMEALY1_H_ #define _FA_CALCMEALY1_H_ #include "FAConfig.h" #include "FARSNfa_wo_ro.h" #include "FARSDfa_wo_ro.h" #include "FAMealyDfa.h" #include "FANfa2Dfa_t.h" #include "FAArray_cont_t.h" #include "FAMultiMap_judy.h" namespace BlingFire { class FAAllocatorA; class FARSNfaA; /// /// This class is a helper for the FAMealyNfa2Dfa converter, it builds /// the first component of the decomposition. Don't use this class directly. /// class FACalcMealy1 { public: FACalcMealy1 (FAAllocatorA * pAlloc); public: /// sets up input RS NFA void SetInNfa (const FARSNfaA * pInNfa); /// sets up state -> color map void SetColorMap (const int * pS2C, const int Size); /// makes conversion void Process (); /// returns object into the initial state void Clear (); /// returns output automaton const FARSDfaA * GetDfa () const; const FAMealyDfaA * GetSigma () const; private: void Prepare (); inline const int Remap ( const int * pStates, const int Count, const int ** ppStates ); void RemapNfa (); private: // input RS NFA const FARSNfaA * m_pInNfa; // color map const int * m_pS2C; int m_MapSize; int m_MaxColor; // reverse mapping C -> {S} FAMultiMap_judy m_c2s; // input (remapped) automaton FARSNfa_wo_ro m_in_nfa; // output Mealy DFA FARSDfa_wo_ro m_OutDfa; FAMealyDfa m_OutSigma; // determinization algorithm FANfa2Dfa_t < FARSNfa_wo_ro, FARSDfa_wo_ro > m_nfa2dfa; // temporary arrays for remapping destination states FAArray_cont_t < int > m_tmp; FAArray_cont_t < int > m_tmp2; FAArray_cont_t < int > m_alphabet; }; } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FAEncoder_pm_dpm.h
<filename>blingfirecompile.library/inc/FAEncoder_pm_dpm.h /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_ENCODER_PM_DPM_H_ #define _FA_ENCODER_PM_DPM_H_ #include "FAConfig.h" #include "FAEncoderA.h" namespace BlingFire { /// Does the following: /// 1. Makes prefix-mask encoding for the first element of chain /// 2. Makes delta-prefix-mask for all the other elements /// /// Note: /// This encoder suits well for non-descending sequences of ints, with /// the first special element - the size of the sequence, e.g. [5 1 2 3 3 3]. /// class FAEncoder_pm_dpm : public FAEncoderA { public: const int GetMaxBytes () const; const int Encode (const int * pChain, const int Size, unsigned char * pOutBuffer) const; private: enum { MAX_BYTES_PER_INT = 9 }; }; } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FAStr2IntA.h
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_STR2INTA_H_ #define _FA_STR2INTA_H_ #include "FAConfig.h" namespace BlingFire { class FAStr2IntA { public: /// finds value by the string virtual const bool Get (const char * pStr, const int Size, int * pValue) const = 0; /// returns the total number of pairs stored in map virtual const int GetStrCount () const = 0; /// returns String by its idx /// idx \in [0, GetChainCount ()) /// return value is the size of the Chain virtual const int GetStr (const int Idx, const char ** ppStr) const = 0; /// returns value by its idx virtual const int GetValue (const int Idx) const = 0; /// adds String -> Value pair, returns index virtual const int Add (const char * pStr, const int Size, const int Value) = 0; }; } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FAHeap_t.h
<reponame>palerdot/BlingFire<filename>blingfirecompile.library/inc/FAHeap_t.h<gh_stars>1000+ /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_HEAP_T_H_ #define _FA_HEAP_T_H_ #include "FAConfig.h" #include "FAArray_cont_t.h" namespace BlingFire { class FAAllocatorA; template < class Ty > class FAHeap_t { public: void Create (FAAllocatorA * pAlloc); public: /// returns the number of elementes in the heap inline const int size () const; /// makes the heap empty inline void clear (); /// returns true if the heap is empty inline const bool empty () const; /// returns the smallest element inline const Ty * top () const; /// removes the smallest element inline void pop (); /// adds in an element inline void push (const Ty& e); private: inline const Ty * at (const int i) const; inline void swap (const int idx1, const int idx2); inline void heapify_down (int i); inline void heapify_up (int i); private: FAArray_cont_t < Ty > m_array; }; template < class Ty > void FAHeap_t< Ty >::Create (FAAllocatorA * pAlloc) { m_array.SetAllocator (pAlloc); m_array.Create (); // there must always be a first dummy element m_array.push_back (0); } template < class Ty > const Ty * FAHeap_t< Ty >::at (const int i) const { if (1 > i || m_array.size () <= (unsigned int) i) return NULL; return & m_array [i]; } template < class Ty > void FAHeap_t< Ty >::swap (const int idx1, const int idx2) { DebugLogAssert (1 <= idx1 && m_array.size () > (unsigned int)idx1); DebugLogAssert (1 <= idx2 && m_array.size () > (unsigned int)idx2); const Ty E = m_array [idx1]; m_array [idx1] = m_array [idx2]; m_array [idx2] = E; } template < class Ty > void FAHeap_t< Ty >::heapify_down (int i) { while (true) { const int i_2 = i << 1; const Ty * e = at (i); const Ty * left = at (i_2); const Ty * right = at (i_2 + 1); if (NULL == left && NULL == right) break; if (NULL != left) { if (NULL != right) { if (*e < *left && *e < *right) break; if (*right < *left) { swap (i, i_2 + 1); i = i_2 + 1; } else { swap (i, i_2); i = i_2; } } else { if (*e < *left) break; swap (i, i_2); i = i_2; } } } // of while } template < class Ty > void FAHeap_t< Ty >::heapify_up (int i) { while (true) { if (1 == i) break; const int i_2 = i >> 1; const Ty * e = at (i); const Ty * parent = at (i_2); if (*e > *parent) break; swap (i, i_2); i = i_2; } // of while } template < class Ty > const int FAHeap_t< Ty >::size () const { return m_array.size () - 1; } template < class Ty > void FAHeap_t< Ty >::clear () { if(1 < m_array.size()) { m_array.resize (1); } } template < class Ty > const bool FAHeap_t< Ty >::empty () const { return 1 == m_array.size (); } template < class Ty > const Ty * FAHeap_t< Ty >::top () const { DebugLogAssert (1 < m_array.size ()); return & m_array [1]; } template < class Ty > void FAHeap_t< Ty >::pop () { DebugLogAssert (1 < m_array.size ()); // move the last element to the begining m_array [1] = m_array [m_array.size () - 1]; // delete the last element m_array.pop_back (); // heapify from the beginining heapify_down (1); } template < class Ty > void FAHeap_t< Ty >::push (const Ty& e) { const int new_idx = m_array.size (); // insert a new element into the end m_array.push_back (e); // heapify from the end heapify_up (new_idx); } } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FASortMultiMap.h
<gh_stars>1000+ /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_SORTMULTIMAP_H_ #define _FA_SORTMULTIMAP_H_ #include "FAConfig.h" #include "FAArray_cont_t.h" namespace BlingFire { class FAMultiMapA; class FAAllocatorA; /// /// Sorts multimap keys with respect to the lexicographic order of the /// associated arrays of values. /// class FASortMultiMap { public: FASortMultiMap (FAAllocatorA * pAlloc); public: /// sets up input multi-map void SetMultiMap (const FAMultiMapA * pMap); /// sets up direction, e.g. l2r, r2l in which to compare arrays of values void SetDirection (const int Direction); /// sorts the chains void Process (); /// returns ordered keys const int GetKeyOrder (const int ** ppKeys) const; private: // Key1 < Key2 if Chain[Key1] < Chain[Key2] lexicographically class _TKeyCmp_l2r { public: _TKeyCmp_l2r (const FAMultiMapA * pMap); public: const bool operator () (const int Key1, const int Key2) const; private: const FAMultiMapA * m_pMap; }; // Key1 < Key2 if Rev(Chain[Key1]) < Rev(Chain[Key2]) lexicographically, // where Rev([a1, a2, ... an]) == [an, ..., a2, a1] class _TKeyCmp_r2l { public: _TKeyCmp_r2l (const FAMultiMapA * pMap); public: const bool operator () (const int Key1, const int Key2) const; private: const FAMultiMapA * m_pMap; }; private: const FAMultiMapA * m_pMap; FAArray_cont_t < int > m_keys; int m_Direction; }; } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FATestCmpDfa.h
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_TESTCMPDFA_H_ #define _FA_TESTCMPDFA_H_ #include "FAConfig.h" #include "FAArray_t.h" #include "FABitArray.h" #include "FAArray_cont_t.h" namespace BlingFire { class FAAllocatorA; class FARSDfaCA; class FAState2OwCA; class FAState2OwsCA; class FAMealyDfaCA; /// /// For the given two triplets: < FARSDfaCA, FAState2OwCA, FAState2OwsCA > /// identifies whether these triplets have the same behavior. /// /// Note: States can be renumerated in defeerent orders. /// class FATestCmpDfa { public: FATestCmpDfa (FAAllocatorA * pAlloc); public: // all pointer except pDfa1 can be NULL void SetFsm1 ( const FARSDfaCA * pDfa1, const FAState2OwCA * pState2Ow1, const FAState2OwsCA * pState2Ows1, const FAMealyDfaCA * pSigma1 ); // all pointer except pDfa2 can be NULL void SetFsm2 ( const FARSDfaCA * pDfa2, const FAState2OwCA * pState2Ow2, const FAState2OwsCA * pState2Ows2, const FAMealyDfaCA * pSigma2 ); // returns true if interfaces behave identically const bool Process (const int MaxState, const int MaxIw); private: // returns object into initial state void Clear (); // helper, returns true if state has already been procesed const bool WasSeen (const FABitArray * pVisited, const int State) const; // helper, marks state as been processed void SetSeen (FABitArray * pVisited, const int State); /// compares DFA's alphabets const bool CmpAlphabets (); private: const FARSDfaCA * m_pDfa1; const FARSDfaCA * m_pDfa2; const FAState2OwCA * m_pState2Ow1; const FAState2OwCA * m_pState2Ow2; const FAState2OwsCA * m_pState2Ows1; const FAState2OwsCA * m_pState2Ows2; const FAMealyDfaCA * m_pSigma1; const FAMealyDfaCA * m_pSigma2; // stack of pairs: <State1, State2>, State2 \in pDfa1, State2 \in pDfa2 FAArray_t < int > m_stack; // indicates whether State \in pDfa1 has already been processed FABitArray m_visited1; // indicates whether State \in pDfa2 has already been processed FABitArray m_visited2; // temporary storage for Ows1 FAArray_cont_t < int > m_ows1; int * m_pOws1; int m_MaxOws1Count; // temporary storage for Ows2 FAArray_cont_t < int > m_ows2; int * m_pOws2; int m_MaxOws2Count; // alphabet storage FAArray_cont_t < int > m_iws1; FAArray_cont_t < int > m_iws2; }; } #endif
palerdot/BlingFire
blingfireclient.library/inc/FATransform_prefix_t.h
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_TRANSFORM_PREFIX_T_H_ #define _FA_TRANSFORM_PREFIX_T_H_ #include "FAConfig.h" #include "FATransformCA_t.h" #include "FARSDfaCA.h" #include "FASecurity.h" namespace BlingFire { /// /// Moves recognized prefix to the end of word delimited with m_Delim value. /// /// For example: if m_Delim == '_' then "prefrest" -> "rest_pref" /// /// Notes: /// 1. Transformation can be made in-place. /// 2. If transformation is made in-place it needs word+pref memory, /// even if the output result is always word+1 length. /// 3. m_Delim value should not interfere with word's alphabet /// template < class Ty > class FATransform_prefix_t : public FATransformCA_t < Ty > { public: FATransform_prefix_t (); public: /// sets up prefix delimiter value void SetDelim (const Ty Delim); /// sets up an RS automaton of prefixes void SetRsDfa (const FARSDfaCA * pPrefDfa); /// makes transformation /// Note: this function has to be *within* the class definition, because otherwise compiler makes an error /// and generates some warnings about "unreferenced local function has been removed". const int Process ( const Ty * pIn, const int InCount, __out_ecount(MaxOutSize) Ty * pOut, const int MaxOutSize ) const { DebugLogAssert (m_pPrefDfa); // as __in_range(0, FALimits::MaxWordSize) const int InCount does not work __analysis_assume (0 < InCount && FALimits::MaxWordSize >= InCount && pIn); DebugLogAssert (0 < InCount && FALimits::MaxWordSize >= InCount && pIn); const int PrefLen = GetPrefLen (pIn, InCount); if (0 == PrefLen) return -1; // see FATransform_prefix_t< Ty >::GetPrefLen implementation __analysis_assume (0 < PrefLen && InCount >= PrefLen); DebugLogAssert (0 < PrefLen && InCount >= PrefLen); // copy if (pIn != pOut) { // see whether output buffer is large enough if (MaxOutSize >= InCount + 1) { int i; // copy root for (i = PrefLen; i < InCount; ++i) { *pOut++ = pIn [i]; } // set-up delimiter *pOut++ = m_Delim; // copy recognized prefix for (i = 0; i < PrefLen; ++i) { *pOut++ = pIn [i]; } } // in-place } else { // see whether output buffer is large enough if (MaxOutSize > InCount + PrefLen) { int i; // save prefix copy Ty * pPrefCopy = pOut + InCount; for (i = 0; i < PrefLen; ++i) { pPrefCopy [i] = pIn [i]; } // move the root left for (i = PrefLen; i < InCount; ++i) { *pOut++ = pIn [i]; } // set-up delimiter *pOut++ = m_Delim; // move recognized prefix left for (i = 0; i < PrefLen; ++i) { *pOut++ = pPrefCopy [i]; } } } return InCount + 1; } private: /// finds the longest known-prefix length /// returns 0, if no prefix was recognized inline const int GetPrefLen (const Ty * pIn, const int InCount) const; private: // delimiter Ty m_Delim; // keeps language of prefixes const FARSDfaCA * m_pPrefDfa; // constants enum { DefDelim = 3, }; }; template < class Ty > FATransform_prefix_t< Ty >::FATransform_prefix_t () : m_Delim (DefDelim), m_pPrefDfa (NULL) { } template < class Ty > void FATransform_prefix_t< Ty >::SetDelim (const Ty Delim) { m_Delim = Delim; } template < class Ty > void FATransform_prefix_t< Ty >::SetRsDfa (const FARSDfaCA * pPrefDfa) { m_pPrefDfa = pPrefDfa; } template < class Ty > inline const int FATransform_prefix_t< Ty >:: GetPrefLen (const Ty * pIn, const int InCount) const { DebugLogAssert (m_pPrefDfa); // as __in_range(0, FALimits::MaxWordSize) const int InCount does not work __analysis_assume (0 < InCount && FALimits::MaxWordSize >= InCount && pIn); DebugLogAssert (0 < InCount && FALimits::MaxWordSize >= InCount && pIn); int PrefLen = 0; int State = m_pPrefDfa->GetInitial (); // -1 because at least one symbol should be left for root for (int i = 0; i < InCount - 1; ++i) { DebugLogAssert (pIn); // convert input symbol into int const int Iw = pIn [i]; // get go to the following state State = m_pPrefDfa->GetDest (State, Iw); if (-1 == State) { return PrefLen; } if (m_pPrefDfa->IsFinal (State)) { PrefLen = i + 1; } } return PrefLen; } } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FANfaCreator_wre.h
<reponame>palerdot/BlingFire<filename>blingfirecompile.library/inc/FANfaCreator_wre.h /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_NFA_CREATOR_WRE_H_ #define _FA_NFA_CREATOR_WRE_H_ #include "FAConfig.h" #include "FANfaCreator_base.h" namespace BlingFire { class FAAllocatorA; class FAChain2NumA; class FANfaCreator_wre : public FANfaCreator_base { public: FANfaCreator_wre (FAAllocatorA * pAlloc); public: /// sets up the base for the output nfa's Iws void SetBaseIw (const int BaseIw); /// sets up token -> num mapping void SetToken2NumMap (FAChain2NumA * pToken2Num); /// adds a rtansition void SetTransition (const int FromState, const int ToState, const int LabelOffset, const int LabelLength); private: /// assigns a unique identifer to the token inline const int Token2Num (const char * pStr, const int Len); private: /// mapping from token string to its numerical identifer FAChain2NumA * m_pToken2Num; /// tmp chain storage FAArray_cont_t < int > m_arr; /// the base value for all token identifers int m_BaseIw; }; } #endif
palerdot/BlingFire
blingfireclient.library/inc/FASetImageA.h
<reponame>palerdot/BlingFire<filename>blingfireclient.library/inc/FASetImageA.h<gh_stars>1000+ /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_SETIMAGEA_H_ #define _FA_SETIMAGEA_H_ #include "FAConfig.h" namespace BlingFire { /// /// Image pointer set up interface for objects represented as memory dumps. /// class FASetImageA { public: virtual void SetImage (const unsigned char * pImage) = 0; }; } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FAMealyDfaA.h
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_MEALYDFA_A_H_ #define _FA_MEALYDFA_A_H_ #include "FAConfig.h" #include "FAMealyDfaCA.h" namespace BlingFire { /// /// FSM-compile-time interface for MealyDfa automaton reaction. /// class FAMealyDfaA : public FAMealyDfaCA { public: /// returns output weight for the given arc <Src, Iw> /// returns -1, if no Ow was associated virtual const int GetOw (const int Src, const int Iw) const = 0; /// sets up Ow for the given arc <Src, Iw> /// if -1 == Ow then it remove associated (if there was any) Ow virtual void SetOw (const int Src, const int Iw, const int Ow) = 0; /// have to be called after all transitions have been added virtual void Prepare () = 0; /// returns container into the state as if it was just constructed virtual void Clear () = 0; }; } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FAWRERules2TokenNfa.h
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_WRERULES2TOKENNFA_H_ #define _FA_WRERULES2TOKENNFA_H_ #include "FAConfig.h" #include "FAChain2Num_hash.h" #include "FANfaCreator_wre.h" #include "FARegexpSimplify.h" #include "FARegexp2Nfa.h" #include "FANfas2CommonENfa.h" namespace BlingFire { /// /// This class builds Token NFA from a list of WRE rules or a single rule. /// class FAWRERules2TokenNfa { public: FAWRERules2TokenNfa (FAAllocatorA * pAlloc); public: /// sets up WRE_TYPE, e.g. one of FAFsmConst::WRE_TYPE_* void SetType (const int Type); /// full or empty TokenText <--> TokenNum map container void SetToken2NumMap (FAChain2NumA * pTokens); /// add one or more (in case of WRE_TYPE_MOORE) rules void AddRule (const char * pWRE, const int Length); /// makes the output ready void Process (); /// returns object into the initial state, frees memory void Clear (); /// returns constructed token NFA const FARSNfaA * GetTokenNfa () const; private: /// WRE type int m_Type; /// simplifies the expression FARegexpSimplify m_simplify; /// builds NFA from the WRE rule FARegexp2Nfa m_rule2nfa; /// single rule NFA FANfaCreator_wre m_rule_nfa; /// NFA list --> ENFA FANfas2CommonENfa m_merge; }; } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FAMergeMwe.h
<gh_stars>1000+ /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_MERGEMWE_H_ #define _FA_MERGEMWE_H_ #include "FAConfig.h" namespace BlingFire { class FARSDfaCA; class FATaggedTextA; class FATaggedTextCA; /// /// This class merges MWE by the left-most-longest algorithm. /// class FAMergeMwe { public: FAMergeMwe (); public: /// sets up simple word delimiter, ' ' is used by default void SetMweDelim (const int MweDelim); /// MWE DFA void SetRsDfa (const FARSDfaCA * pDfa); /// ignores case void SetIgnoreCase (const bool IgnoreCase); /// makes processing void Process (FATaggedTextA * pOut, const FATaggedTextCA * pIn) const; private: /// returns how many tokens should be glued together starting from Pos inline const int GetTokenCount ( const int Pos, const FATaggedTextCA * pIn ) const; private: const FARSDfaCA * m_pDfa; int m_MweDelim; bool m_IgnoreCase; }; } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FARegexpLexerA.h
<reponame>palerdot/BlingFire<filename>blingfirecompile.library/inc/FARegexpLexerA.h<gh_stars>1000+ /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_REGEXPLEXERA_H_ #define _FA_REGEXPLEXERA_H_ #include "FAConfig.h" #include "FAArray_cont_t.h" #include "FAToken.h" namespace BlingFire { /// /// A common interface for regular-expression lexical analysers. /// class FARegexpLexerA { public: virtual void SetRegexp (const char * pReStr, const int Length) = 0; virtual void SetTokens (FAArray_cont_t < FAToken > * pTokens) = 0; virtual void Process () = 0; }; } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FATagSet.h
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_TAGSET_H_ #define _FA_TAGSET_H_ #include "FAConfig.h" #include "FAStr2Int_hash.h" #include "FAArray_cont_t.h" namespace BlingFire { class FAAllocatorA; /// /// Tagset container. /// class FATagSet : public FAStr2Int_hash { public: FATagSet (FAAllocatorA * pAlloc); public: // returns -1 if does not exist const int Tag2Str (const int Tag, const char ** ppStr) const; // returns -1 if does not exist const int Str2Tag (const char * pStr, const int Size) const; // overriden from FAStr2IntA const int Add (const char * pStr, const int Size, const int Tag); // Largest tag ID we've seen const int GetMaxTag () const; private: inline void ensure (const int Tag); private: // mapping from Tag to Str -> Value pair in FAStr2Int_hash FAArray_cont_t < int > m_tag2idx; int m_iMaxTag; }; } #endif
palerdot/BlingFire
blingfireclient.library/inc/FARSDfa_pack_triv.h
<reponame>palerdot/BlingFire<filename>blingfireclient.library/inc/FARSDfa_pack_triv.h /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_RSDFA_PACK_TRIV_H_ #define _FA_RSDFA_PACK_TRIV_H_ #include "FAConfig.h" #include "FASetImageA.h" #include "FARSDfaCA.h" #include "FAIwMap_pack.h" namespace BlingFire { /// /// This class is able to interpret automaton image stored by FADfaPack_triv /// class FARSDfa_pack_triv : public FASetImageA, public FARSDfaCA { public: FARSDfa_pack_triv (); public: void SetImage (const unsigned char * pAutImage); /// read interface public: const int GetMaxState () const; const int GetMaxIw () const; const int GetInitial () const; const int GetIWs ( __out_ecount_opt (MaxIwCount) int * pIws, const int MaxIwCount ) const; const bool IsFinal (const int State) const; const int GetDest (const int State, const int Iw) const; private: // interprets iw2iw map dump, if any FAIwMap_pack m_iw2iw; // pointer to the automaton image const unsigned char * m_pAutImage; // alphabet size int m_IwCount; // alphabet pointer const int * m_pIws; // initial state int m_InitialState; // indicates whether it is necessary to do input weights remapping bool m_RemapIws; // dst size int m_DstSize; }; } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FAResolveMatch_nest.h
<reponame>palerdot/BlingFire /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_RESOLVEMATCH_NEST_H_ #define _FA_RESOLVEMATCH_NEST_H_ #include "FAConfig.h" #include "FAResolveMatchA.h" #include "FAArray_cont_t.h" namespace BlingFire { class FAAllocatorA; /// /// 1. Removes overlappings (prefers lefttest match) /// 2. Removes inclusions of the same rule /// class FAResolveMatch_nest : public FAResolveMatchA { public: FAResolveMatch_nest (FAAllocatorA * pAlloc); virtual ~FAResolveMatch_nest (); public: void AddResult (const int Rule, const int From, const int To); void Process (); const int GetCount () const; void GetResult (const int i, int * pRule, int * pFrom, int * pTo) const; void Clear (); private: inline void SortResults (); inline void FilterResults_uniq (); inline void FilterResults_overlap_include (); private: /// keeps packed results from a single parser pass FAArray_cont_t < unsigned int > m_results; /// needed for same rule inclusion removal FAArray_cont_t < int > m_rule2pos; /// inclusion stack FAArray_cont_t < unsigned int > m_stack; enum { DefMaxPos = 0xFF, // local limitation DefMaxRule = 0xFFFF, // local limitation }; }; } #endif
palerdot/BlingFire
blingfireclient.library/inc/FATokenSegmentationTools_1best_t.h
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_TOKENSEGMENTATIONTOOLS_1BEST_T_H_ #define _FA_TOKENSEGMENTATIONTOOLS_1BEST_T_H_ #include "FAConfig.h" #include "FARSDfaCA.h" #include "FAMealyDfaCA.h" #include "FAArrayCA.h" #include "FAMultiMapCA.h" #include "FADictConfKeeper.h" #include "FALimits.h" #include "FASecurity.h" #include "FATokenSegmentationToolsCA_t.h" #include <vector> #include <float.h> namespace BlingFire { /// /// Splits input sequence into segments with smaller number of segments /// and maximum sum of weights. /// /// Input: sequence of characters /// Output: array of tuples <TokenId, From, To> /// /// If input sequence contains a subsequence of unknown characters then /// this subsequence is treated as one unknown segment. /// template < class Ty > class FATokenSegmentationTools_1best_t : public FATokenSegmentationToolsCA_t <Ty> { public: FATokenSegmentationTools_1best_t (); public: /// initializes from the valid configuration object void SetConf (const FADictConfKeeper * pConf); /// writes an array of tuples <TokenId, From, To> into pOut /// returns the actual / needed size of the array to fit all the tuples or /// -1 in case of an error const int Process ( const Ty * pIn, const int InSize, __out_ecount(MaxOutSize) int * pOut, const int MaxOutSize, const int UnkId ) const; private: // Mealy DFA keeping a map from a known segment to idx and // and MultiMap keeping a realtion between idx and <ID, Score> pair const FARSDfaCA * m_pDfa; const FAMealyDfaCA * m_pMealy; const FAArrayCA * m_pK2I; // note this is an identify since we don't have duplicate ID's const FAMultiMapCA * m_pI2Info; // unknown segment score const float m_UnkScore; // to keep track of arc data struct _TArc { int _Begin; // the begging position of the ssegment int _Id; // ID of a segment from the vocab double _Score; // cumulative score public: _TArc (): _Begin(-1), _Id(-1), _Score(-FLT_MAX) {} }; // a helper method to add an arc into the pArcs inline void AddArc (_TArc * pArcs, int start, int end, int OwSum) const; // a helper method to add an arc if a token is not known inline void AddUnknownArc (_TArc * pArcs, int start) const; }; template < class Ty > FATokenSegmentationTools_1best_t < Ty >:: FATokenSegmentationTools_1best_t () : m_pDfa (NULL), m_pMealy (NULL), m_pK2I (NULL), m_pI2Info (NULL), m_UnkScore (-100000.0) // this is guaranteed lower than any of the segment scores {} template < class Ty > void FATokenSegmentationTools_1best_t < Ty >:: SetConf (const FADictConfKeeper * pConf) { LogAssert (pConf); LogAssert(FAFsmConst::TYPE_MEALY_DFA == pConf->GetFsmType()); m_pDfa = pConf->GetRsDfa (); m_pMealy = pConf->GetMphMealy (); m_pK2I = pConf->GetK2I (); m_pI2Info = pConf->GetI2Info (); LogAssert(0 < m_pK2I->GetCount ()); } template < class Ty > inline void FATokenSegmentationTools_1best_t < Ty >:: AddArc (_TArc * pArcs, int start, int end, int Key) const { // look up the score and the id of the segment const int * pValues = NULL; const int Count = m_pI2Info->Get (Key, &pValues); LogAssert (2 == Count && NULL != pValues); const float Score = *((const float*) &(pValues [1])); // compute previous score given the start const double prevScore = 0 < start ? pArcs [start - 1]._Score : 0; // get a pointer to the arc object _TArc * pA = pArcs + end; // set the arc, if it was never set then it has smallest negative float number // so the condition is always true if (pA->_Score < Score + prevScore) { pA->_Begin = start; pA->_Id = pValues [0]; pA->_Score = Score + prevScore; } } template < class Ty > inline void FATokenSegmentationTools_1best_t < Ty >:: AddUnknownArc (_TArc * pArcs, int start) const { const int end = start; // get a pointer to the arc object and previous arc object _TArc * pA = pArcs + end; _TArc * pPrevA = pA - 1; // compute previous score given the start const double prevScore = 0 < start ? pPrevA->_Score : 0; // set the arc, if it was never set then it has smallest negative float number // so the condition is always true if (pA->_Score < m_UnkScore + prevScore) { pA->_Begin = start; pA->_Id = -1; pA->_Score = m_UnkScore + prevScore; // check if the previous arc is also Unknown then merge them if (0 < start && -1 == pPrevA->_Id) { pA->_Begin = pPrevA->_Begin; } } } template < class Ty > const int FATokenSegmentationTools_1best_t < Ty >:: Process ( const Ty * pIn, const int InSize, __out_ecount(MaxOutSize) int * pOut, const int MaxOutSize, const int UnkId ) const { DebugLogAssert (m_pDfa && m_pMealy && m_pK2I && m_pI2Info); if (0 >= InSize) { return 0; } LogAssert (pIn && InSize <= FALimits::MaxArrSize); // allocate storage for best arcs for each ending position std::vector <_TArc> End2BestArc (InSize); DebugLogAssert(InSize == End2BestArc.size ()); _TArc * pArcs = End2BestArc.data (); // get the initial state const int InitialState = m_pDfa->GetInitial (); // populate the arcs for (int start = 0; start < InSize; ++start) { int State = InitialState; int SumOw = 0; int Ow = 0; bool TokenUnknown = true; // go as deep as we can from the start position for (int i = start; i < InSize; ++i) { const Ty Iw = pIn [i]; State = m_pMealy->GetDestOw (State, Iw, &Ow); // see if the does not have a transition if (-1 == State) { break; } SumOw += Ow; DebugLogAssert (0 <= Ow); // see if the destination state is a final state if (m_pDfa->IsFinal (State)) { AddArc (pArcs, start, i, SumOw); TokenUnknown = false; } } // of for(int i = start; i < InSize; ++start) ... if (TokenUnknown) { AddUnknownArc (pArcs, start); } } // for(int start = 0; start < InSize; ++start) ... int ActualOutSize = 0; int end = InSize - 1; // now let's go in the reverse order and follow the best path while (0 <= end) { const _TArc * pA = pArcs + end; const int start = pA->_Begin; const int ID = pA->_Id; // validate the invariant of the algorithm DebugLogAssert (0 <= start && start < InSize); DebugLogAssert (0 <= end && end < InSize); DebugLogAssert (start <= end); DebugLogAssert (-1 == ID || ID >= 0); if (ActualOutSize + 3 <= MaxOutSize) { // write the results in <t, f, id> order so when reversed the order is correct pOut[ActualOutSize] = end; pOut[ActualOutSize + 1] = start; pOut[ActualOutSize + 2] = (-1 != ID) ? ID : UnkId; } ActualOutSize += 3; // skip to the end of the previous segment DebugLogAssert (start - 1 < end); end = start - 1; } // see if the pOut contains all the results if (MaxOutSize >= ActualOutSize) { // reverse the array so the results <id, f, t> and in left to tight order const int ActualOutSize_2 = ActualOutSize / 2; for(int i = 0; i < ActualOutSize_2; ++i) { int tmp = pOut[i]; pOut[i] = pOut[ActualOutSize - i - 1]; pOut[ActualOutSize - i - 1] = tmp; } } return ActualOutSize; } } #endif
palerdot/BlingFire
blingfireclient.library/inc/FABrResultCA.h
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_BRRESULTCA_H_ #define _FA_BRRESULTCA_H_ #include "FAConfig.h" namespace BlingFire { /// /// Interface for reading results of extracting brackets /// class FABrResultCA { public: /// returns an array of all added BrId --> [<From, To>, ... , <From, To>] /// (returns -1 if no BrId bracket was extracted) virtual const int GetRes (const int BrId, const int ** ppData) const = 0; /// returns next result BrId --> [<From, To>, ... , <From, To>] /// (the initial value of BrId should be -1) /// (returns -1 if no BrId bracket was extracted) virtual const int GetNextRes (int * pBrId, const int ** ppData) const = 0; /// returns first added BrId --> <From, To> relation /// (returns -1 if no BrId bracket was extracted) virtual const int GetFrom (const int BrId) const = 0; virtual const int GetTo (const int BrId) const = 0; }; } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FAParser_nest_t.h
<reponame>palerdot/BlingFire /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_PARSER_NEST_T_H_ #define _FA_PARSER_NEST_T_H_ #include "FAConfig.h" #include "FAParser_base_t.h" #include "FAResolveMatch_nest.h" #include "FAState2OwsCA.h" #include <algorithm> namespace BlingFire { /// /// This parser allows nested results with different constituent names to be /// added into a tree at a single pass. /// template < class Ty > class FAParser_nest_t : public FAParser_base_t < Ty > { public: FAParser_nest_t (FAAllocatorA * pAlloc); ~FAParser_nest_t (); private: const int UpdateResults ( const int FromPos, const int ToPos, const int State ); const bool ApplyResults (); private: enum { DefActionSize = 3, }; typedef FAParser_base_t < Ty > BASE; // conflicts resolver FAResolveMatch_nest m_resolver; }; template < class Ty > FAParser_nest_t< Ty >::FAParser_nest_t (FAAllocatorA * pAlloc) : FAParser_base_t < Ty > (pAlloc), m_resolver (pAlloc) {} template < class Ty > FAParser_nest_t< Ty >::~FAParser_nest_t () {} template < class Ty > const int FAParser_nest_t< Ty >::UpdateResults ( const int FromPos, const int ToPos, const int State ) { DebugLogAssert (BASE::m_pState2Rules); const int Count = \ BASE::m_pState2Rules->GetOws (State, BASE::m_pRules, BASE::m_MaxRulesSize); DebugLogAssert (0 < Count && Count <= BASE::m_MaxRulesSize); for (int i = 0; i < Count; ++i) { const int RuleNum = BASE::m_pRules [i]; const int * pAct; #ifndef NDEBUG const int ActSize = #endif BASE::m_pRule2Act->Get (RuleNum, &pAct); DebugLogAssert (DefActionSize == ActSize && pAct); // += Left Context Size int From2 = FromPos + pAct [0]; if (0 > From2) { From2 = 0; // due to the included left anchor } // -= Right Context Size int To2 = ToPos - pAct [1]; if (To2 >= BASE::m_UpperCount) { To2 = BASE::m_UpperCount - 1; // due to the included right anchor } // get action Tag const int Tag = pAct [2]; DebugLogAssert (From2 <= To2 && 0 <= To2 && 0 <= From2); DebugLogAssert (FALimits::MinTag <= Tag && FALimits::MaxTag >= Tag); DebugLogAssert (0 <= (BASE::m_UpperCount - To2)); m_resolver.AddResult (Tag, From2, To2); } // of for (int i = 0; ... return FromPos; } template < class Ty > const bool FAParser_nest_t< Ty >::ApplyResults () { int From, To, Tag; m_resolver.Process (); const int Count = m_resolver.GetCount (); for (int i = 0; i < Count; ++i) { m_resolver.GetResult (i, &Tag, &From, &To); DebugLogAssert (FALimits::MinTag <= Tag && FALimits::MaxTag >= Tag); BASE::m_pTree->AddNode (-Tag, From, To); } m_resolver.Clear (); return 0 != Count; } } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FADictStr2SuffixRule.h
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_DICTSTR2SUFFIXRULE_H_ #define _FA_DICTSTR2SUFFIXRULE_H_ #include "FAConfig.h" #include "FATransformCA_t.h" #include "FAArray_cont_t.h" namespace BlingFire { class FAAllocatorA; class FAMultiMapCA; /// /// This class converts intput dictionary entry to suffix rule, applying input /// transformation to the word_from and output transformation to the word_to. /// /// Input: /// word_from\tword_to[\ttag_from[\ttag_to]]\n /// Output: /// word_from --> [tag_from][tag_to]-N+suff\n /// or /// word_from --> [tag_from][tag_to]-N+suff\t-M+prefix\n /// class FADictStr2SuffixRule { public: FADictStr2SuffixRule (FAAllocatorA * pAlloc); public: // input transformation void SetInTr (const FATransformCA_t < int > * pInTr); // output transformation void SetOutTr (const FATransformCA_t < int > * pOutTr); // specifies whether case should be ignored void SetIgnoreCase (const bool IgnoreCase); // checks whether both prefix and suffix change void SetUsePref (const bool UsePref); // sets up normalization map void SetCharmap (const FAMultiMapCA * pCharMap); // makes conversion const int Process ( const int * pStr, const int StrLen, const int ** pOutStr ); private: // splits input string into fields by \t inline void Split (const int * pStr, const int StrLen); // applies input transformation inline void ApplyInTr (); // applies output transformation inline void ApplyOutTr (); // case folding, if needed inline void ToLower (); // charmap normalization, if needed inline void MapChars (); // updates m_SuffPos / m_PrefPos inline void CalcSuffPref (); // builds output inline void BuildOutput (); private: // input transformation const FATransformCA_t < int > * m_pInTr; // output transformation const FATransformCA_t < int > * m_pOutTr; // ignore case flag bool m_IgnoreCase; // indicates wether both prefix and suffix should be cut bool m_UsePref; // fields' pointers const int * m_pFrom; const int * m_pTo; const int * m_pFromTag; const int * m_pToTag; // fields' lengths int m_FromLen; int m_ToLen; int m_FromTagLen; int m_ToTagLen; // Suffix and Prefix coordinates int m_SuffPos; int m_SuffLen; int m_SuffCut; int m_PrefPos; int m_PrefLen; int m_PrefCut; // output buffer FAArray_cont_t < int > m_tmp_from; FAArray_cont_t < int > m_tmp_to; FAArray_cont_t < int > m_out_buff; // charmap const FAMultiMapCA * m_pCharMap; }; } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FAMultiMap_judy.h
<filename>blingfirecompile.library/inc/FAMultiMap_judy.h /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_MULTI_MAP_JUDY_H_ #define _FA_MULTI_MAP_JUDY_H_ #include "FAConfig.h" #include "FAMultiMapA.h" #include "FAMap_judy.h" #include "FAArray_cont_t.h" #include "FAHeap_t.h" #include "FASecurity.h" namespace BlingFire { class FAAllocatorA; /// Judy-based implementation of the FAMultiMapA /// see FAMultiMapA.h for details class FAMultiMap_judy : public FAMultiMapA { public: FAMultiMap_judy (); virtual ~FAMultiMap_judy (); public: void SetAllocator (FAAllocatorA * pAlloc); const int Get ( const int Key, __out_ecount_opt(MaxCount) int * pValues, const int MaxCount ) const; const int GetMaxCount () const; const int Get (const int Key, const int ** ppValues) const; void Set (const int Key, const int * pValues, const int ValuesCount); void Add (const int Key, const int Value); const int Next (int * pKey, const int ** ppValues) const; const int Prev (int * pKey, const int ** ppValues) const; /// additional functionality public: /// makes Arrays of values sorted and uniq void SortUniq (); /// removes Key -> Values pair, /// restructures the map so pointers returned becomes invalid! void Remove (const int Key); /// makes map as if it was just constructed void Clear (); private: inline const int GetNewIdx (); private: /// map: key -> idx FAMap_judy m_key2idx; /// map: idx -> vals FAArray_cont_t < FAArray_cont_t < int > > m_idx2vals; /// keeps unused indices FAHeap_t < int > m_deleted; /// allocator pointer FAAllocatorA * m_pAlloc; /// maximum size of the array asociated with the key int m_MaxCount; }; } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FAHyphInterpreter_t.h
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_HYPHINTERPRETER_T_H_ #define _FA_HYPHINTERPRETER_T_H_ #include "FAConfig.h" #include "FAFsmConst.h" #include "FALimits.h" #include "FAHyphConfKeeper_packaged.h" #include "FAW2SConfKeeper.h" #include "FAWftConfKeeper.h" #include "FAHyphInterpreter_core_t.h" #include "FASegmentationTools_bf_t.h" #include "FASuffixInterpretTools_t.h" #include "FASecurity.h" namespace BlingFire { class FAAllocatorA; /// /// Hyphenator interpreter, combines: /// /// W2H -- core patterns /// W2H_ALT -- alternative core patterns /// W2H+W2S -- independent segmentation and hyphenation /// W2S+W2H -- dependent segmentation and segment hyphenation /// template < class Ty > class FAHyphInterpreter_t { public: /// creates uninitialized object FAHyphInterpreter_t (); public: void SetLDB (const FAMorphLDB_t < Ty > * pLDB); public: /// see FAHyphInterpreter_core_t.h for details const int Process ( const Ty * pIn, const int InSize, __out_ecount(MaxOutSize) int * pOut, const int MaxOutSize, const bool UseAlt = false ); private: /// helper, makes W2B initialization inline const bool InitW2B (const FAMorphLDB_t < Ty > * pLDB); /// returns a hyphenation id inline const int GetHyphId (const Ty * pSeg, const int SegLen); private: int m_HyphType; bool m_fW2B; int m_HyphTypeAlt; bool m_fW2BAlt; FAHyphInterpreter_core_t < Ty > m_w2h; const FAHyphInterpreter_core_t < Ty > * m_pW2h; FAHyphInterpreter_core_t < Ty > m_w2h_alt; const FAHyphInterpreter_core_t < Ty > * m_pW2hAlt; FASegmentationTools_bf_t < Ty > m_w2s; FASuffixInterpretTools_t < Ty > m_w2b; }; template < class Ty > FAHyphInterpreter_t< Ty >::FAHyphInterpreter_t () : m_HyphType (FAFsmConst::HYPH_TYPE_CORE), m_fW2B (false), m_HyphTypeAlt (FAFsmConst::HYPH_TYPE_CORE), m_fW2BAlt (false), m_pW2h (NULL), m_pW2hAlt (NULL) {} template < class Ty > inline const bool FAHyphInterpreter_t< Ty >:: InitW2B (const FAMorphLDB_t < Ty > * pLDB) { DebugLogAssert (pLDB); const FAWftConfKeeper * pConf = pLDB->GetW2BConf (); DebugLogAssert (pConf); const bool NoTrUse = pConf->GetNoTrUse (); const bool UseNfst = pConf->GetUseNfst (); FAAssert (!UseNfst, FAMsg::InitializationError); if (false == NoTrUse) { m_w2b.SetInTr (pLDB->GetInTr ()); m_w2b.SetOutTr (pLDB->GetOutTr ()); } m_w2b.SetConf (pConf); return pConf->GetRsDfa () && pConf->GetState2Ows () && pConf->GetActs (); } template < class Ty > void FAHyphInterpreter_t< Ty >:: SetLDB (const FAMorphLDB_t < Ty > * pLDB) { m_HyphType = FAFsmConst::HYPH_TYPE_CORE; m_fW2B = false; m_HyphTypeAlt = FAFsmConst::HYPH_TYPE_CORE; m_fW2BAlt = false; m_pW2h = NULL; m_pW2hAlt = NULL; if (!pLDB) { return; } const FAHyphConfKeeper * pHyphConf = pLDB->GetW2HConf (); const FAHyphConfKeeper * pHyphAltConf = pLDB->GetW2HAltConf (); const FAW2SConfKeeper * pW2SConf = pLDB->GetW2SConf (); const FAWftConfKeeper * pW2BConf = pLDB->GetW2BConf (); m_w2h.SetConf (pHyphConf); m_w2h_alt.SetConf (pHyphAltConf); if (pHyphConf) { m_pW2h = & m_w2h; m_HyphType = pHyphConf->GetHyphType (); // initialize w2s, if needed if (pW2SConf && FAFsmConst::HYPH_TYPE_CORE != m_HyphType) { m_w2s.SetConf (pW2SConf); } // initialize w2b, if needed if (pW2BConf && pHyphConf->GetNormSegs ()) { m_fW2B = InitW2B (pLDB); } // W2S configuration is needed for this type of hyphenation FAAssert (FAFsmConst::HYPH_TYPE_CORE == m_HyphType || pW2SConf, \ FAMsg::InitializationError); } if (pHyphAltConf) { m_pW2hAlt = & m_w2h_alt; // main pattern-set must exist FAAssert (pHyphConf, FAMsg::InitializationError); m_HyphTypeAlt = pHyphAltConf->GetHyphType (); // initialize w2s, if needed if (pW2SConf && FAFsmConst::HYPH_TYPE_CORE != m_HyphTypeAlt) { m_w2s.SetConf (pW2SConf); } // initialize w2b, if needed if (pW2BConf && pHyphAltConf->GetNormSegs ()) { m_fW2BAlt = InitW2B (pLDB); } // W2S configuration is needed for this type of hyphenation FAAssert (FAFsmConst::HYPH_TYPE_CORE == m_HyphTypeAlt || pW2SConf, \ FAMsg::InitializationError); } } template < class Ty > inline const int FAHyphInterpreter_t< Ty >:: GetHyphId (const Ty * pSeg, const int SegLen) { DebugLogAssert (m_fW2B && pSeg && 0 < SegLen); Ty Out [FALimits::MaxWordLen + 1]; const int OutSize = \ m_w2b.Process (pSeg, SegLen, Out, FALimits::MaxWordLen + 1); if (0 < OutSize && FALimits::MaxWordLen + 1 >= OutSize) { int OutWordSize = 0; for (;OutWordSize < OutSize; ++OutWordSize) { if (0 == Out [OutWordSize]) break; } // there should be exactly one word concatenated with a 0 if (OutWordSize != OutSize - 1) { return FAFsmConst::HYPH_SIMPLE_HYPH; } const int LenDiff = OutWordSize - SegLen; if (-1 > LenDiff || 1 < LenDiff) { return FAFsmConst::HYPH_SIMPLE_HYPH; } if (0 != memcmp (Out, pSeg, (OutWordSize - 1) * sizeof (Ty))) { return FAFsmConst::HYPH_SIMPLE_HYPH; } // equal length if (0 == LenDiff) { const int InLast = pSeg [SegLen - 1]; const int OutLast = Out [SegLen - 1]; if (OutLast == InLast) return FAFsmConst::HYPH_SIMPLE_HYPH; else return (OutLast << 4) | FAFsmConst::HYPH_CHANGE_BEFORE; // output is one character bigger } else if (1 == LenDiff) { const int OutLast = Out [OutWordSize - 1]; return (OutLast << 4) | FAFsmConst::HYPH_ADD_BEFORE; // output is one character smaller (we under compared one character) } else { DebugLogAssert (-1 == LenDiff); if (pSeg [OutWordSize - 1] == Out [OutWordSize - 1]) { return FAFsmConst::HYPH_DELETE_BEFORE; } } } // of if (0 < OutSize && ... return FAFsmConst::HYPH_SIMPLE_HYPH; } template < class Ty > const int FAHyphInterpreter_t< Ty >:: Process ( const Ty * pIn, const int InSize, __out_ecount(MaxOutSize) int * pOut, const int MaxOutSize, const bool UseAlt ) { int Ends [FALimits::MaxWordSize]; // validate the input if (0 >= InSize || FALimits::MaxWordSize < InSize || !pIn || \ !pOut || MaxOutSize < InSize) { return -1; } const FAHyphInterpreter_core_t < Ty > * pW2H = m_pW2h; if (UseAlt) { pW2H = m_pW2hAlt; } if (!pW2H) { return -1; } // a pattern based hyphenation if (FAFsmConst::HYPH_TYPE_CORE == m_HyphType) { return pW2H->Process (pIn, InSize, pOut, MaxOutSize); // a pattern based hyphenation + hyphenation points at segment boundaries } else if (FAFsmConst::HYPH_TYPE_W2H_W2S == m_HyphType) { // do a core hyphenation const int Count2 = pW2H->Process (pIn, InSize, pOut, MaxOutSize); if (-1 == Count2) { return -1; } // make segmenation const int EndCount = \ m_w2s.Process (pIn, InSize, Ends, FALimits::MaxWordSize); // add a hyphen after each segment, except for the last one if (!m_fW2B) { for (int i = 0; i < EndCount - 1; ++i) { const int EndPos = Ends [i]; DebugLogAssert (0 <= EndPos && EndPos < InSize); __analysis_assume (0 <= EndPos && EndPos < InSize); pOut [EndPos] = FAFsmConst::HYPH_SIMPLE_HYPH; } } else { int BeginPos = 0; for (int i = 0; i < EndCount; ++i) { const int EndPos = Ends [i]; DebugLogAssert (0 <= EndPos && EndPos < InSize); __analysis_assume (0 <= EndPos && EndPos < InSize); DebugLogAssert (BeginPos <= EndPos); __analysis_assume (BeginPos <= EndPos); const int Len = EndPos - BeginPos + 1; // add a hyphenation point between segments if (i + 1 < EndCount) { // prefer hyphenator's choise of hyphen if (FAFsmConst::HYPH_NO_HYPH >= pOut [EndPos]) { pOut [EndPos] = GetHyphId (pIn + BeginPos, Len); } } BeginPos = EndPos + 1; } } return InSize; } else { DebugLogAssert (FAFsmConst::HYPH_TYPE_W2S_W2H == m_HyphType); // this allows not to check for correctness of hyphenation in the loop memset (pOut, FAFsmConst::HYPH_NO_HYPH, sizeof (int) * InSize); // make segmenation const int EndCount = \ m_w2s.Process (pIn, InSize, Ends, FALimits::MaxWordSize); // check whether no splitting was performed if (1 >= EndCount) { // do a core hyphenation pW2H->Process (pIn, InSize, pOut, MaxOutSize); } else { // hyphenate every segment and add a hyphenation point after it int BeginPos = 0; for (int i = 0; i < EndCount; ++i) { const int EndPos = Ends [i]; DebugLogAssert (0 <= EndPos && EndPos < InSize); __analysis_assume (0 <= EndPos && EndPos < InSize); DebugLogAssert (BeginPos <= EndPos); __analysis_assume (BeginPos <= EndPos); const int Len = EndPos - BeginPos + 1; // do a core hyphenation pW2H->Process (pIn + BeginPos, Len, pOut + BeginPos, Len); // add a hyphenation point between segments if (i + 1 < EndCount) { if (!m_fW2B) pOut [EndPos] = FAFsmConst::HYPH_SIMPLE_HYPH; else pOut [EndPos] = GetHyphId (pIn + BeginPos, Len); } BeginPos = EndPos + 1; } } // of if (1 < EndCount) ... return InSize; } // of if (FAFsmConst::HYPH_TYPE_CORE == m_HyphType) ... } } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FATestMorph_tag_dict.h
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_TESTMORPH_TAG_DICT_H_ #define _FA_TESTMORPH_TAG_DICT_H_ #include "FAConfig.h" #include "FATestMorph.h" #include "FADictInterpreter_t.h" namespace BlingFire { class FATagSet; /// /// Tag Dict quality test /// /// Input: /// ... /// word\tTag1\tTag2\t...TagN\n /// ... /// class FATestMorph_tag_dict : public FATestMorph { public: FATestMorph_tag_dict (FAAllocatorA * pAlloc); public: void SetTagDict (const FADictInterpreter_t < int > * pDict); void SetTagSet (const FATagSet * pTagSet); void Test (const char * pLineStr, const int LineLen); private: const FADictInterpreter_t < int > * m_pDict; const FATagSet * m_pTagSet; }; } #endif
palerdot/BlingFire
blingfireclient.library/inc/FAMealyDfaCA.h
<gh_stars>1000+ /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_MEALYDFA_CA_H_ #define _FA_MEALYDFA_CA_H_ #include "FAConfig.h" namespace BlingFire { /// /// Run-time interface for MealyDfa automaton reaction. /// class FAMealyDfaCA { public: /// For the given State and Iw returns DstState and Ow, /// returns -1 if transition does not exist. virtual const int GetDestOw ( const int State, const int Iw, int * pOw ) const = 0; }; } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FACssLDB.h
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_CSSLDB_H_ #define _FA_CSSLDB_H_ #include "FAConfig.h" #include "FALDB.h" #include "FAWgConfKeeper.h" #include "FADictConfKeeper.h" #include "FAWreRulesConfKeeper.h" #include "FAGlobalConfKeeper_packaged.h" namespace BlingFire { class FAAllocatorA; /// /// Keeps morphology resources. (The object is safe to share among threads, // after initialization). Every GetXXXConf returns NULL if corresponding /// data does not exist. /// class FACssLDB : public FALDB { public: FACssLDB (FAAllocatorA * pAlloc); ~FACssLDB (); public: void SetImage (const unsigned char * pImgDump); /// returns object into the initial state, (automatically called from the /// SetImage) void Clear (); public: /// returns W --> {T/P}, word tag guesser data, can be NULL const FAWgConfKeeper * GetW2TPConf () const; /// returns tag dictionary data, can be NULL const FADictConfKeeper * GetTagDictConf () const; /// returns OIC rules data, can be NULL const FAWreRulesConfKeeper * GetOicConf () const; /// returns CSS WRE rules data, can be NULL const FAWreRulesConfKeeper * GetCssRulesConf () const; /// returns global configuration const FAGlobalConfKeeper * GetGlobalConf () const; private: void Init (); private: FAAllocatorA * m_pAlloc; // tag dict FADictConfKeeper m_tag_dict; // W2TP* data FAWgConfKeeper m_w2tp; // OIC FAWreRulesConfKeeper m_oic; // CSS rules FAWreRulesConfKeeper m_css_rules; /// global data FAGlobalConfKeeper m_global; // flags bool m_fTagDict; bool m_fW2TP; bool m_fOic; bool m_fCssRules; bool m_fGlobal; }; } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FAMultiMapPack.h
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_MULTIMAPPACK_H_ #define _FA_MULTIMAPPACK_H_ #include "FAConfig.h" #include "FAMultiMapA.h" #include "FAArray_cont_t.h" #include "FAChainsPack_triv.h" namespace BlingFire { class FAAllocatorA; /// /// Builds memory dump for the given FAMultiMapA /// class FAMultiMapPack { public: FAMultiMapPack (FAAllocatorA * pAlloc); public: // sets up input map void SetMultiMap (const FAMultiMapA * pMMap); // sets up min sizeof value, otherwise minimum possible is used void SetSizeOfValue (const int SizeOfValue); // builds dump void Process (); // returns bulit dump const int GetDump (const unsigned char ** ppDump) const; private: // returns object into the initial state void Clear (); // fills in m_keys, m_offsets and packs values void Prepare (); // calculates size of (offset + 1) in bytes inline const unsigned int CalcOffsetSize () const; // calculates resulting dump size inline const unsigned int CalcSize () const; // stores offset inline void EncodeOffset ( const int Key, const int Offset, const int SizeOfOffset ); // builds the output dump void BuildDump (); private: // input multi-map const FAMultiMapA * m_pMMap; // values dump FAChainsPack_triv m_vals2dump; // array of keys FAArray_cont_t < int > m_keys; // array of offsets FAArray_cont_t < int > m_offsets; // output dump FAArray_cont_t < unsigned char > m_dump; unsigned char * m_pDump; int m_Offset; }; } #endif
palerdot/BlingFire
blingfireclient.library/inc/FAUtf32Utils.h
<reponame>palerdot/BlingFire<filename>blingfireclient.library/inc/FAUtf32Utils.h /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_UTF32UTILS_H_ #define _FA_UTF32UTILS_H_ #include "FAConfig.h" #include "FASecurity.h" namespace BlingFire { /// /// Note: /// 1. All symbols are assumed to be UTF-32LE /// 2. Transformation is made according to the common case folding from /// Unicode 4.1.0. Some of the transformations are irreversible, e.g. /// ANGSTREM SIGN, MICRO SIGN and so on, consider Unicode 4.1.0 for details. /// /// returns upper case symbol, if inappropriate or not possible /// returns unchanged Symbol const int FAUtf32ToUpper (const int Symbol); /// the same as above but converts the entire sequence void FAUtf32StrUpper (__out_ecount (Size) int * pChain, const int Size); /// returns lower case symbol, if inappropriate or not possible /// returns unchanged Symbol const int FAUtf32ToLower (const int Symbol); /// the same as above but converts the entire sequence void FAUtf32StrLower (__out_ecount (Size) int * pChain, const int Size); /// returns true if Symbol is in upper case const bool FAUtf32IsUpper (const int Symbol); /// returns true if Symbol is in upper case const bool FAUtf32IsLower (const int Symbol); } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FATestCmpPosNfa.h
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_TESTCMPPOSNFA_H_ #define _FA_TESTCMPPOSNFA_H_ #include "FAConfig.h" #include "FAArray_cont_t.h" namespace BlingFire { class FAAllocatorA; class FARSNfaCA; class FAMultiMapCA; /// /// For the given two triplets: < FARSNfaCA, FAMultiMapCA, FAMultiMapCA > /// (FARSNfaCA - position NFA, FAMultiMapCA - mapping from states to the openning /// triangular brackets, FAMultiMapCA - mapping from states to the closing /// triangular brackets) identifies whether these triplets have the same behavior. /// /// Note: States should have the meaning of positions in the corresponding regular /// expression, e.g. should be enumerated in the same way for both automata. /// class FATestCmpPosNfa { public: FATestCmpPosNfa (FAAllocatorA * pAlloc); public: // sets up first position NFA and mappings from state to triangular brackets // pState2BegTrBr1, pState2EndTrBr1 are optional void SetFsm1 ( const FARSNfaCA * pNfa1, const FAMultiMapCA * pState2BegTrBr1, const FAMultiMapCA * pState2EndTrBr1 ); // sets up second position NFA and mappings from state to triangular brackets // pState2BegTrBr2, pState2EndTrBr2 are optional void SetFsm2 ( const FARSNfaCA * pNfa2, const FAMultiMapCA * pState2BegTrBr2, const FAMultiMapCA * pState2EndTrBr2 ); // returns true if interfaces behaves identically const bool Process (const int MaxState, const int MaxIw); private: const bool CheckMaxTrBrSize (); const bool CheckInitials () const; const bool CheckState2BegTrBr (const int State); const bool CheckState2EndTrBr (const int State); const bool CheckDest (const int State, const int Iw); private: // input interfaces const FARSNfaCA * m_pNfa1; const FARSNfaCA * m_pNfa2; const FAMultiMapCA * m_pState2BegTrBr1; const FAMultiMapCA * m_pState2BegTrBr2; const FAMultiMapCA * m_pState2EndTrBr1; const FAMultiMapCA * m_pState2EndTrBr2; // temporary arrays FAArray_cont_t < int > m_tmp_arr1; FAArray_cont_t < int > m_tmp_arr2; int m_MaxTrBrBegSize; int m_MaxTrBrEndSize; }; } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FAState2OwsA.h
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_STATE2OWS_A_H_ #define _FA_STATE2OWS_A_H_ #include "FAConfig.h" #include "FAState2OwsCA.h" namespace BlingFire { /// /// Additional interface for Moore Machines with multiple Ows at State /// class FAState2OwsA : public FAState2OwsCA { /// read interface public: /// inherited from FAState2OwsCA virtual const int GetOws ( const int State, int * pOws, const int MaxCount ) const = 0; /// returns number of out weights associated with the state /// returns -1, if no Ows were associated virtual const int GetOws ( const int State, const int ** ppOws ) const = 0; /// write interface public: /// re-associates output weights with the State virtual void SetOws ( const int State, const int * pOws, const int Size ) = 0; }; } #endif
palerdot/BlingFire
blingfireclient.library/inc/FAState2Ow_pack_triv.h
<filename>blingfireclient.library/inc/FAState2Ow_pack_triv.h /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_STATE2OW_PACK_TRIV_H_ #define _FA_STATE2OW_PACK_TRIV_H_ #include "FAConfig.h" #include "FASetImageA.h" #include "FAState2OwCA.h" namespace BlingFire { /// /// This class is able to interpret automaton image stored by FAAutPack_triv /// class FAState2Ow_pack_triv : public FASetImageA, public FAState2OwCA { public: FAState2Ow_pack_triv (); //// from FASetImageA public: void SetImage (const unsigned char * pAutImage); /// from FAState2OwCA public: const int GetOw (const int State) const; private: // pointer to the automaton image const unsigned char * m_pAutImage; // dst size int m_DstSize; }; } #endif
palerdot/BlingFire
blingfireclient.library/inc/FAOffsetTable_pack.h
<gh_stars>1000+ /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_OFFSETTABLE_PACK_H_ #define _FA_OFFSETTABLE_PACK_H_ #include "FAConfig.h" #include "FASetImageA.h" namespace BlingFire { /// /// This class interprets image dump created by FAOffsetTablePack class /// class FAOffsetTable_pack : public FASetImageA { public: FAOffsetTable_pack (); public: /// sets up image dump void SetImage (const unsigned char * pImage); /// returns offset by its index const unsigned int GetOffset (const int Idx) const; private: // array of bases const unsigned char * m_pBase; // array of deltas const unsigned char * m_pDelta; // base size in bytes int m_BaseSize; // shift value int m_ShiftValue; // number of indices for validation int m_OffsetCount; }; } #endif
palerdot/BlingFire
blingfirecompile.library/inc/FAUtf16Utils.h
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_UTF16UTILS_H_ #define _FA_UTF16UTILS_H_ #include "FAConfig.h" #include "FASecurity.h" namespace BlingFire { /// Converts UTF-16LE/BE symbol into int (UTF-32LE), /// returns new pointer in the multi byte sequence, /// NULL if the sequence is not a valid UTF-16LE/BE string const wchar_t * FAUtf16ToInt ( const wchar_t * ptr, int * result, bool fBE ); /// Converts int (UTF-32LE) into UTF-16LE/BE symbol /// returns end pointer of the output sequence wchar_t * FAIntToUtf16 ( int Symbol, __out_ecount(MaxSize) wchar_t * ptr, const int MaxSize, bool fBE ); /// Converts UTF-16LE/BE string of specified length to the array of ints. /// Returns the number of used elements in the array. /// Returns -1 if the input sequence is invalid. const int FAStrUtf16ToArray ( const wchar_t * pStr, const int Len, __out_ecount(MaxSize) int * pArray, const int MaxSize, bool fBE ); /// Converts array of ints (UTF-32LE) into UTF-16LE/BE string of upto MaxStrSize /// length, does not place terminating 0-byte. Returns output string length. /// Returns -1 for invalid input sequence. const int FAArrayToStrUtf16 ( const int * pArray, const int Size, __out_ecount(MaxStrSize) wchar_t * pStr, const int MaxStrSize, bool fBE ); /// returns true if pEncName is a valid UTF-16LE encoding name const bool FAIsUtf16LeEnc (const char * pEncName); /// returns true if pEncName is a valid UTF-16BE encoding name const bool FAIsUtf16BeEnc (const char * pEncName); } #endif
SahiltheGreat/xv6-public
testfile.c
<reponame>SahiltheGreat/xv6-public<gh_stars>0 #include "types.h" #include "stat.h" #include "user.h" #include "fs.h" // #include "proc_stat.h" // struct proc_stat tate[100]; int main (int argc,char *argv[]) { // int pid; // // int status=0,a=3,b=4; // pid = fork (); // if (pid == 0) // { // // exec(argv[1],argv); // for(int i=0;i<9;i++) // { // cprintf("%d\n",i); // } // exit(); // } // else // { // int a , b ; // int status=waitx(&a,&b); // printf(1, "Wait Time = %d\n Run Time = %d with Status %d \n",a,b,status); // } // exit(); int pid ; // int status = 0; pid = fork(); if(pid==0) { randomfunc(); } else { int a , b ; int status=waitx(&a,&b); printf(1, "Wait Time = %d\n Run Time = %d with Status %d \n",a,b,status); } sleep(5); pid = fork(); if(pid==0) { randomfunc(); } else { int a , b ; int status=waitx(&a,&b); printf(1, "Wait Time = %d\n Run Time = %d with Status %d \n",a,b,status); } sleep(5); pid = fork(); if(pid==0) { randomfunc(); } else { int a , b ; int status=waitx(&a,&b); printf(1, "Wait Time = %d\n Run Time = %d with Status %d \n",a,b,status); } sleep(5); pid = fork(); if(pid==0) { randomfunc(); } else { int a , b ; int status=waitx(&a,&b); printf(1, "Wait Time = %d\n Run Time = %d with Status %d \n",a,b,status); } sleep(5); pid = fork(); if(pid==0) { randomfunc(); } else { int a , b ; int status=waitx(&a,&b); printf(1, "Wait Time = %d\n Run Time = %d with Status %d \n",a,b,status); } sleep(5); pid = fork(); if(pid==0) { randomfunc(); } else { int a , b ; int status=waitx(&a,&b); printf(1, "Wait Time = %d\n Run Time = %d with Status %d \n",a,b,status); } sleep(5); pid = fork(); if(pid==0) { randomfunc(); } else { int a , b ; int status=waitx(&a,&b); printf(1, "Wait Time = %d\n Run Time = %d with Status %d \n",a,b,status); } sleep(5); pid = fork(); if(pid==0) { randomfunc(); } else { int a , b ; int status=waitx(&a,&b); printf(1, "Wait Time = %d\n Run Time = %d with Status %d \n",a,b,status); } sleep(5); }
SahiltheGreat/xv6-public
sysproc.c
<gh_stars>0 #include "types.h" #include "x86.h" #include "defs.h" #include "date.h" #include "param.h" #include "memlayout.h" #include "mmu.h" #include "proc.h" #include "proc_stat.h" int sys_fork(void) { return fork(); } int sys_exit(void) { exit(); return 0; // not reached } int sys_wait(void) { return wait(); } int sys_kill(void) { int pid; if(argint(0, &pid) < 0) return -1; return kill(pid); } int sys_getpid(void) { return myproc()->pid; } int sys_sbrk(void) { int addr; int n; if(argint(0, &n) < 0) return -1; addr = myproc()->sz; if(growproc(n) < 0) return -1; return addr; } int sys_sleep(void) { int n; uint ticks0; if(argint(0, &n) < 0) return -1; acquire(&tickslock); ticks0 = ticks; while(ticks - ticks0 < n){ if(myproc()->killed){ release(&tickslock); return -1; } sleep(&ticks, &tickslock); } release(&tickslock); return 0; } // return how many clock tick interrupts have occurred // since start. int sys_uptime(void) { uint xticks; acquire(&tickslock); xticks = ticks; release(&tickslock); return xticks; } int sys_waitx(void) { int *wtime; int *rtime; if(argptr(0, (char**)&wtime, sizeof(int)) < 0) return 12; if(argptr(1, (char**)&rtime, sizeof(int)) < 0) return 13; return waitx(wtime,rtime); } int sys_randomfunc(void) { return 1; } int sys_set_priority(void) { int prio; if(argint(0, &prio) < 0) return -1; // cprintf("sysproc : %d\n",prio); return set_priority(prio); } int sys_getinf(void) { int pid; struct rostat st; if(argptr(0, (void*)&st, sizeof(st))<0) return -1; if(argint(1, &pid) < 0) return -1; return getinf(st,pid); } int sys_getpinfo(void) { int pid; struct rostat *st; if(argptr(0, (void*)&st, sizeof(*st))<0) return -1; if(argint(1, &pid) < 0) return -1; // for(i=0;i<64;i++) // { // if(pid==pstat_var.pid[i]) // { // st->inuse[i] = pstat_var.inuse[i]; // st->pid[i] = pstat_var.pid[i]; // st->priority[i] = pstat_var.priority[i]; // for(j=0;j<5;j++) // { // st->ticks[i][j] =pstat_var.ticks[i][j] ; // } // } // } return getpinfo(st,pid); } // int sys_getpinfo(void) // { // struct proc_stat * stru; // return 1; // }
SahiltheGreat/xv6-public
ps.c
#include "types.h" #include "stat.h" #include "user.h" #include "param.h" /* * Subset of struct proc (from proc.h) * Passing the whole struct proc from kernel * to user space would be VERY UNSAFE! */ enum procstate { UNUSED, EMBRYO, SLEEPING, RUNNABLE, RUNNING, ZOMBIE }; struct proc { enum procstate state; // Process state int pid; // Process ID int ppid ; // Parent process ID int priority; // Process priority int tickets; // Process totalTickets int ctime; char name[16]; // Process name }; int main(int argc, char *argv[]){ struct proc ptable[NPROC]; struct proc *p; // int err; // err = getptable(NPROC * sizeof(struct proc), &ptable); // if (err) { // printf(1,"Error getting ptable"); // exit(); // } printf(1, "PID\t\tPPID\t\tSTATE\t\tPRIORITY\tTICKETS\t\tCPUTIME\t\tCMD\n"); for(p = ptable; p != &ptable[NPROC-1]; p++) { if (p->state == UNUSED) continue; // init does not have ppid! if (p->pid == 1) printf(1, "%d\t\tN/A",p->pid); else printf(1, "%d\t\t%d", p->pid, p->ppid); switch(p->state){ case UNUSED: printf(1,"\t\t%s", "UNUSED "); break; case EMBRYO: printf(1,"\t\t%s", "EMBRYO "); break; case SLEEPING: printf(1,"\t\t%s", "SLEEPING"); break; case RUNNABLE: printf(1,"\t\t%s", "RUNNABLE"); break; case RUNNING: printf(1,"\t\t%s", "RUNNING "); break; case ZOMBIE: printf(1,"\t\t%s", "ZOMBIE "); break; } printf(1, "\t%d", p->priority); // printf(1, "\t\t%d", p->tickets); printf(1, "\t\t%d", p->ctime); printf(1,"\t\t%s\n", p->name); } exit(); }
SahiltheGreat/xv6-public
foobar1.c
#include "types.h" #include "stat.h" #include "user.h" #include "fcntl.h" #include "proc_stat.h" int main(int argc, char *argv[]) { int pid; int k, n; int x, f=100; if (argc != 2) { printf(2, "usage: %s n\n", argv[0]); } n = atoi(argv[1]); for ( k = 0; k < n; k++ ) { pid = fork (); if ( pid < 0 ) { printf(1, "%d failed in fork!\n", getpid()); exit(); } else if (pid == 0) { // child // set_priority(60-k); printf(1, "Child %d created\n",getpid()); struct rostat stru; getpinfo(&stru,getpid()); sleep(10); for (volatile long long int i = 0; i < 1000000*f; i++) { x++; } printf(1,"pid %d runtime %d numrun %d current-queue %d\n",stru.pid,stru.runtime,stru.num_run,stru.current_queue); exit(); } } for (k = 0; k < n; k++) { wait(); } exit(); }
SahiltheGreat/xv6-public
randomfunc.c
#include "types.h" #include "stat.h" #include "user.h" #include "fs.h" // #include "proc_stat.h" // struct proc_stat tate[100]; int main (int argc,char *argv[]) { int x = getpid(); int i; cprintf("PID is %d\n",x); for(i=0;i<=9;i++) { cprintf("%d ",i); } cprintf("\n"); exit(); }
SahiltheGreat/xv6-public
myprogram.c
<gh_stars>0 #include "types.h" #include "stat.h" #include "user.h" int main(void) { // sleep(1000) for(long long int i=0;i<100000000;i++) { volatile int x = 69420; x++; } // sleep(1000); printf(1, "My first xv6 program\n"); exit(); }
SahiltheGreat/xv6-public
pro2.c
<filename>pro2.c #include "types.h" #include "stat.h" #include "user.h" int main(int argc, char *argv[]) { // sleep(10); int x=0; for(volatile long long int i=0;i<1000000*atoi(argv[1]);i++) { // volatile int x = 69420; x++; } // sleep(10); printf(1, "%d\n",atoi(argv[1])); exit(); }
SahiltheGreat/xv6-public
foobar2.c
<gh_stars>0 // #include "types.h" // #include "stat.h" // #include "user.h" // #include "fs.h" // int main(int argc, char *argv[]) // { // for(int i=0;i<10;i++) // { // int pid = fork(); // if(pid==0) // { // set_priority(10-i); // printf(1,"prio %d\n",10-i); // // getinf(getpid()); // sleep(10); // printf(1,"i = %d\n",10-i); // exit(); // } // } // while(1); // int pid; // int k, n; // // int x, z; // if (argc != 2) { // printf(2, "usage: %s n\n", argv[0]); // } // n = atoi(argv[1]); // for ( k = 0; k < n; k++ ) { // pid = fork (); // set_priority(pid,10-k); // if ( pid < 0 ) { // printf(1, "%d failed in fork!\n", getpid()); // exit(); // } else if (pid == 0) { // // child // printf(1, "Child %d created\n",getpid()); // // for ( z = 0; z < 10000.0; z += 0.01 ) // // x = x + 3.14 * 89.64; // useless calculations to consume CPU time // exit(); // } // } // for (k = 0; k < n; k++) { // wait(); // } // exit(); // int priority; // int pid; // if(argc<3) // { // printf(2, "Error: Exiting\n"); // exit(); // } // pid = atoi(argv[1]); // priority = atoi(argv[2]); // if(priority < 0 || priority > 100) // { // printf(2, "Invalid priority!\n"); // exit(); // } // printf(1, "Process %d\n Priority %d\n", pid, priority); // set_priority(priority); // exit(); // int pro1; // if((pro1 = fork())==0) // { // int pro2; // if((pro2 = fork())==0) { // #ifdef PBS // set_priority(80); // #endif // sleep(atoi(argv[1])); // printf(1, "Exit 1\n"); // // getinf(getpid()); // } // else { // #ifdef PBS // set_priority(20); // #endif // sleep(atoi(argv[2])); // printf(1, "Exit 2\n"); // // getinf(getpid()); // } // } // else // { // #ifdef PBS // set_priority(50); // #endif // sleep(atoi(argv[3])); // printf(1, "Exit 3\n"); // // getinf(getpid()); // } // exit(); #include "types.h" #include "stat.h" #include "user.h" void looper(int f) { // if(f<1) // return; // ff(f-1); // ff(f-2); // return; int x=0; for (volatile long long int i = 0; i < 1000000*f; i++) { x++; } return; } int main() { // sleep(10); int pid = fork(); if(pid == 0) { // sleep (10); int ppid = fork(); if(ppid == 0) { #ifdef PBS set_priority(80); #endif looper(100); printf(1,"P1\n"); } else { #ifdef PBS set_priority(90); #endif looper(100); printf(1,"P2\n"); wait(); } } else { #ifdef PBS set_priority(70); #endif looper(100); printf(1,"P3\n"); wait(); } exit(); }
SahiltheGreat/xv6-public
proc_stat.h
<gh_stars>0 #ifndef _PSTAT_H_ #define _PSTAT_H_ #include "param.h" struct proc_stat { int inuse[NPROC]; // whether this slot of the process table is in use (1 or 0) int pid[NPROC]; // PID of each process int priority[NPROC]; // current priority level of each process (0-4) int runtime[NPROC]; int num_run[NPROC]; // int currq[NPROC]; int ticks[NPROC][5]; // number of ticks each process has accumulated at each of 4 priorities }; struct rostat { int pid; int runtime; int num_run; int current_queue; int ticks[5]; }; #endif // _PSTAT_H_
SahiltheGreat/xv6-public
newtest.c
<reponame>SahiltheGreat/xv6-public #include "types.h" #include "stat.h" #include "user.h" #include "fs.h" int main (int argc,char *argv[]) { int pid; // int status=0,a=3,b=4; pid = fork (); if (pid == 0) { exec(argv[1],argv); // sleep(5); // printf(1, "exec %s failed\n", argv[1]); // sleep(10); exit(); } else { // sleep(5); int a , b ; // getpinfo(tate,pid); // printf("%d %d\n",tate[0].pid[0],tate[0].runtime[0]); int status=waitx(&a,&b); printf(1, "Wait Time = %d\n Run Time = %d with Status %d \n",a,b,status); // exit(); } exit(); }
QB4-dev/esp_nano_httpd
esp_nano_httpd.c
<reponame>QB4-dev/esp_nano_httpd /*Copyright (c) 2018 <EMAIL> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/ #include "esp_nano_httpd.h" #include <ip_addr.h> #include <espconn.h> #include <osapi.h> #include <mem.h> //#define NHTTPD_DEBUG //#define NHTTPD_DEBUG_REQ #ifdef NHTTPD_DEBUG #define NANO_HTTPD_DBG(fmt, args...) os_printf(fmt, ## args) #else #define NANO_HTTPD_DBG(fmt, args...) /* Don't do anything in release builds */ #endif #ifdef NHTTPD_DEBUG_REQ #define NANO_HTTPD_DBG_REQ(fmt, args...) os_printf(fmt, ## args) #else #define NANO_HTTPD_DBG_REQ(fmt, args...) /* Don't do anything in release builds */ #endif #define HTTP_RESP_CHUNK_LEN 2048 //set chunk size(no more than 2920) static const http_callback_t *url_config; static struct { char *buff; uint32_t bytes; uint32_t size; } json_cache; /* Taken from sprite_tm code: "Copies len bytes over from dst to src, but does it using *only* aligned 32-bit reads. Yes, it's no too optimized but it's short and sweet and it works" */ void ICACHE_FLASH_ATTR memcpy_aligned(char *dst, const char *src, int len) { uint32_t i; uint32_t w, b; for (i=0; i<len; i++) { b=((uint32_t)src&3); w=*((uint32_t *)(src-b)); if(b==0) *dst=(w>>0); if(b==1) *dst=(w>>8); if(b==2) *dst=(w>>16); if(b==3) *dst=(w>>24); dst++; src++; } } static void ICACHE_FLASH_ATTR http_resp_free_after_tx(struct espconn *conn, char *arg){ http_request_t * req = (http_request_t*)conn->reverse; if( req == NULL ) return; req->resp_alloc = arg; } static void ICACHE_FLASH_ATTR http_resp_chunk_tx(void *arg) { char http_resp_buff[HTTP_RESP_CHUNK_LEN]; struct espconn *conn; http_request_t *req; uint32 len; conn = (struct espconn *)arg; if(conn == NULL) return; req = (http_request_t*)conn->reverse; if( req == NULL ) return; if( req->resp_bytes_left > HTTP_RESP_CHUNK_LEN) len = HTTP_RESP_CHUNK_LEN; else len = req->resp_bytes_left; memcpy_aligned(http_resp_buff, req->resp_content, len); if( espconn_send(conn, (char*)http_resp_buff, len) == 0 ){ req->resp_content += len; req->resp_bytes_left -= len; } //all data has been sent, free allocated memory if( len == 0 && req->resp_alloc != NULL){ os_free(req->resp_alloc); req->resp_alloc = NULL; } } void ICACHE_FLASH_ATTR send_http_response(struct espconn *conn, const char *code, const char *cont_type, const char *content, uint32_t cont_len) { http_request_t *req; uint32_t header_len; uint32_t bytes_free; uint32_t cont_bytes; char http_resp_buff[HTTP_RESP_CHUNK_LEN]; const char http_header[] = "HTTP/1.1 %s\r\n" "Accept-Ranges: bytes\r\n" "Content-Type: %s; charset=UTF-8\r\n" "Content-Length: %i\r\n" "Connection: close\r\n\r\n"; req = (http_request_t*)conn->reverse; if( req == NULL ) return; ets_snprintf(http_resp_buff, HTTP_RESP_CHUNK_LEN, http_header, code, cont_type, cont_len); header_len = strlen(http_resp_buff); bytes_free = HTTP_RESP_CHUNK_LEN-header_len; cont_bytes = (cont_len > bytes_free)?(bytes_free):cont_len; memcpy_aligned(http_resp_buff+header_len, content, cont_bytes); req->resp_bytes_left = (content != NULL)? (cont_len-cont_bytes) : 0; req->resp_content = content+cont_bytes; espconn_send(conn, http_resp_buff, header_len+cont_bytes); //start content tx chunk by chunk } void ICACHE_FLASH_ATTR resp_http_ok(struct espconn *conn){ send_http_response(conn, "200 OK","text/html",NULL,0); } void ICACHE_FLASH_ATTR resp_http_404(struct espconn *conn){ const char content[] = "Error 404 Not Found"; send_http_response(conn, "404 Not Found","text/html",content,strlen(content)); } void ICACHE_FLASH_ATTR resp_http_error(struct espconn *conn){ const char content[] = "500 Internal Error"; send_http_response(conn, "500 Internal Error", "text/html",content,strlen(content)); } void ICACHE_FLASH_ATTR send_html(struct espconn *conn, void *html, uint32_t len){ send_http_response(conn, "200 OK","text/html", html, len); } void ICACHE_FLASH_ATTR send_text(struct espconn *conn, void *txt, uint32_t len){ send_http_response(conn, "200 OK","text/plain", txt, len); } void ICACHE_FLASH_ATTR send_css(struct espconn *conn, void *css, uint32_t len){ send_http_response(conn, "200 OK","text/css", css, len); } void ICACHE_FLASH_ATTR send_svg(struct espconn *conn, void *svg, uint32_t len){ send_http_response(conn, "200 OK","image/svg+xml", svg, len); } static int ICACHE_FLASH_ATTR json_putchar(int c) { if(json_cache.buff != NULL && json_cache.bytes < json_cache.size) { json_cache.buff[json_cache.bytes++] = c; return c; } return 0; } void ICACHE_FLASH_ATTR send_json_tree(struct espconn *conn, struct jsontree_object *js_tree, uint32_t cache_size) { struct jsontree_context js_ctx; json_cache.buff = (char *)os_zalloc(cache_size); if(json_cache.buff == NULL) return resp_http_error(conn); json_cache.size=cache_size; json_cache.bytes=0; jsontree_setup(&js_ctx, (struct jsontree_value *)js_tree, json_putchar); while( jsontree_print_next(&js_ctx)){}; http_resp_free_after_tx(conn, json_cache.buff); send_http_response(conn, "200 OK","application/json", json_cache.buff, json_cache.bytes); } static int ICACHE_FLASH_ATTR parse_request_header(http_request_t *req, char *data, uint32_t len) { char *type, *path, *query, *http_ver; char *head_attr, *content_type, *content_len, *req_content; if( data == NULL ) goto unknown_request; //find header attributes head_attr = strstr(data,"\r\n"); if(head_attr != NULL){ os_memset(head_attr,0,2); head_attr=head_attr+2; } else { goto unknown_request; } //find tokens type = strtok(data," "); path = strtok(NULL," "); http_ver = strtok(NULL," "); //get request type if( strcmp(type,"GET") == 0 ) req->type = TYPE_GET; else if( strcmp(type,"POST") == 0 ) req->type = TYPE_POST; else goto unknown_request; //check HTTP version if( strcmp(http_ver,"HTTP/1.1") != 0 ) goto unknown_request; //set path and find query string if( path != NULL ){ req->path = path; query = os_strchr(path,'?'); if( query != NULL ){ req->query = query+1; *query = 0; } } else { goto unknown_request; } //get request content information content_type = strstr(head_attr,"Content-Type:"); content_len = strstr(head_attr,"Content-Length:"); req_content = strstr(head_attr,"\r\n\r\n"); if(req_content != NULL){ memset(req_content,0,4);//mask CR LF CR LF req_content+=4; //skip CR LF CR LF } if(content_type != NULL){ content_type = strtok(content_type,"\r\n"); req->content_type = strchr(content_type,':')+1; } if(content_len != NULL){ content_len = strtok(content_len,"\r\n"); req->content_len = atoi(strchr(content_len,':')+1); req->cont_chunk_len = len - (req_content-data); req->cont_bytes_left = req->content_len - req->cont_chunk_len; } //set content pointer if(req_content == data+len) req->content=0; //no data expected else req->content=req_content; req->read_state = REQ_GOT_HEADER; return 0; unknown_request: req->type = TYPE_UNKNOWN; return -1; } static void ICACHE_FLASH_ATTR receive_cb(void *arg, char *pdata, unsigned short len) { struct espconn *conn = (struct espconn *)arg; const http_callback_t *recall_cb; const http_callback_t *url; http_request_t *req; NANO_HTTPD_DBG("got new request. req len %d Free heap size: %d\n", len, system_get_free_heap_size()); NANO_HTTPD_DBG_REQ("request:\n%s\n", pdata); if(conn == NULL || pdata == NULL) return; req = (http_request_t*)conn->reverse; if( req == NULL ) return; if( req->read_state == REQ_GOT_HEADER ){ if( parse_request_header(req,pdata,len) != 0 ) return resp_http_error(conn); //try to find requested url in given url config for(url = url_config; url->path != NULL; url++){ if( strcmp(req->path,url->path) == 0 ){ NANO_HTTPD_DBG("url: %s found\n", req->path); if(url->handler != NULL) url->handler(conn, url->arg, url->arg_len); if(req->cont_bytes_left > 0){ //not all content data received req->read_state = REQ_CONTENT_CHUNK; req->callback = url; //recall this url on next reqest part } return;//request handled } } return resp_http_404(conn); //url not found } //not all bytes received before, recall last callback if(req->read_state == REQ_CONTENT_CHUNK && req->cont_bytes_left > 0){ req->content = pdata; req->cont_chunk_len = len; req->cont_bytes_left = req->cont_bytes_left - len; recall_cb = (http_callback_t*)req->callback; if(recall_cb != NULL) recall_cb->handler(conn, recall_cb->arg, recall_cb->arg_len); return; } } static void ICACHE_FLASH_ATTR disconnect_cb(void *arg){ struct espconn *conn = (struct espconn *)arg; if( conn->reverse != NULL ){ os_free(conn->reverse); conn->reverse = NULL; } NANO_HTTPD_DBG("disconnected. Free heap size: %d\n", system_get_free_heap_size()); } static void ICACHE_FLASH_ATTR connection_listener(void *arg) { struct espconn *conn = (struct espconn *)arg; espconn_set_opt(conn, ESPCONN_START|ESPCONN_KEEPALIVE); http_request_t *req = (http_request_t*) os_zalloc(sizeof(http_request_t)); conn->reverse = req; espconn_regist_recvcb(conn, receive_cb ); espconn_regist_sentcb(conn, http_resp_chunk_tx); espconn_regist_disconcb(conn, disconnect_cb); } /* Define content_info as in example below: const http_callback_t url_cfg[] = { {"/", send_html, index_html, sizeof(index_html)}, {"/led", led_demo_callback, NULL, 0}, {"/wifi", wifi_callback, NULL, 0}, {0,0,0,0} //last callback }; Always put NULL callback at the end of callback list */ void ICACHE_FLASH_ATTR esp_nano_httpd_register_content(const http_callback_t *content_info ) { url_config = content_info; } /* initialize nano httpd */ void ICACHE_FLASH_ATTR esp_nano_httpd_init(void) { static struct espconn *conn; if(conn != NULL) return; //already initialized conn = (struct espconn *)os_zalloc(sizeof(struct espconn)); if(conn == NULL) return; espconn_create(conn); espconn_regist_time(conn, 5, 1); conn->type = ESPCONN_TCP; conn->state = ESPCONN_NONE; /* Listen TCP packets on port 80 */ conn->proto.tcp = (esp_tcp *)os_zalloc(sizeof(esp_tcp)); if(conn->proto.tcp == NULL)return; conn->proto.tcp->local_port = 80; espconn_regist_connectcb(conn, connection_listener); espconn_accept(conn); os_printf("nano httpd active on port %d\n", conn->proto.tcp->local_port); } /* initialize wifi AP and httpd. Use one of wifi modes defined in <user_interface.h> NOTE: Two last bytes from device MAC address will be added at the end to create unique AP names for multiple devices For example: AP_ssid defined as: "MY-ESP-DEV" devices visible as: device 1: "MY-ESP-DEV-9FAE" device 2: "MY-ESP-DEV-A3C2" ... */ void ICACHE_FLASH_ATTR esp_nano_httpd_init_AP(uint8_t wifi_mode, const char *AP_ssid, const char *AP_pass) { struct softap_config ap_config = {0}; char mac[6]; if(wifi_mode == SOFTAP_MODE || wifi_mode == STATIONAP_MODE){ wifi_get_macaddr(SOFTAP_IF, (unsigned char*)mac); wifi_softap_get_config(&ap_config); ets_snprintf(ap_config.ssid,32,"%s-%02X%02X", AP_ssid, mac[4],mac[5]); ets_strncpy(ap_config.password, AP_pass?AP_pass:"",64); ap_config.ssid_len = strlen(ap_config.ssid); ap_config.channel = 1; ap_config.authmode = AP_pass?AUTH_WPA_WPA2_PSK:AUTH_OPEN; ap_config.ssid_hidden = 0; ap_config.max_connection = 4; ap_config.beacon_interval = 100; wifi_set_opmode(NULL_MODE); wifi_set_opmode(wifi_mode); wifi_softap_set_config(&ap_config); } esp_nano_httpd_init(); }
QB4-dev/esp_nano_httpd
esp_nano_httpd.h
<filename>esp_nano_httpd.h /*Copyright (c) 2018 <EMAIL> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/ #ifndef ESP_NANO_HTTPD_H_ #define ESP_NANO_HTTPD_H_ #include <c_types.h> #include <ip_addr.h> #include <espconn.h> #include <user_interface.h> #include <json/jsontree.h> /* http callback structure */ typedef struct { const char *path; void (*handler)(struct espconn *, void *, uint32_t); void *arg; uint32_t arg_len; } http_callback_t; /* http request structure */ typedef struct { enum { TYPE_UNKNOWN= 0, TYPE_GET = 1, TYPE_POST = 2 } type; enum { REQ_GOT_HEADER = 0, REQ_CONTENT_CHUNK= 1 } read_state; const char* path; const char* query; const char* content_type; void *content; uint32_t content_len; uint32_t cont_chunk_len; uint32_t cont_bytes_left; const void *callback; void *prv_data; const char *resp_content; uint8_t *resp_alloc; uint32_t resp_bytes_left; } http_request_t; void esp_nano_httpd_register_content(const http_callback_t *content_info ); void esp_nano_httpd_init(void); void esp_nano_httpd_init_AP(uint8_t wifi_mode, const char *AP_ssid, const char *AP_pass); void send_http_response(struct espconn *conn, const char *code, const char *cont_type, const char *content, uint32_t cont_len); void send_html(struct espconn *conn, void *html, uint32_t len); void send_text(struct espconn *conn, void *txt, uint32_t len); void send_css(struct espconn *conn, void *css, uint32_t len); void send_svg(struct espconn *conn, void *svg, uint32_t len); void send_json_tree(struct espconn *conn, struct jsontree_object *js_tree, uint32_t cache_size); void resp_http_ok(struct espconn *conn); void resp_http_404(struct espconn *conn); void resp_http_error(struct espconn *conn); #endif /* ESP_NANO_HTTPD_H_ */
QB4-dev/esp_nano_httpd
util/file_upload.h
<reponame>QB4-dev/esp_nano_httpd<gh_stars>1-10 /*Copyright (c) 2018 <EMAIL> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/ #ifndef ESP_NANO_HTTPD_FILE_UPLOAD_H_ #define ESP_NANO_HTTPD_FILE_UPLOAD_H_ #include "../esp_nano_httpd.h" #include <os_type.h> /* Description: - file_upload_callback is used to upload any file from web browser to ESP flash memory. You should define file info object like: file_info_t wav_file = { .accept_file_ext = ".wav", //accepted file extension .accept_cont_type = "audio", //accepted content type .base_sec = 512, //start sector in flash memory for uploaded file write .max_f_size = 128*SPI_FLASH_SEC_SIZE //max length in bytes in flash memory for uploaded file }; and then connect it to file upload callback: const http_callback_t url_cfg[] = { {"/file_upload", file_upload_callback, &wav_file, 0 }, {0,0,0,0} }; Now it is possible to upload files from file input in web browser to ESP flash memory Supported actions(CGI like) for javascript xhttp requests: GET request: /file_upload return file upload info: Example response data(json format): { "file_extension":".wav", "ContentType":"audio", "flash_sector":512, "max_size":524288, "upload_status":"", "upload_bytes":0 } */ typedef struct { const char *accept_file_ext; const char *accept_cont_type; uint16_t base_sec; uint32_t uploaded_bytes; uint32_t max_f_size; } file_info_t; void file_upload_callback(struct espconn *conn, void *arg, uint32_t len); #endif /* ESP_NANO_HTTPD_FILE_UPLOAD_H_ */
QB4-dev/esp_nano_httpd
util/wifi_util.c
<reponame>QB4-dev/esp_nano_httpd /*Copyright (c) 2018 <EMAIL> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/ #include "wifi_util.h" #include <osapi.h> #include <mem.h> #include <ip_addr.h> #include <espconn.h> #include <json/jsontree.h> #include "../esp_nano_httpd.h" static struct bss_info *bss_link; //scan list static struct espconn *wifi_scan_conn; //to keep connection pointer for scan_done_cb static int js_wifi_scan_list(struct jsontree_context *js_ctx); static const char empty_str[] = ""; static struct jsontree_string js_conn_info = JSONTREE_STRING(empty_str); static struct jsontree_string js_ssid_info = JSONTREE_STRING(empty_str); static struct jsontree_string js_addr_info = JSONTREE_STRING(empty_str); static struct jsontree_string js_save_info = JSONTREE_STRING(empty_str); static struct jsontree_callback js_wifi_scan_cb = JSONTREE_CALLBACK(js_wifi_scan_list, NULL); JSONTREE_OBJECT(json_tree, JSONTREE_PAIR("conn", &js_conn_info), JSONTREE_PAIR("SSID", &js_ssid_info), JSONTREE_PAIR("addr", &js_addr_info), JSONTREE_PAIR("save", &js_save_info), JSONTREE_PAIR("scan", &js_wifi_scan_cb), ); static int ICACHE_FLASH_ATTR js_wifi_scan_list(struct jsontree_context *js_ctx) { const char *auth_mode[] = { "OPEN", "WEP", "WPA-PSK", "WPA2-PSK", "WPA-PSK/WPA2-PSK" }; char link_info[256]; jsontree_write_atom(js_ctx, "["); while (bss_link != NULL){ ets_snprintf(link_info,256,"{\"ssid\":\"%s\",\"auth\":\"%s\",\"rssi\":%d}", bss_link->ssid, auth_mode[bss_link->authmode], bss_link->rssi ); jsontree_write_atom(js_ctx, link_info); if(bss_link->next.stqe_next != NULL) jsontree_write_atom(js_ctx, ","); bss_link = bss_link->next.stqe_next; } jsontree_write_atom(js_ctx, "]"); return 0; } static void ICACHE_FLASH_ATTR resp_wifi_conn_status(void *arg) { static struct station_config station_config; static struct ip_info ip_config; struct espconn *conn = arg; static char ip_addr[32]; uint8_t st; const char *conn_status[]= { "IDLE", "CONNECTING", "WRONG_PASSWORD", "NO_AP_FOUND", "CONNECT_FAIL", "GOT_IP" }; st = wifi_station_get_connect_status(); js_conn_info.value = conn_status[st]; wifi_get_ip_info(STATION_IF, &ip_config); os_sprintf(ip_addr,IPSTR,IP2STR(&ip_config.ip)); js_addr_info.value = ip_addr; wifi_station_get_config(&station_config); js_ssid_info.value = station_config.ssid; send_json_tree(conn, &json_tree, 1024); } static void ICACHE_FLASH_ATTR wifi_scan_done(void *arg, STATUS status) { if(wifi_scan_conn == NULL) return; if(status != OK) return resp_http_error(wifi_scan_conn); bss_link = (struct bss_info *)arg; //update bss_link list send_json_tree(wifi_scan_conn, &json_tree, 1024); } void ICACHE_FLASH_ATTR wifi_callback(struct espconn *conn, void *arg, uint32_t len) { http_request_t *req = conn->reverse; struct station_config station_conf = {0}; bool save_ok; char *param; char *action; if(req == NULL || wifi_get_opmode() == SOFTAP_MODE) return resp_http_error(conn); js_addr_info.value = empty_str;//reset addr info text js_save_info.value = empty_str;//reset save info text if(req->type == TYPE_GET && req->query != NULL){ param=strtok((char*)req->query,"&"); //read request query string if( os_memcmp(param,"action=",7) == 0 ){ action = strchr(param,'=')+1; if( os_strcmp(action,"scan") == 0){ //scan for available networks wifi_scan_conn = conn; wifi_station_scan(NULL,wifi_scan_done); return; } else if( os_strcmp(action,"save") == 0){ //save current config wifi_station_get_config(&station_conf); save_ok = wifi_station_set_config(&station_conf); js_save_info.value = save_ok?"OK":"ERR"; } } } else if(req->type == TYPE_POST){ if(req->content == NULL) return resp_http_error(conn); /* in request content We expect serialized input form query like: ssid=MY_SSID&passwd=<PASSWORD> Use strtok to divide query into tokens*/ param=strtok(req->content,"&"); do { if(param == NULL) //empty parameter continue; else if( os_memcmp(param,"ssid=",5) == 0 ) //ssid ets_strncpy(station_conf.ssid, strchr(param,'=')+1,32); else if( os_memcmp(param,"passwd=",7) == 0 ) //password ets_strncpy(station_conf.password, strchr(param,'=')+1,64); } while( (param=strtok(NULL,"&")) != NULL); //now connect to network station_conf.bssid_set = 0; //do not look for specific router MAC address wifi_station_disconnect(); wifi_station_set_config_current(&station_conf); wifi_station_connect(); } resp_wifi_conn_status(conn); }
QB4-dev/esp_nano_httpd
util/file_upload.c
<reponame>QB4-dev/esp_nano_httpd /*Copyright (c) 2018 <EMAIL> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/ #include "file_upload.h" #include <ets_sys.h> #include <osapi.h> #include <spi_flash.h> #include <mem.h> #include <json/jsontree.h> #include <upgrade.h> #include "firmware_upgrade.h" static const char empty_str[] = ""; static struct jsontree_string js_upload_f_ext = JSONTREE_STRING(empty_str); static struct jsontree_string js_upload_c_type = JSONTREE_STRING(empty_str); static struct jsontree_int js_upload_sec = {.type= JSON_TYPE_INT, .value=0}; static struct jsontree_int js_upload_max_size = {.type= JSON_TYPE_INT, .value=0}; static struct jsontree_string js_upload_status = JSONTREE_STRING(empty_str); static struct jsontree_int js_upload_bytes = {.type= JSON_TYPE_INT, .value=0}; JSONTREE_OBJECT(js_tree_upload, JSONTREE_PAIR("file_extension",&js_upload_f_ext), JSONTREE_PAIR("ContentType", &js_upload_c_type), JSONTREE_PAIR("flash_sector", &js_upload_sec), JSONTREE_PAIR("max_size", &js_upload_max_size), JSONTREE_PAIR("upload_status", &js_upload_status), JSONTREE_PAIR("upload_bytes", &js_upload_bytes) ); static struct jsontree_string js_upgrade_usrbin = JSONTREE_STRING(empty_str); static struct jsontree_string js_upgrade_flash_map = JSONTREE_STRING(empty_str); JSONTREE_OBJECT(js_tree_upgrade, JSONTREE_PAIR("usrbin", &js_upgrade_usrbin), JSONTREE_PAIR("flash_map", &js_upgrade_flash_map), JSONTREE_PAIR("upload_status", &js_upload_status), JSONTREE_PAIR("upload_bytes", &js_upload_bytes) ); #define EXTRA_BYTES 128 //additional bytes in sector buffer #define SEC_BUFF_LEN SPI_FLASH_SEC_SIZE+EXTRA_BYTES typedef struct { uint16_t c_sec; //current flash sector uint16_t sec_wr; //sector write index uint32_t wr; //total write index uint8_t sec_buff[SEC_BUFF_LEN]; } flash_upload_t; typedef struct { const char *boundary; enum { GET_CONTENT_BOUNDARY = 0, GET_CONTENT_INFO = 1, UPLOAD_IN_PROGRESS = 2, UPLOAD_COMPLETE = 3, UPLOAD_ERR_NO_INPUT_FILE = -1, UPLOAD_ERR_WRONG_FILE_EXT = -2, UPLOAD_ERR_WRONG_CONTENT = -3, UPLOAD_ERR_FILE_TOO_BIG = -4, UPLOAD_ERR_FLASH_WRITE = -5, } state; file_info_t *f_info; flash_upload_t *flash; } upload_state_t; static uint8_t* ICACHE_FLASH_ATTR get_bound(const char *content_type) { static char boundary[72]; uint8_t *bound; if(content_type == NULL) return boundary; bound = strstr(content_type,"boundary="); if( bound != NULL && strstr(content_type,"multipart/form-data;") != NULL ){ ets_snprintf(boundary,sizeof(boundary),"--%s",strchr(bound,'=')+1); return boundary; } else { return NULL; } } static uint8_t* ICACHE_FLASH_ATTR find_bound(uint8_t *data, uint32_t len, const char *bound) { uint16_t bound_len = strlen(bound); uint8_t match = 0; uint16_t i; for(i=0; i<len;i++){ ( data[i] == bound[match] )?(match++):( match=0 ); if(match == bound_len) return &data[i]+1; //return bound end addr } return NULL; } static void ICACHE_FLASH_ATTR req_content_upload(uint8_t *content, uint32_t len, upload_state_t *upload, uint32_t bytes_left) { char *tok, *cont_disposition, *input_name, *f_name, *content_type; uint8_t *p, *bound_end, *file_cont; uint32_t rx, page_wr, sector_wr, flash_addr; flash_upload_t *flash = upload->flash; uint16_t base_sec = upload->f_info->base_sec; switch(upload->state){ case GET_CONTENT_BOUNDARY: bound_end = find_bound(content, len, upload->boundary); if( bound_end != NULL){ rx = bound_end - content; //count processed bytes upload->state = GET_CONTENT_INFO; if(rx < len) req_content_upload(bound_end, len-rx, upload, bytes_left); } break; case GET_CONTENT_INFO: p = content+2; //skip CR LF file_cont = strstr(p,"\r\n\r\n"); if(file_cont == NULL || file_cont+4 > content+len) return; os_memset(file_cont,0,4); //mask CR LF CR LF file_cont += 4; //skip CR LF CR LF rx = file_cont - content; //count processed bytes //find content info tok = strtok(p,";\r\n"); do{ if(strstr(tok,"Content-Disposition: ")) cont_disposition = strchr(tok,' ')+1; else if(strstr(tok," name=")) input_name = strchr(tok,'=')+1; else if(strstr(tok," filename=")){ f_name = strchr(tok,'=')+1; os_printf("file name:%s\n",f_name); } else if(strstr(tok,"Content-Type: ")) content_type = strchr(tok,' ')+1; } while( (tok = strtok(NULL,";\r\n")) != NULL); //check if file exists if( strcmp(f_name, "\"\"") == 0 ){ os_printf("error: no file\n"); upload->state = UPLOAD_ERR_NO_INPUT_FILE; return; } //check file extension if( upload->f_info->accept_file_ext && strstr(f_name, upload->f_info->accept_file_ext) == NULL ){ os_printf("error: wrong file type != %s \n", upload->f_info->accept_file_ext); upload->state = UPLOAD_ERR_WRONG_FILE_EXT; return; } //skip content type check when: content type not specified/"application/octet-stream" - general binary data if( upload->f_info->accept_cont_type && !!strcmp(content_type, "application/octet-stream" ) ){ //check content type if( strstr(content_type, upload->f_info->accept_cont_type) == 0 ){ os_printf("Error: content type mismatch %s != %s\n", content_type, upload->f_info->accept_cont_type); upload->state = UPLOAD_ERR_WRONG_CONTENT; return; } } upload->state = UPLOAD_IN_PROGRESS; if(rx < len) req_content_upload(file_cont, len-rx, upload, bytes_left); break; case UPLOAD_IN_PROGRESS: page_wr = (flash->sec_wr+len < SEC_BUFF_LEN)?(len):(SEC_BUFF_LEN - flash->sec_wr); os_memcpy(flash->sec_buff+flash->sec_wr, content, page_wr); //write new bytes to buffer flash->sec_wr += page_wr; len-= page_wr; //check upload size if(flash->wr + flash->sec_wr > upload->f_info->max_f_size){ upload->state = UPLOAD_ERR_FILE_TOO_BIG; return; } if(flash->sec_wr == SEC_BUFF_LEN || bytes_left == 0){ //page buffer full or no more req bytes left ets_intr_lock(); spi_flash_erase_sector(base_sec+flash->c_sec); //erase new sector ets_intr_unlock(); bound_end = find_bound(flash->sec_buff, SEC_BUFF_LEN, upload->boundary); //try find end boundary if( bound_end != NULL){ //got bound end rx = bound_end - flash->sec_buff; //count processed bytes sector_wr = rx - (strlen(upload->boundary)+2); // + CR LF } else { sector_wr = SPI_FLASH_SEC_SIZE; //normal - full sector write } os_printf("upload: sec %x/%db %db left\n", base_sec+flash->c_sec, sector_wr, bytes_left); //flash sector write flash_addr = (base_sec+flash->c_sec)*SPI_FLASH_SEC_SIZE; ets_intr_lock(); if( SPI_FLASH_RESULT_OK == spi_flash_write(flash_addr, (uint32_t *)flash->sec_buff, sector_wr) ){ flash->wr+= sector_wr; //move extra bytes in buffer from end to start os_memcpy(flash->sec_buff, flash->sec_buff+SPI_FLASH_SEC_SIZE, EXTRA_BYTES); flash->sec_wr=EXTRA_BYTES; flash->c_sec++; // if bound-end found file upload is complete if( bound_end != NULL) upload->state = UPLOAD_COMPLETE; }else{ upload->state = UPLOAD_ERR_FLASH_WRITE; } ets_intr_unlock(); upload->f_info->uploaded_bytes = upload->flash->wr; } if(upload->state != UPLOAD_IN_PROGRESS) return; if(len > 0) req_content_upload(content+page_wr, len, upload, bytes_left); break; default: break; } } static const char ICACHE_FLASH_ATTR *get_upload_state_str(upload_state_t *upload ) { if(upload == NULL) return empty_str; switch(upload->state){ case UPLOAD_IN_PROGRESS: return "UPLOAD_IN_PROGRESS"; case UPLOAD_COMPLETE: return "UPLOAD_COMPLETE"; case UPLOAD_ERR_NO_INPUT_FILE: return "UPLOAD_ERR_NO_INPUT_FILE"; case UPLOAD_ERR_WRONG_FILE_EXT: return "UPLOAD_ERR_WRONG_FILE_EXT"; case UPLOAD_ERR_WRONG_CONTENT: return "UPLOAD_ERR_WRONG_CONTENT"; case UPLOAD_ERR_FILE_TOO_BIG: return "UPLOAD_ERR_FILE_TOO_BIG"; case UPLOAD_ERR_FLASH_WRITE: return "UPLOAD_ERR_FLASH_WRITE"; default: break; } return "UPLOAD_STATE_UNKNOWN"; } static void ICACHE_FLASH_ATTR resp_upload_info(struct espconn *conn, file_info_t *f_info, upload_state_t *upload) { js_upload_f_ext.value = f_info->accept_file_ext; js_upload_c_type.value = f_info->accept_cont_type; js_upload_sec.value = f_info->base_sec; js_upload_max_size.value = f_info->max_f_size; js_upload_status.value = get_upload_state_str(upload); js_upload_bytes.value = (upload != NULL)? upload->flash->wr:0; send_json_tree(conn, &js_tree_upload, 256); } void ICACHE_FLASH_ATTR file_upload_callback(struct espconn *conn, void *arg, uint32_t len) { http_request_t *req = conn->reverse; file_info_t *f_info = arg; upload_state_t *upload; if(req != NULL || f_info != NULL ) upload=(upload_state_t *)req->prv_data; else return resp_http_error(conn); if(req->type == TYPE_GET ) return resp_upload_info(conn, f_info, upload); if(req->type != TYPE_POST ) return resp_http_error(conn); if( req->read_state == REQ_GOT_HEADER ){ upload = (upload_state_t*)os_zalloc(sizeof(upload_state_t)); if(upload == NULL) return resp_http_error(conn); upload->flash = (flash_upload_t*)os_zalloc(sizeof(flash_upload_t)); if(upload->flash == NULL) return resp_http_error(conn); upload->boundary = get_bound(req->content_type); if(upload->boundary == NULL) return resp_http_error(conn); upload->f_info = f_info; req->prv_data = upload; os_printf("file upload...\n"); } req_content_upload(req->content, req->cont_chunk_len, upload, req->cont_bytes_left); if(req->cont_bytes_left == 0){ os_printf("uploaded(%d bytes) %s\n", upload->f_info->uploaded_bytes, (upload->state==UPLOAD_COMPLETE)?("OK"):("ERR")); resp_upload_info(conn, f_info, upload); os_free(upload->flash); os_free(upload); upload = NULL; } } static void ICACHE_FLASH_ATTR resp_upgrade_info(struct espconn *conn, upload_state_t *upload) { uint8_t fw_bin; enum flash_size_map flash_map; fw_bin = system_upgrade_userbin_check(); flash_map = system_get_flash_size_map(); js_upgrade_usrbin.value = (fw_bin == UPGRADE_FW_BIN1)?"APP1":"APP2"; switch(flash_map){ case FLASH_SIZE_4M_MAP_256_256: case FLASH_SIZE_2M: js_upgrade_flash_map.value = "FOTA_NOT_SUPPORTED"; break; case FLASH_SIZE_8M_MAP_512_512: js_upgrade_flash_map.value = "FLASH_SIZE_8M_MAP_512_512"; break; case FLASH_SIZE_16M_MAP_512_512: js_upgrade_flash_map.value = "FLASH_SIZE_16M_MAP_512_512"; break; case FLASH_SIZE_32M_MAP_512_512: js_upgrade_flash_map.value = "FLASH_SIZE_32M_MAP_512_512"; break; case FLASH_SIZE_16M_MAP_1024_1024: js_upgrade_flash_map.value = "FLASH_SIZE_16M_MAP_1024_1024"; break; case FLASH_SIZE_32M_MAP_1024_1024: js_upgrade_flash_map.value = "FLASH_SIZE_32M_MAP_1024_1024"; break; default: js_upgrade_flash_map.value = "FLASH_SIZE_MAP_UNKNOWN"; break; } js_upload_status.value = get_upload_state_str(upload); js_upload_bytes.value = (upload != NULL)?upload->flash->wr:0; send_json_tree(conn, &js_tree_upgrade, 256); } void ICACHE_FLASH_ATTR firmware_upgrade_callback(struct espconn *conn, void *arg, uint32_t len) { http_request_t *req = conn->reverse; static file_info_t f_info; static upload_state_t *upload; enum flash_size_map flash_map; char *param, *action; void (*pre_upgrade_func)(void) = arg; static os_timer_t reboot_timer; uint8_t fw_bin; if(req == NULL) return resp_http_error(conn); //GET request - return upgrade info if(req->type == TYPE_GET && req->query == NULL) return resp_upgrade_info(conn, upload); //POST request - firmware upload if(req->type != TYPE_POST ) return resp_http_error(conn); if( req->read_state == REQ_GOT_HEADER ){ //stop if another firmware upload not finished if(upload != NULL ) return resp_http_error(conn); f_info.accept_file_ext = ".bin"; f_info.accept_cont_type = NULL; fw_bin = system_upgrade_userbin_check(); flash_map = system_get_flash_size_map(); os_printf("fw app bin: %s upgrade flash map %d\n", fw_bin?"APP1":"APP2", flash_map); switch(flash_map){ case FLASH_SIZE_4M_MAP_256_256: case FLASH_SIZE_2M: return resp_http_error(conn); //FOTA not supported case FLASH_SIZE_8M_MAP_512_512: case FLASH_SIZE_16M_MAP_512_512: case FLASH_SIZE_32M_MAP_512_512: f_info.base_sec = (fw_bin == UPGRADE_FW_BIN2)? 0x0001:0x0081; f_info.max_f_size = 128*SPI_FLASH_SEC_SIZE; break; case FLASH_SIZE_16M_MAP_1024_1024: case FLASH_SIZE_32M_MAP_1024_1024: f_info.base_sec = (fw_bin == UPGRADE_FW_BIN2)? 0x0001:0x0101; f_info.max_f_size = 256*SPI_FLASH_SEC_SIZE; break; default: return resp_http_error(conn); //flash map unknown } //execute before upgrade action if specified if( pre_upgrade_func != NULL ) pre_upgrade_func(); upload = (upload_state_t*)os_zalloc(sizeof(upload_state_t)); if(upload == NULL) return resp_http_error(conn); upload->flash = (flash_upload_t*)os_zalloc(sizeof(flash_upload_t)); if(upload->flash == NULL) return resp_http_error(conn); upload->boundary = get_bound(req->content_type); if(upload->boundary == NULL) return resp_http_error(conn); upload->f_info = &f_info; } req_content_upload(req->content, req->cont_chunk_len, upload, req->cont_bytes_left); //request processing finished if(req->cont_bytes_left == 0){ os_printf("firmware uploaded(%d bytes) %s\n", upload->f_info->uploaded_bytes, (upload->state==UPLOAD_COMPLETE)?("OK"):("ERR")); resp_upgrade_info(conn, upload); os_free(upload->flash); os_free(upload); //reboot to new firmware if firmware upload is complete if( upload->state == UPLOAD_COMPLETE ){ system_upgrade_flag_set(UPGRADE_FLAG_FINISH); //delayed reboot - let ESP send response to client before restart os_printf("FOTA reboot...\n"); os_timer_disarm(&reboot_timer); os_timer_setfn(&reboot_timer, (os_timer_func_t *)system_upgrade_reboot, NULL); os_timer_arm(&reboot_timer, 1000, 0); } } }
QB4-dev/esp_nano_httpd
util/firmware_upgrade.h
/*Copyright (c) 2018 <EMAIL> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/ #ifndef ESP_NANO_HTTPD_FOTA_H_ #define ESP_NANO_HTTPD_FOTA_H_ #include "../esp_nano_httpd.h" #include <os_type.h> /* Description: - firmware_upgrade_callback is used to provide Firmware Over the Air(FOTA) feature. All You need to do is to connect this calback to URL like: const http_callback_t url_cfg[] = { {"/upgrade", firmware_upgrade_callback, on_upgrade_init, 0 }, {0,0,0,0} }; You can specify an action taken right before upgrade and pass it to firmware_upgrade_callback as optional argument like void on_upgrade_init(void) function in this example Supported actions(CGI like) for javascript xhttp requests: GET request: /upgrade return firmware upgrade info: Example response data(json format): { "usrbin":"APP1", "flash_map":"FLASH_SIZE_32M_MAP_1024_1024", "upload_status":"", "upload_bytes":0 } During file/firmware upload upload_status field in GET response is updated and following values are possible: UPLOAD_IN_PROGRESS UPLOAD_COMPLETE UPLOAD_ERR_NO_INPUT_FILE UPLOAD_ERR_WRONG_FILE_EXT UPLOAD_ERR_WRONG_CONTENT UPLOAD_ERR_FILE_TOO_BIG UPLOAD_ERR_FLASH_WRITE UPLOAD_STATE_UNKNOWN */ void firmware_upgrade_callback(struct espconn *conn, void *arg, uint32_t len); #endif /* ESP_NANO_HTTPD_FOTA_H_ */
QB4-dev/esp_nano_httpd
util/wifi_util.h
<filename>util/wifi_util.h /*Copyright (c) 2018 <EMAIL> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/ #ifndef ESP_NANO_HTTPD_WIFI_UTIL_H_ #define ESP_NANO_HTTPD_WIFI_UTIL_H_ #include <c_types.h> #include <user_interface.h> /* This callback is used to configure ESP8266 WiFi settings. To use it add something like below in esp_nano_httpd URL table: const http_callback_t url_cfg[] = { {"/wifi", wifi_callback, NULL, 0}, {0,0,0,0} }; Supported actions(CGI like) very handy for javascript xhttp requests GET request: /wifi return current connection info GET request: /wifi?action=scan scan for available networks POST request: /wifi connect to network(POST request content: ssid=MY_SSID&passwd=MY_PASSWD) GET request: /wifi?action=save save current WiFi config Example response data(json format): { "conn":"GOT_IP", "SSID":"Dom", "addr":"", "save":"", "scan":[ {"ssid":"Dom","auth":"<PASSWORD>-PSK/WPA2-PSK","rssi":-71}, {"ssid":"PENTAGRAM_P_6351","auth":"OPEN","rssi":-35} ] } */ void wifi_callback(struct espconn *conn, void *arg, uint32_t len); #endif /* ESP_NANO_HTTPD_WIFI_UTIL_H_ */
jwachlin/ARCartBase
ARCartBase.h
<filename>ARCartBase.h /** * @file ARCartBase.h * @author <NAME> * @date Feb 2019 * @brief Firmware for AR Cart base station interface to computer */ #ifndef _AR_CART_BASE_H_ #define _AR_CART_BASE_H_ #include <stdint.h> #include <Arduino.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/timers.h" // Task setup #define SERIAL_TASK_STACK_SIZE (1000) #define NETWORK_TASK_STACK_SIZE (1000) #define SERIAL_TASK_PRIORITY (2) #define NETWORK_TASK_PRIORITY (2) /** * @brief Command information */ typedef struct motor_command_t { float lfm; float lrm; float rfm; float rrm; } motor_command_t; void start_base(void); void serial_task(void * param); void network_task(void * param); #endif
jwachlin/ARCartBase
base_serial.h
/** * @file base_serial.h * @author <NAME> * @date Feb 2019 * @brief Firmware for AR Cart base station interface to computer */ #ifndef _BASE_SERIAL_H_ #define _BASE_SERIAL_H_ #define MAX_PAYLOAD_SIZE (128) #define START_BYTE_0 (0x77) #define START_BYTE_1 (0x12) /** * @brief Serial packets */ typedef struct serial_packet_t { uint8_t cls; uint8_t id; uint8_t length; uint8_t payload[MAX_PAYLOAD_SIZE]; uint8_t checksum; } serial_packet_t; #endif
jwachlin/ARCartBase
base_network.h
/** * @file base_network.h * @author <NAME> * @date Feb 2019 * @brief Network interface for AR Cart */ #ifndef _BASE_NETWORK_H_ #define _BASE_NETWORK_H_ #include <stdint.h> #include "ARCartBase.h" typedef enum message_type_t{ MSG_CONTROLLER_INPUT, MSG_TELEMETRY }; /** * @brief Controller structure */ typedef struct __attribute__((packed)) controller_input_t { uint32_t address; float right_stick_lr; // Right joystick left right [-1.0,1.0] float right_stick_ud; // Right joystick up down [-1.0,1.0] float left_stick_lr; // Left joystick left right [-1.0,1.0] float left_stick_ud; // Left joystick up down [-1.0,1.0] } controller_input_t; /** * @brief Speed information. Note no direction information possible */ typedef struct cart_speed_t { float lfm; float lrm; float rfm; float rrm; float avg; } cart_speed_t; /** * @brief Cart telemetry */ typedef struct __attribute__((packed)) cart_telemetry_t { uint32_t cart_number; motor_command_t motor_command; cart_speed_t speed; } cart_telemetry_t; bool network_init(void); void send_command(controller_input_t * controller_input); #endif
alexsandrovp/winreg
registry.h
<reponame>alexsandrovp/winreg /* Copyright (c) 2016 <NAME> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #pragma once #include <string> #include <vector> #include <Windows.h> #pragma comment (lib, "Shlwapi.lib") inline std::wstring wstring_from_utf8(const std::string& str); inline std::string utf8_from_wstring(const std::wstring& str); namespace winreg { HKEY splitHiveFromKey(std::string path, std::string& key); HKEY splitHiveFromKey(std::wstring path, std::wstring& key); bool keyExists(HKEY hive, std::string key, REGSAM redirection = 0); bool keyExists(HKEY hive, std::wstring key, REGSAM redirection = 0); bool createKey(HKEY hive, std::string key, REGSAM redirection = 0); bool createKey(HKEY hive, std::wstring key, REGSAM redirection = 0); /* careful, there is no check to see if dst in nested inside src */ bool copyKey(HKEY srcHive, std::wstring srcKey, HKEY dstHive, std::wstring dstKey, REGSAM srcRedirection = 0, REGSAM dstRedirection = 0); bool propertyExists(HKEY hive, std::string key, std::string property, REGSAM redirection = 0); bool propertyExists(HKEY hive, std::wstring key, std::wstring property, REGSAM redirection = 0); DWORD getPropertyType(HKEY hive, std::string key, std::string property, REGSAM redirection = 0); DWORD getPropertyType(HKEY hive, std::wstring key, std::wstring property, REGSAM redirection = 0); std::vector<std::string> enumerateProperties(HKEY hive, std::string key, REGSAM redirection = 0); std::vector<std::wstring> enumerateProperties(HKEY hive, std::wstring key, REGSAM redirection = 0); std::vector<std::string> enumerateSubkeys(HKEY hive, std::string key, REGSAM redirection = 0); std::vector<std::wstring> enumerateSubkeys(HKEY hive, std::wstring key, REGSAM redirection = 0); bool deleteProperty(HKEY hive, std::string key, std::string property, REGSAM redirection = 0); bool deleteProperty(HKEY hive, std::wstring key, std::wstring property, REGSAM redirection = 0); bool deleteKey(HKEY hive, std::string key, std::string subkey, bool recurse = false, REGSAM redirection = 0); bool deleteKey(HKEY hive, std::wstring key, std::wstring subkey, bool recurse = false, REGSAM redirection = 0); bool killKey(HKEY hive, std::string key, REGSAM redirection = 0); bool killKey(HKEY hive, std::wstring key, REGSAM redirection = 0); // string std::string getString(HKEY hive, std::string key, std::string property, std::string default_value, REGSAM redirection = 0); std::wstring getString(HKEY hive, std::wstring key, std::wstring property, std::wstring default_value, REGSAM redirection = 0); bool setString(HKEY hive, std::string key, std::string property, std::string value, REGSAM redirection = 0); bool setString(HKEY hive, std::wstring key, std::wstring property, std::wstring value, REGSAM redirection = 0); //expand string std::string getExpandString(HKEY hive, std::string key, std::string property, std::string default_value, REGSAM redirection = 0); std::wstring getExpandString(HKEY hive, std::wstring key, std::wstring property, std::wstring default_value, REGSAM redirection = 0); bool setExpandString(HKEY hive, std::string key, std::string property, std::string value, REGSAM redirection = 0); bool setExpandString(HKEY hive, std::wstring key, std::wstring property, std::wstring value, REGSAM redirection = 0); //multistring bool getMultiString(HKEY hive, std::string key, std::string property, std::vector<std::string>& value, REGSAM redirection = 0); bool getMultiString(HKEY hive, std::wstring key, std::wstring property, std::vector<std::wstring>& value, REGSAM redirection = 0); bool setMultiString(HKEY hive, std::string key, std::string property, const std::vector<std::string>& value, REGSAM redirection = 0); bool setMultiString(HKEY hive, std::wstring key, std::wstring property, const std::vector<std::wstring>& value, REGSAM redirection = 0); //dword long getDword(HKEY hive, std::string key, std::string property, long default_value, REGSAM redirection = 0); long getDword(HKEY hive, std::wstring key, std::wstring property, long default_value, REGSAM redirection = 0); bool setDword(HKEY hive, std::string key, std::string property, long number, REGSAM redirection = 0); bool setDword(HKEY hive, std::wstring key, std::wstring property, long number, REGSAM redirection = 0); //dword be long getDwordBE(HKEY hive, std::string key, std::string property, long default_value, REGSAM redirection = 0); long getDwordBE(HKEY hive, std::wstring key, std::wstring property, long default_value, REGSAM redirection = 0); bool setDwordBE(HKEY hive, std::string key, std::string property, long number, REGSAM redirection = 0); bool setDwordBE(HKEY hive, std::wstring key, std::wstring property, long number, REGSAM redirection = 0); //qword long long getQword(HKEY hive, std::string key, std::string property, long long default_value, REGSAM redirection = 0); long long getQword(HKEY hive, std::wstring key, std::wstring property, long long default_value, REGSAM redirection = 0); bool setQword(HKEY hive, std::string key, std::string property, long long number, REGSAM redirection = 0); bool setQword(HKEY hive, std::wstring key, std::wstring property, long long number, REGSAM redirection = 0); // binary bool getBinary(HKEY hive, std::string key, std::string property, std::string& result, REGSAM redirection = 0); bool getBinary(HKEY hive, std::wstring key, std::wstring property, std::string& result, REGSAM redirection = 0); std::string getBinaryAsBase64(HKEY hive, std::string key, std::string property, std::string default_value, REGSAM redirection = 0); std::string getBinaryAsBase64(HKEY hive, std::wstring key, std::wstring property, std::string default_value, REGSAM redirection = 0); bool setBinary(HKEY hive, std::string key, std::string property, const char* const data, size_t datalen, REGSAM redirection = 0); bool setBinary(HKEY hive, std::wstring key, std::wstring property, const char* const data, size_t datalen, REGSAM redirection = 0); bool setBinaryFromBase64(HKEY hive, std::string key, std::string property, std::string data, REGSAM redirection = 0); bool setBinaryFromBase64(HKEY hive, std::wstring key, std::wstring property, std::string data, REGSAM redirection = 0); // other types bool getAsByteArray(HKEY hive, std::wstring key, std::wstring property, std::string& result, unsigned long& type, REGSAM redirection = 0); bool getAsByteArray(HKEY hive, std::string key, std::string property, std::string& result, unsigned long& type, REGSAM redirection = 0); std::string getAsBase64ByteArray(HKEY hive, std::string key, std::string property, std::string default_value, unsigned long& type, REGSAM redirection = 0); std::string getAsBase64ByteArray(HKEY hive, std::wstring key, std::wstring property, std::string default_value, unsigned long& type, REGSAM redirection = 0); bool setByteArray(HKEY hive, std::wstring key, std::wstring property, const char* const data, size_t datalen, unsigned long type, REGSAM redirection = 0); bool setByteArray(HKEY hive, std::string key, std::string property, const char* const data, size_t datalen, unsigned long type, REGSAM redirection = 0); bool setByteArrayFromBase64(HKEY hive, std::string key, std::string property, std::string data, unsigned long type, REGSAM redirection = 0); bool setByteArrayFromBase64(HKEY hive, std::wstring key, std::wstring property, std::string data, unsigned long type, REGSAM redirection = 0); namespace remap { bool start(HKEY sourceHive, HKEY targetHive, const std::string& targetKey, REGSAM redirection); bool start(HKEY sourceHive, HKEY targetHive, const std::wstring& targetKey, REGSAM redirection); bool stop(HKEY sourceHive); } }
alexsandrovp/winreg
base64.h
/* Copyright (c) 2016 <NAME> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /* modifications: 1. removed #ifndef/#define/#endif and replaced with #pragma once 2. added stl wrappers */ #pragma once #include <string> #include <stdlib.h> //size_t get_buffer_size_for_encoding(size_t byte_length); //size_t get_buffer_size_for_decoding(size_t encoded_length); // wrapper for stl string std::string b64encode(const char* data, size_t data_length); // wrapper for stl string std::string b64encode(std::string data); // wrapper for stl string std::string b64decode(std::string data); /* encodes 'plain' bytes as base64 into 'encoded', appending a null character at the end 'encoded' must be an unallocated pointer to char, this function will allocate the necessary memory. it is the caller's responsibility to free the memory allocated in 'encoded' using 'delete[]' 'plain' is treated as an array of bytes of 'plain_length' length, thus pay attention if your string has a NULL end, it will might be encoded as well the function returns the length of the array (excluding the null character) */ size_t base64_encode(const char* plain, size_t plain_length, char** encoded, int addPad); /* decodes 'encoded' bytes as base64 into 'plain', appending a null character at the end 'plain' must be an unallocated pointer to char, this function will allocate the necessary memory. it is the caller's responsibility to free the memory allocated in 'plain' using 'delete[]' 'encoded_length' must be the length of bytes in the 'encoded' array that must be encoded. careful not to pass the array size, as it may contain invalid characters that cannot be decoded (NULL terminator, for instance) the function returns the length of the array (excluding the null character) if the function fails, the memory allocated to 'plain' is freed and the pointer is set to null. the function then returns an index in 'encoded' that triggered the error. */ size_t base64_decode(const char* encoded, size_t encoded_length, char** plain);
alexsandrovp/winreg
test.h
<filename>test.h<gh_stars>0 /* Copyright (c) 2016 <NAME> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #pragma once #define ERROR_NO_MEMORY 1 #define ERROR_IMPORT_TESTREGISTRY 100 #define ERROR_REMOVE_TESTREGISTRY 101 #define ERROR_KEYEXISTS 102 #define ERROR_CREATEKEY 103 #define ERROR_PROPERTYTYPE 104 #define ERROR_PROPERTYEXISTS 105 #define ERROR_ENUMERATEKEYS 106 #define ERROR_ENUMERATEPROPERTIES 107 #define ERROR_DELETEKEY 108 #define ERROR_DELETEPROPERTY 109 #define ERROR_REGPATHCONVERT 110 #define ERROR_COPYTREE 111 #define ERROR_GETSTRING 200 #define ERROR_SETSTRING 201 #define ERROR_GETEXPSTRING 202 #define ERROR_SETEXPSTRING 203 #define ERROR_GETMULTISTRING 204 #define ERROR_SETMULTISTRING 205 #define ERROR_GETDWORD 300 #define ERROR_SETDWORD 301 #define ERROR_GETDWORDBE 302 #define ERROR_SETDWORDBE 303 #define ERROR_GETQWORD 304 #define ERROR_SETQWORD 305 #define ERROR_GETBINARY 306 #define ERROR_SETBINARY 307 #define ERROR_GETOTHER 308 #define ERROR_SETOTHER 309 int testAll();
davidson-bruno/dining-philosofers
phil.h
#ifndef PHIL_H #define PHIL_H #define HUNGRY 0 #define THINKING 1 #define EATING 2 #include <semaphore.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <time.h> /* Convenções: Prefixo "env" : variável ou função relacionada ao ambiente (de "enviroment") Prefixo "i" : variável ou função que indica índice Prefixo "max" : variável que guarda valor máximo Prefixo "min" : variável que guarda valor mínimo Prefixo "next" : variável que guarda valor a ser consumido Prefixo "phil" : variável ou função relacionada a um filósofo (de "philosofer") Prefixo "sem" : variável ou função relacionada a um semáforo Prefixo "total": variável de acumulação */ typedef struct { int id; int next_eating; int next_thinking; int status; int times_he_ate; int total_eating; int total_hungry; int total_thinking; sem_t sem; } phil_t; typedef struct { int max_rand_time; int max_runtime; int min_rand_time; int runtime; int total_phil; phil_t* phils; sem_t mutex; time_t start_time; } env_t; typedef struct { env_t* env; int phil_i; } args_t; /* Filósofos */ void* phil_thread_func(void*); void phil_init(env_t*, int); void phil_init_all(env_t*); void phil_show(phil_t*); void phil_think(phil_t*); void phil_take_hashi(env_t*, int); void phil_try(env_t*, int); void phil_eat(phil_t*); void phil_put_hashi(env_t*, int); int phil_get_left(env_t*, int); int phil_get_right(env_t*, int); /* Ambiente */ void* env_thread_func(void*); void env_init(env_t*); void env_show(env_t*); int env_rand_time(env_t*); #endif
davidson-bruno/dining-philosofers
main.c
<reponame>davidson-bruno/dining-philosofers #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include "phil.c" int main(int argc, char* argv[]) { // Declara e inicializa o ambiente env_t env; env_init(&env); // Passa os argumentos do programa para o ambiente for(int i = 0; i < argc; i++) { if(strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0) { printf("------------\n"); printf("Jantar dos filósofos\n"); printf("------------\n"); printf("--help | -h\tExibe a ajuda e sai.\n"); printf("--tot | -t\tQuantidade de filósofos que serão criados. O padrão é 5.\n"); printf("--run | -r\tTempo máximo de execução em segundos de cada thread. O programa encerra quando todas terminam o processamento. Se definido como zero, executa sem limite de tempo (padrão).\n"); printf("--min | -i\tLimite inferior do intervalo de tempo gerado aleatoriamente (Padrão = 1).\n"); printf("--max | -m\tLimite suprior do intervalo de tempo gerado aleatoriamente (Padrão = 5).\n"); return 0; } if(strcmp(argv[i], "--tot") == 0 || strcmp(argv[i], "-t") == 0) { int value = atoi(argv[i + 1]); env.total_phil = value; } else if(strcmp(argv[i], "--run") == 0 || strcmp(argv[i], "-r") == 0) { int value = atoi(argv[i + 1]); env.max_runtime = value; } else if(strcmp(argv[i], "--max") == 0 || strcmp(argv[i], "-m") == 0) { int value = atoi(argv[i + 1]); env.max_rand_time = value; } else if(strcmp(argv[i], "--min") == 0 || strcmp(argv[i], "-i") == 0) { int value = atoi(argv[i + 1]); env.min_rand_time = value; } } // Declara e inicializa os filósofos phil_t phils[env.total_phil]; env.phils = phils; phil_init_all(&env); // Declara as threads pthread_t phil_threads[env.total_phil]; pthread_t env_thread; // Declara os argumentos da função args_t args[env.total_phil]; // Guarda o tempo de início da execução na variável start_time time(&env.start_time); // Declara variável de sinalização de erro que será utilizada int error = 0; // Cria as threads dos filósofos for(int i = 0; i < env.total_phil; i++) { args[i].env = &env; args[i].phil_i = i; error = pthread_create(&(phil_threads[i]), NULL, phil_thread_func, &(args[i])); if(error) { printf("Erro ao criar a thread do filósofo %i. O erro retornou o status %i.\n", i, error); exit(EXIT_FAILURE); } } // Cria a thread de exibição error = pthread_create(&(env_thread), NULL, env_thread_func, &(env)); if(error) { printf("Erro ao criar a thread de exibição. O erro retornou o status %i.\n", error); exit(EXIT_FAILURE); } for(int i = 0; i < env.total_phil; i++) { error = pthread_join(phil_threads[i], NULL); if(error) { printf("Erro ao processar a thread do filósofo %i. O erro retornou o status %i.\n", i, error); exit(EXIT_FAILURE); } } env_show(&env); return EXIT_SUCCESS; }
davidson-bruno/dining-philosofers
phil.c
<reponame>davidson-bruno/dining-philosofers #include "phil.h" /* Funções dos filósofos */ void* phil_thread_func(void* arguments) { args_t* args = (args_t*)arguments; env_t* env = args->env; int phil_i = args->phil_i; phil_t* phil = &env->phils[phil_i]; time_t start_time; time_t end_time; while(1) { time(&start_time); phil_think(phil); time(&end_time); phil->total_thinking += difftime(end_time, start_time); time(&start_time); phil_take_hashi(env, phil_i); time(&end_time); phil->total_hungry += difftime(end_time, start_time); time(&start_time); phil_eat(phil); time(&end_time); phil->total_eating += difftime(end_time, start_time); phil->times_he_ate++; phil_put_hashi(env, phil_i); if(env->max_runtime > 0) { if(env->runtime >= env->max_runtime) { break; } } } pthread_exit((void*) 0); } void phil_init(env_t* env, int phil_i) { phil_t* phil = &env->phils[phil_i]; phil->id = phil_i + 1; phil->status = THINKING; phil->times_he_ate = 0; phil->total_eating = 0; phil->total_hungry = 0; phil->total_thinking = 0; phil->next_eating = 0; phil->next_thinking = env_rand_time(env); sem_init(&phil->sem, 0, 0); } void phil_init_all(env_t* env) { for(int i = 0; i < env->total_phil; i++) { phil_init(env, i); } } void phil_show(phil_t* phil) { if(phil->status == THINKING) { printf(" %i\t\tpensando\t %i\t\t %i\t\t %i\t\t%i\n", phil->id, phil->total_thinking, phil->total_hungry, phil->total_eating, phil->times_he_ate); } else if(phil->status == HUNGRY) { printf(" %i\t\tfaminto\t\t %i\t\t %i\t\t %i\t\t%i\n", phil->id, phil->total_thinking, phil->total_hungry, phil->total_eating, phil->times_he_ate); } else if(phil->status == EATING) { printf(" %i\t\tcomendo\t\t %i\t\t %i\t\t %i\t\t%i\n", phil->id, phil->total_thinking, phil->total_hungry, phil->total_eating, phil->times_he_ate); } } void phil_think(phil_t* phil) { sleep(phil->next_thinking); } void phil_take_hashi(env_t* env, int phil_i) { sem_wait(&env->mutex); env->phils[phil_i].status = HUNGRY; phil_try(env, phil_i); sem_post(&env->mutex); sem_wait(&env->phils[phil_i].sem); } void phil_try(env_t* env, int phil_i) { phil_t* phils = env->phils; int left = phil_get_left(env, phil_i); int right = phil_get_right(env, phil_i); if(phils[phil_i].status == HUNGRY && phils[left].status != EATING && phils[right].status != EATING) { sem_post(&phils[phil_i].sem); phils[phil_i].next_eating = env_rand_time(env); phils[phil_i].status = EATING; } } void phil_eat(phil_t* phil) { sleep(phil->next_eating); } void phil_put_hashi(env_t* env, int phil_i) { int phil_left = phil_get_left(env, phil_i); int phil_right = phil_get_left(env, phil_i); sem_wait(&env->mutex); env->phils[phil_i].next_thinking = env_rand_time(env); env->phils[phil_i].status = THINKING; phil_try(env, phil_left); phil_try(env, phil_right); sem_post(&env->mutex); } int phil_get_left(env_t* env, int phil_i) { return (phil_i + env->total_phil - 1) % env->total_phil; } int phil_get_right(env_t* env, int phil_i) { return (phil_i + 1) % env->total_phil; } /* Funções do ambiente */ void* env_thread_func(void* arguments) { while(1) { env_t* env = (env_t*) arguments; time_t end_time; time(&end_time); env->runtime = difftime(end_time, env->start_time); env_show(env); sleep(1); } } void env_init(env_t* env) { env->start_time = -1; env->max_rand_time = 5; env->max_runtime = 0; env->min_rand_time = 1; env->runtime = 0; env->total_phil = 5; env->phils = NULL; sem_init(&env->mutex, 0, 1); } void env_show(env_t* env) { system("clear"); printf("Execute com o parâmetro --help para ver a ajuda\n\n"); printf("Executar cada thread "); if(env->max_runtime <= 0) { printf("infinitamente"); } else { printf("por %i segundos", env->max_runtime); } printf(" | Tempo aleatório gerado entre %i e %i segundos\n", env->min_rand_time, env->max_rand_time); printf("Tempo total de execução: %i segundos\n\n", env->runtime); printf(" Filósofo\tStatus\t Pensando\tFaminto\t Comendo\t Vezes Comeu\n"); for(int i = 0; i < env->total_phil; i++) { phil_show(&env->phils[i]); } printf("\n"); } int env_rand_time(env_t* env) { srand(time(NULL)); return (rand() % env->max_rand_time) + env->min_rand_time; }
LuckyChen73/WYNewsClassNine
WYNewsClassNine/WYNewsClassNine/Classes/Tool/WYNetworkTool.h
// // WYNetworkTool.h // WYNewsClassNine // // Created by chenWei on 2017/3/20. // Copyright © 2017年 陈伟. All rights reserved. // #import <AFNetworking/AFNetworking.h> @interface WYNetworkTool : AFHTTPSessionManager //单例 + (instancetype)sharedTool; /** 网络中间层 @param urlStr url 字符串 @param method 请求方式 @param parameters 请求参数 @param callBack 回调 block */ - (void)requestWithURL:(NSString *)urlStr withMethod:(NSString *)method withParameters:(id)parameters withCallBack:(void(^)(id))callBack; @end
LuckyChen73/WYNewsClassNine
WYNewsClassNine/WYNewsClassNine/Classes/Home/ChannelView/WYChannelController.h
<reponame>LuckyChen73/WYNewsClassNine<filename>WYNewsClassNine/WYNewsClassNine/Classes/Home/ChannelView/WYChannelController.h // // WYChannelController.h // WYNewsClassNine // // Created by chenWei on 2017/3/18. // Copyright © 2017年 陈伟. All rights reserved. // #import <UIKit/UIKit.h> @interface WYChannelController : UIViewController @end
LuckyChen73/WYNewsClassNine
WYNewsClassNine/WYNewsClassNine/Classes/Tool/WYNetworkTool+news.h
// // WYNetworkTool+news.h // WYNewsClassNine // // Created by chenWei on 2017/3/20. // Copyright © 2017年 陈伟. All rights reserved. // #import "WYNetworkTool.h" @interface WYNetworkTool (news) /** 获取网易新闻的列表的数据 @param tid tid 字符串 @param callBack 完成回调,将模型数组直接返回 */ - (void)requestNewsListWithTid:(NSString *)tid withCallBack:(void(^)(NSArray *modelArr))callBack; /** 获取网易新闻的详细页的数据 @param docid 新闻的 id @param callBack 完成回调,将处理好的网易新闻的正文 html 字符串返回 */ - (void)requestNewsListWithDetail:(NSString *)docid withCallBack:(void (^)(NSString *bodyStr))callBack; @end
LuckyChen73/WYNewsClassNine
WYNewsClassNine/WYNewsClassNine/Classes/Home/NewDetail/WYDetailController.h
<filename>WYNewsClassNine/WYNewsClassNine/Classes/Home/NewDetail/WYDetailController.h // // WYDetailController.h // WYNewsClassNine // // Created by chenWei on 2017/3/18. // Copyright © 2017年 陈伟. All rights reserved. // #import <UIKit/UIKit.h> #import "WYNewsModel.h" @interface WYDetailController : UIViewController @property (nonatomic, strong) WYNewsModel *newsModel; @end
LuckyChen73/WYNewsClassNine
WYNewsClassNine/WYNewsClassNine/Classes/Home/Home/View/WYChannelView.h
<reponame>LuckyChen73/WYNewsClassNine // // WYChannelView.h // WYNewsClassNine // // Created by chenWei on 2017/3/18. // Copyright © 2017年 陈伟. All rights reserved. // #import <UIKit/UIKit.h> @protocol WYChannelViewDelegate <NSObject> - (void)channelView:(NSInteger)index; @end @interface WYChannelView : UIScrollView @property (nonatomic, weak) id<WYChannelViewDelegate> channelDelegate; @property (nonatomic, strong) NSArray *modelArr; //是否为选中的下标 @property (nonatomic, assign) NSInteger isSelectedIndex; @end
LuckyChen73/WYNewsClassNine
WYNewsClassNine/WYNewsClassNine/Classes/Home/NewList/Other/WYBigImageCell.h
<filename>WYNewsClassNine/WYNewsClassNine/Classes/Home/NewList/Other/WYBigImageCell.h // // WYBigImageCell.h // WYNewsClassNine // // Created by chenWei on 2017/3/20. // Copyright © 2017年 陈伟. All rights reserved. // #import <UIKit/UIKit.h> #import "WYNewsModel.h" @interface WYBigImageCell : UITableViewCell @property (nonatomic, strong) WYNewsModel *newsModel; @end
LuckyChen73/WYNewsClassNine
WYNewsClassNine/WYNewsClassNine/Classes/Home/Home/Model/WYLabel.h
// // WYLabel.h // WYNewsClassNine // // Created by chenWei on 2017/3/18. // Copyright © 2017年 陈伟. All rights reserved. // #import <UIKit/UIKit.h> #import "WYChannelModel.h" @interface WYLabel : UILabel /** 一创建 label 就给 label 赋值 @param model <#model description#> @return <#return value description#> */ + (instancetype)labelWithModel:(WYChannelModel *)model; @property (nonatomic, assign) BOOL isSelected; @end
LuckyChen73/WYNewsClassNine
WYNewsClassNine/WYNewsClassNine/Classes/Home/Home/Model/WYChannelModel.h
// // WYChannelModel.h // WYNewsClassNine // // Created by chenWei on 2017/3/18. // Copyright © 2017年 陈伟. All rights reserved. // #import <Foundation/Foundation.h> @interface WYChannelModel : NSObject //频道id @property (nonatomic, copy) NSString *tid; //频道名字 @property (nonatomic, copy) NSString *tname; /** 获取所有频道模型数据 @return <#return value description#> */ + (NSArray *)channelModel; @end
LuckyChen73/WYNewsClassNine
WYNewsClassNine/WYNewsClassNine/Classes/Home/NewList/Other/WYThreeImageCell.h
// // WYThreeImageCell.h // WYNewsClassNine // // Created by chenWei on 2017/3/20. // Copyright © 2017年 陈伟. All rights reserved. // #import <UIKit/UIKit.h> #import "WYNewsModel.h" @interface WYThreeImageCell : UITableViewCell @property (nonatomic, strong) WYNewsModel *newsModel; @end
LuckyChen73/WYNewsClassNine
WYNewsClassNine/WYNewsClassNine/Classes/Main/WYMainViewController.h
// // WYMainViewController.h // WYNewsClassNine // // Created by chenWei on 2017/3/18. // Copyright © 2017年 陈伟. All rights reserved. // #import <UIKit/UIKit.h> @interface WYMainViewController : UITabBarController @end
LuckyChen73/WYNewsClassNine
WYNewsClassNine/WYNewsClassNine/Classes/Home/Home/WYHomeController.h
<gh_stars>0 // // WYHomeController.h // WYNewsClassNine // // Created by chenWei on 2017/3/18. // Copyright © 2017年 陈伟. All rights reserved. // #import <UIKit/UIKit.h> @interface WYHomeController : UIViewController @end
LuckyChen73/WYNewsClassNine
WYNewsClassNine/WYNewsClassNine/Classes/Home/NewList/WYNewsListController.h
// // WYNewsListController.h // WYNewsClassNine // // Created by chenWei on 2017/3/18. // Copyright © 2017年 陈伟. All rights reserved. // #import <UIKit/UIKit.h> #import "WYChannelModel.h" @interface WYNewsListController : UIViewController @property (nonatomic, strong) WYChannelModel *model; @property (nonatomic, assign) NSInteger index; - (id)initWithIndex:(NSInteger)index withChannelModel:(WYChannelModel *)model; @end
LuckyChen73/WYNewsClassNine
WYNewsClassNine/WYNewsClassNine/Classes/Home/NewList/WYNewsModel.h
<gh_stars>0 // // WYNewsModel.h // WYNewsClassNine // // Created by chenWei on 2017/3/20. // Copyright © 2017年 陈伟. All rights reserved. // #import <Foundation/Foundation.h> @interface WYNewsModel : NSObject //回复数 @property (nonatomic, copy) NSString *replyCount; //文章 id @property (nonatomic, copy) NSString *docid; //是否是头部 @property (nonatomic, assign) BOOL hasHead; //文章标题 @property (nonatomic, copy) NSString *title; //新闻 url @property (nonatomic, copy) NSString *url; //新闻来源 @property (nonatomic, copy) NSString *source; //是否是大图 @property (nonatomic, assign) BOOL imgType; //图片地址 @property (nonatomic, copy) NSString *imgsrc; //是否是第一张图片的其余图片 @property (nonatomic, strong) NSArray *imgExtra; @end
HFTrader/fecpp
fecpp.h
/* * Forward error correction based on Vandermonde matrices * * (C) 1997-1998 <NAME> (<EMAIL>) * (C) 2009 <NAME> (<EMAIL>) * * Distributed under the terms given in license.txt */ #ifndef FECPP_H_ #define FECPP_H_ #include <map> #include <vector> #include <functional> #include <cstdint> namespace fecpp { using std::uint8_t; using std::size_t; using byte = std::uint8_t; #if defined(__i386__) || defined(__x86_64__) #define FECPP_IS_X86 #endif /** * Forward error correction code */ class fec_code { public: /** * fec_code constructor * @param K the number of shares needed for recovery * @param N the number of shares generated */ fec_code(size_t K, size_t n); size_t get_K() const { return K; } size_t get_N() const { return N; } /** * @param input the data to FEC * @param size the length in bytes of input * @param out the output callback */ void encode( const uint8_t input[], size_t size, std::function<void (size_t, size_t, const uint8_t[], size_t)> out) const; /** * @param shares map of share id to share contents * @param share_size size in bytes of each share * @param out the output callback */ void decode( const std::map<size_t, const uint8_t*>& shares, size_t share_size, std::function<void (size_t, size_t, const uint8_t[], size_t)> out) const; private: size_t K, N; std::vector<uint8_t> enc_matrix; }; #if defined(FECPP_IS_X86) /** * CPU runtime detection */ bool has_sse2(); bool has_ssse3(); size_t addmul_sse2(uint8_t z[], const uint8_t x[], uint8_t y, size_t size); size_t addmul_ssse3(uint8_t z[], const uint8_t x[], uint8_t y, size_t size); #endif } #endif
icanzilb/RealmNotificationExample
Pods/Target Support Files/Pods-FineNotifications/Pods-FineNotifications-umbrella.h
#ifdef __OBJC__ #import <UIKit/UIKit.h> #endif FOUNDATION_EXPORT double Pods_FineNotificationsVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_FineNotificationsVersionString[];
gabrielefronze/TSystFitter
TSystFitSettings.h
<gh_stars>0 // // Created by <NAME> on 25/06/2017. // #ifndef TSYSTFITTER_TSYSTFITSETTIGNS_H #define TSYSTFITTER_TSYSTFITSETTIGNS_H #include "Rtypes.h" #include "TSystFitParameter.h" #include "TF1.h" #include <utility> #include <vector> class TSystFitSettings { public: explicit TSystFitSettings(Int_t fNParams = 0); explicit TSystFitSettings(std::vector<TSystFitParameter> params) : fParams(std::move(params)){}; explicit TSystFitSettings(TF1 funcky, std::vector<int> nSamples); void GenerateConfigurations(); inline void AddParameter(const TSystFitParameter &param){ fParams.push_back(param); }; Bool_t SetParameter(ULong_t iParam, TSystFitParameter param); TSystFitParameter GetParameter(Int_t iParam){ return fParams[iParam]; }; inline ULong_t GetNParams(){ return (ULong_t)fParams.size(); }; ULong_t GetNConfigurations(); std::vector<ParamValue> GetConfiguration(unsigned long iConfig); private: std::vector<TSystFitParameter> fParams; std::vector<std::vector<int>> fConfigurations; }; #endif //TSYSTFITTER_TSYSTFITSETTIGNS_H
gabrielefronze/TSystFitter
TSystFitParameter.h
<reponame>gabrielefronze/TSystFitter // // Created by <NAME> on 25/06/2017. // #ifndef TSYSTFITTER_TSYSTFITPARAMETER_H #define TSYSTFITTER_TSYSTFITPARAMETER_H #include "TF1.h" #include <utility> #include <vector> enum ParamType{ kCustom, kFix, kUniform, kNoType }; struct ParamValue{ Double_t fValue; Double_t fUpperLimit; Double_t fLowerLimit; ParamValue(){ fValue = 0.; fUpperLimit = 0.; fLowerLimit = 0.; } explicit ParamValue(Double_t value){ fValue = value; fUpperLimit = value; fLowerLimit = value; } explicit ParamValue(Double_t value, Double_t lowerLimit, Double_t upperLimit){ fValue = value; fUpperLimit = upperLimit; fLowerLimit = lowerLimit; } explicit ParamValue(const Double_t data[3]){ fValue = data[0]; fUpperLimit = data[2]; fLowerLimit = data[1]; } }; class TSystFitParameter { public: TSystFitParameter() : fParamType(kNoType){}; explicit TSystFitParameter(TF1 *funcky, Int_t nSamples); explicit TSystFitParameter(ParamValue paramValue, Int_t nSamples); inline const ULong_t GetNValues(){ return fParamValues.size(); }; inline const ParamType GetType(){ return fParamType; }; inline const ParamValue GetValue(UInt_t index=0){ return (index<fParamValues.size()) ? fParamValues[index] : ParamValue(0.,0.,0.); }; inline TF1* GetFuncky(){ return new TF1(*fSampledFuncky); }; private: std::vector<ParamValue> fParamValues; ParamType fParamType; TF1 *fSampledFuncky; }; #endif //TSYSTFITTER_TSYSTFITPARAMETER_H